为什么我的 git 预提交钩子没有从行尾修剪白色 space?

Why isn't my git pre-commit hook trimming white space from the end of lines?

我在 Mac 莫哈韦沙漠。我在 ~/.git-templates/hooks/pre-commit 创建了一个文件,我想从我提交的文件的行尾删除白色 space 。我希望这在全球范围内发生,在我所有的项目中。

# A git hook script to find and fix trailing whitespace in your commits. Bypass
# it with the --no-verify option to git-commit.

# detect platform
platform="win"
uname_result=`uname`
if [[ "$uname_result" == "Linux" ]]; then
  platform="linux"
elif [[ "$uname_result" == "Darwin" ]]; then
  platform="mac"
fi

# change IFS to ignore filename's space in |for|
IFS="
"

# remove trailing whitespace in modified lines
for line in `git diff --check --cached | sed '/^[+-]/d'` ; do
  # get file name
  if [[ "$platform" == "mac" ]]; then
    file="`echo $line | sed -E 's/:[0-9]+: .*//'`"
    line_number="`echo $line | sed -E 's/.*:([0-9]+).*//'`"
  else
    file="`echo $line | sed -r 's/:[0-9]+: .*//'`"
    line_number="`echo $line | sed -r 's/.*:([0-9]+).*//'`"
  fi

  # since $file in working directory isn't always equal to $file in index,
  # we backup it; thereby we can add our whitespace fixes without accidently
  # adding unstaged changes
  backup_file="${file}.working_directory_backup"
  cat "$file" > "$backup_file"
  git checkout -- "$file" # discard unstaged changes in working directory

  # remove trailing whitespace in $file (modified lines only)
  if [[ "$platform" == "win" ]]; then
    # in windows, `sed -i` adds ready-only attribute to $file (I don't kown why), so we use temp file instead
    sed "${line_number}s/[[:space:]]*$//" "$file" > "${file}.bak"
    mv -f "${file}.bak" "$file"
  elif [[ "$platform" == "mac" ]]; then
    sed -i "" "${line_number}s/[[:space:]]*$//" "$file"
  else
    sed -i "${line_number}s/[[:space:]]*$//" "$file"
  fi
  git add "$file" # to index, so our whitespace changes will be committed

  # restore unstaged changes in $file from its working directory backup, fixing
  # whitespace that we fixed above
  sed "${line_number}s/[[:space:]]*$//" "$backup_file" > "$file"
  rm "$backup_file"

  [[ "$platform" == "mac" ]] || e_option="-e" # mac does not understand -e
  echo $e_option "Removed trailing whitespace in 3[31m$file3[0m:$line_number"
done

echo

# credits:
# https://github.com/philz/snippets/blob/master/pre-commit-remove-trailing-whitespace.sh
# https://github.com/imoldman/config/blob/master/pre-commit.git.sh

# If there still are whitespace errors, print the offending file names and fail.
exec git diff-index --check --cached $against --

# Now we can commit
exit

所以问题是它没有修剪行尾的白色 space。当我在提交后打开我的文件时,我仍然看到白色 space。所以我的问题是如何解决这个问题?我是不是把挂钩放在了错误的位置,还是我的文件中还需要做其他事情?

首先,确保挂钩位于全局挂钩路径 (available since Git 2.9) 引用的文件夹中

git config --global core.hooksPath /path/to/my/centralized/hooks

然后,检查 pre-commit 挂钩是否可执行,并实际运行:在开始处添加至少一个 echo,以验证其在提交时的执行。

关于您的脚本:在退出前的最后一条指令中,您可能想调用 git diff 而不是 git diff-index,不是吗?


关于行动"removing trailing whitespaces from my files before committing":

  • 大多数编辑器允许 运行 在文件保存时执行此操作,这可能是从您自己编辑的文件中删除尾随空格的最简单方法

  • 使用 git 特定触发器:更适合的方法是在 git 属性中使用干净的过滤器(参见 Keyword Expansion 部分 git本书):

这将在您 "git add" 每个文件时应用更改,而不是在您提交时应用更改:

# choose a name for your filter (e.g : 'trimspace'), and write
# the two 'clean' and 'smudge' action :
$ git config filter.trimspace.clean 'sed -e "s/[[:space:]]*$//g"'
$ git config filter.trimspace.smudge cat

# edit the `.gitattributes` file at the root of your repo,
# and target all the files you may want to trim :
$ cat .gitattributes
*.txt filter=trimspace
*.c filter=trimspace
*.py filter=trimspace
...

# from now on : running `git add` will auto trim targeted files when
# they are added to the index

变量 $against 似乎在这里引起了问题。 $against 变量未在此处初始化,这似乎是失败的原因。

正如您提到的那样,您的代码死于该行。如果我删除行 exec git diff-index --check --cached $against --,您的代码执行正常(没有错误情况)。

来到那个特定的行:如果其中仍有空格,该行用于打印出任何行。但是,我发现代码是部分编写的。

完整代码需要为:

#!/bin/sh
#
# This hook script verifies that there are no whitespace errors in the files to be committed

if git rev-parse --verify HEAD >/dev/null 2>&1
then
 against=HEAD
else
 # Initial commit: diff against an empty tree object
 against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

# Redirect output to stderr.
exec 1>&2

# If there are whitespace errors, print the offending file names and fail.
exec git diff-index --check --cached $against --

代码可以在 this 站点找到。

您需要在最后一行进行比较,但 $against 未定义。如果 HEAD 不存在,此代码会将其正确定义为 HEAD 或某个虚拟树对象。

添加此代码后,它在我的系统中正常运行(Ubuntu 16.04LTS,Git 版本 2.7.4)

尝试添加完整代码,让我知道它是否适合您。

谢谢

$against 未定义。从官方添加以下内容pre-commit.sample

if git rev-parse --verify HEAD >/dev/null 2>&1
then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=$(git hash-object -t tree /dev/null)
fi