Skip to content

Instantly share code, notes, and snippets.

@binderclip
Last active October 20, 2019 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binderclip/5bd466d5dd0519c3e0d5dfdbc0cc84e6 to your computer and use it in GitHub Desktop.
Save binderclip/5bd466d5dd0519c3e0d5dfdbc0cc84e6 to your computer and use it in GitHub Desktop.
#!/bin/sh
exit_code=0
goimports_fix() {
hash goimports 2>&- || { echo >&2 "goimports not in PATH."; exit 1; }
for file in `git diff --cached --name-only --diff-filter=d | grep -v vendor | grep '\.go$'`
do
if [[ ! -z `git diff --name-only ${file} | grep '\.go$'` ]]
then
# goimports check staged file which has unstaged changes
ERROR=$(git cat-file -p :${file} | goimports -l ${file} 2>&1 >/dev/null)
if [[ ! -z ${ERROR} ]]
then
echo goimports ${file} meet error:
echo ${ERROR}
exit_code=1
else
if [[ ! -z `git cat-file -p :${file} | goimports -l 2>/dev/null` ]]
then
echo ${file} should be goimports, please check and fix it and stage changes
exit_code=1
fi
fi
else
# goimports check and fix file which dose not have unstaged changes
ERROR=$(goimports -l ${file} 2>&1 >/dev/null)
if [[ ! -z ${ERROR} ]]
then
echo goimports ${file} meet error:
echo ${ERROR}
exit_code=1
else
if [[ ! -z `goimports -l ${file} 2>/dev/null` ]]
then
`goimports -w ${file}`
echo ${file} goimports auto fixed, please stage the changes
exit_code=1
fi
fi
fi
done
}
goimports_fix
if [[ ${exit_code} == 1 ]]; then
echo "\ncommit stopped, check the above log, fix, add, recommit"
fi
exit ${exit_code}
@binderclip
Copy link
Author

binderclip commented Oct 20, 2019

在 commit 之前对修改过的 go 文件执行 goimports,如果会有改动就会报错并停止 commit,同时如果没有未 stage 的改动会直接用 goimports 修改文件。

# 下载 pre-commit hook
cd ~/.gittemplates/hooks/
curl https://gist.githubusercontent.com/binderclip/5bd466d5dd0519c3e0d5dfdbc0cc84e6/raw/pre-commit -O
chmod 755 pre-commit

# 新项目创建的时候会自动复制过去

# 旧项目可以手动拷贝过去
cd YOUR_GO_PROJECT_PATH
cp ~/.gittemplates/hooks/* .git/hooks/

refs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment