Skip to content

Instantly share code, notes, and snippets.

@mniak
Last active November 23, 2021 17:54
Show Gist options
  • Save mniak/f53345fdb4f54281b54674904340e4b1 to your computer and use it in GitHub Desktop.
Save mniak/f53345fdb4f54281b54674904340e4b1 to your computer and use it in GitHub Desktop.
Format Go files on pre-commit hook

Setup

curl -sL https://git.io/J1K67 | bash

What this will do?

  • Run the file setup.sh from this gist, that performs the following tasks:
    • Download the file lefthook.yml from this gist
    • Download the file prepare.sh from this gist
    • Add executable permissions to prepare.sh
    • Run the script prepare.sh. It does the following:
      • Installs the program gofumpt
      • Installs the program lefthook
      • Execute lefthook install for configuring the git hooks

Tools of choice

Lefthook

Git hooks manager

More at https://github.com/evilmartians/lefthook

gofumpt

Go formatter

More at https://github.com/mvdan/gofumpt

pre-commit:
parallel: true
commands:
gofumpt:
glob: "*.go"
run: |
git stash -q --keep-index # stash unstaged changes
gofumpt -w {staged_files} # format staged files
git add -u # stage formatting
git stash pop -q # reapply stashed
#!/bin/bash
goInstallStatus() {
cmdname=$1
color=$2
status=$3
extra=$4
tput init
echo -n "Command "
tput bold
tput setaf 7
echo -n ${cmdname}
tput init
echo -n ": "
tput setaf $color
echo -n $status
tput init
echo " $extra"
tput dim
}
goInstall() {
cmdname=$1
package=$2
if command -v ${cmdname} &> /dev/null; then
goInstallStatus "$cmdname" 2 "FOUND!"
else
goInstallStatus "$cmdname" 1 "NOT FOUND!" "Installing..."
if go install ${package}@latest; then
goInstallStatus "$cmdname" 2 "INSTALLED!"
else
goInstallStatus "$cmdname" 1 "INSTALLATION FAILED!"
fi
fi
tput init
}
step() {
message=$1
length=${#message}
echo ""
echo $message
for ((i=0; i<$length; i++)); do echo -n "-"; done
echo ""
}
step "Installing dependencies..."
goInstall "lefthook" "github.com/evilmartians/lefthook"
goInstall "gofumpt" "mvdan.cc/gofumpt"
step "Enabling git hooks..."
lefthook install
#!/bin/bash
# curl -sL https://git.io/J1K67 | bash
curl -o lefthook.yml https://gist.githubusercontent.com/mniak/f53345fdb4f54281b54674904340e4b1/raw/lefthook.yml
curl -o prepare.sh https://gist.githubusercontent.com/mniak/f53345fdb4f54281b54674904340e4b1/raw/prepare.sh
chmod +x prepare.sh
./prepare.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment