0

我按照本指南创建 git pre-commit hooks,到目前为止,我真的很喜欢它给我带来的好处。

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

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

当我提交时,我的脚本只获取 中的已更改文件列表,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 and git diff --name-only --diff-filter=M中,如果是这样就退出。

欢迎提出其他建议。

4

1 回答 1

2

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

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

于 2013-08-08T20:29:34.953 回答