Skip to content

Instantly share code, notes, and snippets.

@anatolebeuzon
Last active May 13, 2022 14:33
Show Gist options
  • Save anatolebeuzon/655c8df8d08fe7695fe25591f1308de7 to your computer and use it in GitHub Desktop.
Save anatolebeuzon/655c8df8d08fe7695fe25591f1308de7 to your computer and use it in GitHub Desktop.
Auto-vendor Go dependencies in the background after a git checkout

Why?

Having to run go mod vendor every time I git checkout <branch> is annoying. If I forget, gopls is unusable, tests cannot be run, and VSCode complains (go: inconsistent vendoring).

What?

Add a post-checkout hook that will run go mod vendor in the background every time a branch is checked out.

How to add the hook?

Several ways possible. I chose one that allows me to keep all my Git config in one place. (Alternative: put the git config directly in your repo)

  1. Add this to your global .gitconfig:
[includeIf "gitdir:~/path/to/your/go/repo/"]
	path = .gitconfig-go
  1. Add a .gitconfig-go file just next to it:
[core]
	hooksPath = ~/path/to/git-go-hooks-folder
  1. Create the git-go-hooks-folder folder and insert the post-checkout file attached

How to confirm that it works?

git checkout a branch, then tail vendor.log

Limitations

It does not work on all git operations that might require a go mod vendor (e.g. you might have to run go mod vendor yourself after a rebase).

#!/bin/bash
set -e
prevHEAD=$1
newHEAD=$2
checkoutType=$3
branchName=$(git branch --show-current)
if [[ $checkoutType == 1 ]] && checkoutType='branch' \
&& [[ ! -z "$branchName" ]]; # disable this hook when rebasing
then
echo 'Will vendor Go dependencies in the background'
log_file="$(git rev-parse --show-toplevel)/vendor.log"
echo "$(date): on branch $branchName, running 'go mod vendor'" >> $log_file
# Must close stdout & stderr pipes for proper backgrounding, see https://stackoverflow.com/a/17733087/3865626
((go mod vendor 2>> $log_file) && (echo "$(date): done." >> $log_file)) >&- 2>&- &
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment