从预提交挂钩中排除某些文件类型

Tim*_*Tim 2 git bash pre-commit-hook

我想要一个预提交 git 钩子来检查(如果可能的话,自动删除)尾随空格。

\n

让 git 在提交之前自动删除尾随空格中,我找到了一个 github 页面的链接,其中实现了这样的钩子。这工作正常,但正如该页面上的@VonC\n提到的

\n
\n

由于该挂钩获取每个文件的文件名,因此我建议\n小心某些类型的文件:您不想删除\n.md(markdown)文件中的尾随空格!\xe2\x80\x93 VonC

\n
\n

再往下

\n
\n

我宁愿让钩子能够检测 .md 文件而不删除空格,而不是要求最终用户在 git 提交上添加 --no-verify 选项。\xe2\x80\x93 VonC

\n
\n

据我所知,没有提到解决方案。

\n

由于我在项目中使用 .md 文件并故意使用尾随空格,因此这对我来说是一个问题。
\n解决方案可能很简单,但我对编写脚本所用的语言没有经验(目前也没有兴趣学习它)。

\n

这是脚本(github 的副本):

\n
#!/bin/bash\n#\n\n# A git hook script to find and fix trailing whitespace\n# in your commits. Bypass it with the --no-verify option\n# to git-commit\n#\n# usage: make a soft link to this file, e.g., ln -s ~/config/pre-commit.git.sh ~/some_project/.git/hooks/pre-commit\n\n# detect platform\nplatform="win"\nuname_result=`uname`\nif [ "$uname_result" = "Linux" ]; then\n  platform="linux"\nelif [ "$uname_result" = "Darwin" ]; then\n  platform="mac"\nfi\n\n# change IFS to ignore filename\'s space in |for|\nIFS="\n"\n# autoremove trailing whitespace\nfor line in `git diff --check --cached | sed \'/^[+-]/d\'` ; do\n  # get file name\n  if [ "$platform" = "mac" ]; then\n    file="`echo $line | sed -E \'s/:[0-9]+: .*//\'`"\n  else\n    file="`echo $line | sed -r \'s/:[0-9]+: .*//\'`"\n  fi  \n  # display tips\n  echo -e "auto remove trailing whitespace in \\033[31m$file\\033[0m!"\n  # since $file in working directory isn\'t always equal to $file in index, so we backup it\n  mv -f "$file" "${file}.save"\n  # discard changes in working directory\n  git checkout -- "$file"\n  # remove trailing whitespace\n  if [ "$platform" = "win" ]; then\n    # in windows, `sed -i` adds ready-only attribute to $file(I don\'t kown why), so we use temp file instead\n    sed \'s/[[:space:]]*$//\' "$file" > "${file}.bak"\n    mv -f "${file}.bak" "$file"\n  elif [ "$platform" == "mac" ]; then\n    sed -i "" \'s/[[:space:]]*$//\' "$file"\n  else\n    sed -i \'s/[[:space:]]*$//\' "$file"\n  fi  \n  git add "$file"\n  # restore the $file\n  sed \'s/[[:space:]]*$//\' "${file}.save" > "$file"\n  rm "${file}.save"\ndone\n\nif [ "x`git status -s | grep \'^[A|D|M]\'`" = "x" ]; then\n  # empty commit\n  echo\n  echo -e "\\033[31mNO CHANGES ADDED, ABORT COMMIT!\\033[0m"\n  exit 1\nfi\n\n# Now we can commit\nexit\n
Run Code Online (Sandbox Code Playgroud)\n

如何修改它以便(例如).md 文件被排除在检查中?另外,如果可以排除多种文件类型,那就太好了。

\n

ser*_*inc 5

您可以使用预提交。最简单的配置是

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.2.0
    hooks:
      - id: trailing-whitespace
        args: [--markdown-linebreak-ext=md]
Run Code Online (Sandbox Code Playgroud)

查看其他钩子,例如检测合并冲突的钩子。