【问题标题】:pre-commit hook doesn't check if saved changes are staged before running预提交钩子不检查保存的更改是否在运行前暂存
【发布时间】:2013-08-08 19:06:45
【问题描述】:

我关注了this guide on creating git pre-commit hooks,到目前为止,我真的很喜欢它给我带来的好处。

但是,我在使用的时候遇到了问题:

  1. 我写了一些代码,也许是一些没有通过 rubocop 检查的代码。
  2. 我暂存它,然后尝试提交它。预提交挂钩按预期工作。
  3. 我去解决 rubocop 报告的问题。
  4. 我保存了更改,但忘记将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


【解决方案1】:

如果我正确理解了您的问题,您需要有文件,因为它们在手头的索引中。

为此,您可以在运行实用程序之前执行git stash -k(保持索引),然后假设它不会更改任何内容,以便不会出现任何冲突。

【讨论】:

  • 这是一个开始。它不会评估任何不在暂存中的东西(这很好),但它似乎确实丢弃了我忘记暂存的任何更改,需要我重写它们。
  • git stash pop 应该带回在工作树中所做的所有更改,但未添加到提交中。它对你有用吗?
  • 是的,我想我在运行git stash pop 或其他东西时可能错过了exit [0|1],因为它现在好多了。我的 bash 很糟糕,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-17
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多