【发布时间】:2013-08-08 19:06:45
【问题描述】:
我关注了this guide on creating git pre-commit hooks,到目前为止,我真的很喜欢它给我带来的好处。
但是,我在使用的时候遇到了问题:
- 我写了一些代码,也许是一些没有通过 rubocop 检查的代码。
- 我暂存它,然后尝试提交它。预提交挂钩按预期工作。
- 我去解决 rubocop 报告的问题。
- 我保存了更改,但忘记将
add发送到索引。
当我提交时,我的脚本只获取git diff --cached --name-only --diff-filter=AM 中已更改文件的列表,在每个文件上运行 rubocop,如果有任何问题则退出。
这是我的脚本:
#!/bin/sh
# Set the ruby environment from local/rvm, depending on your machine.
# http://stackoverflow.com/questions/17515769
if [ -d "$HOME/.rvm/bin" ]; then
PATH="$HOME/.rvm/bin:$PATH"
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
if [ -f ".ruby-version" ]; then
rvm use "$(cat .ruby-version)"
fi
if [ -f ".ruby-gemset" ]; then
rvm gemset use "$(cat .ruby-gemset)"
fi
fi
# http://codeinthehole.com/writing/tips-for-using-a-git-pre-commit-hook/
FILES_PATTERN='\.rb(\..+)?$'
FORBIDDEN='debug'
# Quit if no ruby files are being checked in.
RB_FILES=$(git df --cached --name-only --diff-filter=AM | grep -Ec $FILES_PATTERN)
if [ "$RB_FILES" = "0" ]; then
exit 0
fi
git diff --cached --name-only --diff-filter=AM | \
grep -E $FILES_PATTERN | \
GREP_COLOR='37;41' xargs grep --color --with-filename -n $FORBIDDEN && \
echo 'Please remove debugging statements before commiting.' && exit 1
# Pull in altered files, check with rubocop.
git diff --cached --name-only --diff-filter=AM | \
grep -E $FILES_PATTERN | xargs rubocop -f simple | \
grep 'no offences detected' && exit 0
# If it didn't exit 0 above, warn of issues, output results.
echo 'Rubocop has detected issues with your commit.' && \
git diff --cached --name-only --diff-filter=AM | \
grep -E $FILES_PATTERN | xargs rubocop -f simple && exit 1
我不想使用sed 来解析git diff 的结果。有没有更简单的方法来确保我检查的是 index,而不是磁盘上显示的文件?
我的直觉告诉我,可能有办法检查git diff --name-only --cached --diff-filter=M 和 git diff --name-only --diff-filter=M 中是否有任何文件,如果是这样就退出。
欢迎提出其他建议。
【问题讨论】:
-
嗨,如果你还有这段代码,如果你能更新它,我会很高兴。
标签: git bash githooks pre-commit