Showing posts with label bash. Show all posts
Showing posts with label bash. Show all posts

Monday 20 February 2023

Running eclint locally in development environment

If you have come accross eclint in Azure Devops or in other scenarios, you might want to run this in local development instead to get your linting return an error, possible crashing the build pipeline in Azure Devops. Eclints checks the .editorconfig file of your VS solution and reports if your code is badly formatted according to this file code style rules. Here is a typical eclint setup written with YAML
 
 # Runs ECLINT CHECK. This verfies that code conforms to editor config file.
parameters:
  lintingResultArtifactName: 'LINTING' # Name of published artifact with results.

steps:
- task: Bash@3
  displayName: 'Template steps-linting'
  inputs:
    targetType: 'inline'
    script: 'echo Template steps linting'
- task: Bash@3
  displayName: 'Install ECLINT'
  inputs:
    targetType: 'inline'
    script: |
        sudo npm install -g eclint
    failOnStderr: false
- task: Bash@3
  displayName: 'ECLINT check'
  inputs:
    targetType: 'inline'
    script: |
      eclint check $(git ls-files -- . ':!:*.sln' . ':!:*.sln.DotSettings') > $(Build.ArtifactStagingDirectory)/eclint.txt 2>&1
      file=$(Build.ArtifactStagingDirectory)/eclint.txt
      if [ -s "$file" ]
      then
        echo " ECLint reported errors - build failed 😔" 1>&2
        cat $file
        exit 1
      else
        echo " No errors found. You did good 👍 "
        exit 0
      fi
    failOnStderr: false
- task: PublishBuildArtifacts@1
  displayName: 'Publish artifact'
  condition: succeededOrFailed()
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)'
    ArtifactName: ${{ parameters.lintingResultArtifactName }}
    publishLocation: 'Container'


 
The following shell script can be run with Git Bash in for example Windows environments to run eclint locally.
 
 #!/bin/bash

GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color

exists() {
    command -v "$1" > /dev/null 2>&1
}

runEcLint(){
    echo -e "Starting up eclint linting the files of the solution! ${GREEN}[SUCCESS]${NC} Current folder:"
    pwd
    eclint check $(git ls-files -- . ':!:*.sln' . ':!:*.sln.DotSettings') > eclint.txt 2>&1
    file=eclint.txt
    if [ -s "$file" ]
    then
        echo " ECLint reported errors - build failed 😔" 1>&2
        cat $file
        echo -e "ECLint command reported a ${RED}[FAIL]${NC}. Correct the errors."
        rm eclint.txt
        exit 1
    else
        echo " No errors found. You did good 👍 "
        echo -e "ECLint command reported a ${GREEN}][SUCCESS]${NC}"
        rm eclint.txt
        exit 0
    fi
}

echo "Running eclint locally to check the solution. Checking LOCALDEV environment.."

echo "Checking that npm is installed globally.. "
if  ! [[ "exists npm" ]]; then
    echo -e "Npm is not installed globally. ${RED} [FAIL]${NC}"
    echo "Install npm globally first before running this script! See: https://nodejs.org/en/download/"
    echo "Recommended next step: Install LTS of jnodejs together with npm"
    exit 1
else
    echo -e "You have already installed npm (globally). ${GREEN} [SUCCESS]${NC}"
fi

echo "Checking that eclint is installed globally.. "
if  !  [[ "exists eclint" ]]; then
    echo -e "eclint is not installed globally. ${RED} [FAIL]${NC}"
    echo "Make sure you run this script with sufficient access : Attempting to install eclint globally next."
    echo "Trying to run this command to install eclint: npm install eclint -g"
    npm install -g eclint
    echo -e "\neclint should now be installed. Continuing! ${GREEN} [SUCCESS]${NC}"
else
    echo -e "You have already installed eclint (globally). ${GREEN} [SUCCESS]${NC}"
fi

echo "Switching up a folder to run at root folder of the source.."
pushd ..
echo -e "Switched to parent folder ${GREEN}[SUCCESS]${NC}"

runEcLint

popd #back to the eclint folder
  
 
In case you are running WSL, chances are that you must check if a command is available like this: if ! [ -x "$(command -v npm)" ]; then Also, you might need to add 'sudo' before the npm install -g command. The following launch.json file shows how you can debug inside VsCode Bash scripts, using extension Bash Debug for VsCode.
 
 {
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "bashdb",
            "request": "launch",
            "name": "Bash-Debug",
            "cwd": "${workspaceFolder}",
            "program": "${file}",
            "args": []
            }
    ]
}
 
I tested the script against a solution at work and it spotted the intended eclint warnings for multiple files, as a proof of concept. This makes it easier to fix up eclint errors before pushing them to Azure Devops !

Friday 29 March 2019

Quickly search your Git log using wildcards and shell function

Imagine you got a Git repository with a long history - equivalent to log - and you want find a changeset with a comment containing a word or some words and you want to get the commit SHA to quickly cherry pick that commit to your target branch. This is easier using Azure Devops or some tool, but how to quickly search the log. First we define a search log shell function inside our git config file .gitconfig :

searchlog = "!f() { git --no-pager log --color-words --all --decorate --graph -i --grep \"$1\";  }; f"

Now we can search the log quickly using a wildcard:
git searchlog "visning.*av.*nåtidslinje.*"
We separate our search words with the .* regex syntax and we can search our git log for multiple keywords quickly and get a nice presentation of commits with commit messages matching our log. And now we have a quick way to find our Git commits through the log and the command line to overcome our needly in the haystack scenario.

Thursday 6 September 2018

Some handy Git tips - show latest commits and searching the log and more

This article will present some tips around Git and how you can add functionality for showing the latest commits and search the log. I would like to search these aliased command to show you how they can ease your everyday use of Git from the commandline.

[alias]

glog = log --all --decorate --oneline --graph

glogf = log --all --decorate --oneline --graph --pretty=fuller

st = status

out      = !git fetch && git log FETCH_HEAD..

outgoing = !git fetch && git log FETCH_HEAD..

in       = !git fetch && git log ..FETCH_HEAD

incoming = !git fetch && git log ..FETCH_HEAD

com = "!w() { git commit --all --message \"$1\";  }; w"

undopush = "!w() { git revert HEAD~\"$1\"..HEAD;  }; w"

searchlog = "!f() { git --no-pager log --color-words --all --decorate --graph -i --grep \"$1\";  }; f"

branches =  branch --verbose --sort=-committerdate --format '%(HEAD)%(color:yellow)%(refname:short)%(color:reset) -%(color:red)%(objectname:short)%(color:reset) - %(contents:subject) -%(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'

allbranches = "!g() { git branch --all --verbose --sort=-committerdate --format '%(HEAD) %(color:yellow)%(refname:short)%(color:reset) -%(color:red)%(objectname:short)%(color:reset) - %(contents:subject) -%(authorname) (%(color:green)%(committerdate:relative)%(color:reset))' --color=always | less -R;  }; g"
verify = fsck
clearlocal = clean -fd && git reset 
stash-unapply = !git stash show -p | git apply -R 
lgb = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset%n' --abbrev-commit --date=relative --branches tree = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset%n' --abbrev-commit --date=relative --branches alltree = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset%n' --date=relative --branches --all
latest = "!f() { echo "Latest \"${1:-11}\" commits accross all branches:"; git log  --abbrev-commit --date=relative --branches --all --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset%n' -n ${1:-11};  } ; f"
add-commit = !git add -A && git commit
showconfig = config --global -e

[merge]
tool = kdiff3

[mergetool "kdiff3"]
cmd = \"C:\\\\Program Files\\\\KDiff3\\\\kdiff3\" $BASE $LOCAL $REMOTE -o $MERGED [core]
editor = 'c:/program files/sublime text 3/subl.exe' -w

[core]
editor = 'c:/Program Files/Sublime Text 3/sublime_text.exe'

The best aliases are how you set up Sublime Text 3 as the Git editor and also how you can show the latest commits. The latest commits use a parametrized shell function. I set the default value to 11 in this case, if you do not give a parameter. You can for example show the latest 2 commits by typing: git latest 2
latest = "!f() { echo "Latest \"${1:-11}\" commits accross all branches:"; git log  --abbrev-commit --date=relative --branches --all --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset%n' -n ${1:-11};  } ; f"
Note the use of a shell function and also that we refer to the first parameter as ${1} i bash shell script, with a :-11 to set the first param as 11. The syntax is ${n:-p} where n is the nth parameter (not starting with zero!) and p is the default value. A special syntax, but that is how bash works. Also note that a git alias with a shell function can do multiple functions, separated with semi-colon ;. The searchlog alias / shell function is also handy:
searchlog = "!f() { git --no-pager log --color-words --all --decorate --graph -i --grep \"$1\";  }; f"
Also, multiple aliases here are similar to Mercurial's in and out commands to detect incoming pushed commits and outgoing local commits. Happy Git-ing!

Friday 8 December 2017

Finding old Git Branches with WSL and Bash

Finding old branches in Git

I had to find out which branches in a Git repository was old and output it to a file. An old branch is defined to have no commits the last four months. Here is the bash script I ended up with.




#!/bin/bash

resolveOldBranches(){
branchfile="oldbranches.txt"
declare -i branchiteration=0
branchcount=$(git branch -a | wc -l)

if [ ! -e $branchfile ] ; then
 touch $branchfile
fi

#empty the oldbranch file
: > $branchfile

for k in $(git branch -a | sed /\*/d); do


 if [ -z "$(git log -1 --since='4 months ago' -s $k)" ]; then
  echo $k | cut -d/ -f3 >> $branchfile
 fi
 branchiteration=$branchiteration+1
 percentage= bc <<< "scale=2;($branchiteration/$branchcount)*100"


 read -n 1 -t 0.1 input                  # so read doesn't hang
   if [[ $input = "q" ]] || [[ $input = "Q" ]]
   then
      echo # to get a newline after 
echo -e "XXX\n$($percentage)\nAnalyzing $branchiteration of $branchcount $(bc <<< "scale=2;($branchiteration/$branchcount)*100") % done. \n(Exit: Q/q)... \nXXX"

done | whiptail --title "Resolving OpPlan 4 branch ages" --gauge "Analyzing.. (Press Q or q to exit)" 10 60 0


}

resolveOldBranches
cat $branchfile