gpt4 book ai didi

git - 从预提交 Hook 中排除某些文件类型

转载 作者:行者123 更新时间:2023-12-03 09:23:18 25 4
gpt4 key购买 nike

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

Make git automatically remove trailing whitespace before committing我找到了link to a github page实现这样一个钩子(Hook)的地方。这工作正常,但正如@VonC该页面上提及

Since that hook gets the file name of each file, I would recommend tobe careful for certain type of files: you don't want to removetrailing whitespace in .md (markdown) files! – VonC

再往下

I would rather make the hook able to detect .md file and not removethe whitespaces, rather than asking the end user to add a --no-verifyoption on the git commit. – VonC

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

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

这是脚本(github 的副本):

#!/bin/bash
#

# A git hook script to find and fix trailing whitespace
# in your commits. Bypass it with the --no-verify option
# to git-commit
#
# usage: make a soft link to this file, e.g., ln -s ~/config/pre-commit.git.sh ~/some_project/.git/hooks/pre-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="
"
# autoremove trailing whitespace
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]+: .*//'`"
else
file="`echo $line | sed -r 's/:[0-9]+: .*//'`"
fi
# display tips
echo -e "auto remove trailing whitespace in \033[31m$file\033[0m!"
# since $file in working directory isn't always equal to $file in index, so we backup it
mv -f "$file" "${file}.save"
# discard changes in working directory
git checkout -- "$file"
# remove trailing whitespace
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 's/[[:space:]]*$//' "$file" > "${file}.bak"
mv -f "${file}.bak" "$file"
elif [ "$platform" == "mac" ]; then
sed -i "" 's/[[:space:]]*$//' "$file"
else
sed -i 's/[[:space:]]*$//' "$file"
fi
git add "$file"
# restore the $file
sed 's/[[:space:]]*$//' "${file}.save" > "$file"
rm "${file}.save"
done

if [ "x`git status -s | grep '^[A|D|M]'`" = "x" ]; then
# empty commit
echo
echo -e "\033[31mNO CHANGES ADDED, ABORT COMMIT!\033[0m"
exit 1
fi

# Now we can commit
exit

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

最佳答案

您可以使用pre-commit 。最简单的配置是

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.2.0
hooks:
- id: trailing-whitespace
args: [--markdown-linebreak-ext=md]

查看其他hooks ,例如检测 merge 冲突的一个。

关于git - 从预提交 Hook 中排除某些文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27107118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com