Git BASH – 在合并时钩子删除换行符

huangapple go评论53阅读模式
英文:

Git BASH - Hook on merge removes line breaks

问题

我正在使用git挂钩在我的prepare-commit-msg中,自动将分支名称添加到提交消息中:

#!/bin/sh
NAME=$(git branch | grep '* ' | sed 's/* //')
echo "$NAME"' - '$(cat "$1") > "$1"

然而,如果我执行git合并操作,所有换行符都会被移除。这会导致问题,因为git会自动包括以#开头的注释行,其中包括了被更改的文件等信息。

因此,在合并操作期间,会出现类似以下的情况:

my_branch_name - Merge branch 'master' into my_branch_name # Conflicts: # File1.txt # File2.txt # File3.txt

而不是:

my_branch_name - Merge branch 'master' into my_branch_name
# Conflicts:
# File1.txt
# File2.txt
# File3.txt
英文:

I am using a git hook in my prepare-commit-msg to automatically prepend branch names to the commit message:

#!/bin/sh
NAME=$(git branch | grep '*' | sed 's/* //')
echo "$NAME"' - '$(cat "$1") > "$1"

However if I do a git merge, all of the line endings are removed. This causes an issue because git will automatically include lines with comments starting with a # which include things like files that were changed.

So what winds up happening during a merge is something like this:

my_branch_name - Merge branch 'master' into my_branch_name # Conflicts: # File1.txt # File2.txt # File3.txt

Instead of:

my_branch_name - Merge branch 'master' into my_branch_name
# Conflicts:
# File1.txt
# File2.txt
# File3.txt

答案1

得分: 1

$(cat "$1") 始终会移除换行符。如果使用 git commit 时没有 -m "some message",也会引发问题。

尝试使用 sed 在第一行开头插入分支名称。

#!/bin/sh
NAME=$(git branch | grep '*' | sed 's/* //')
sed -i '1i'"$NAME"' - ' $1
英文:

It's not caused by a merge commit. $(cat "$1") always removes the line endings. If you use git commit without -m "some message", it also raises the issue.

Try sed, to insert the branch name at the beginning of the first line.

#!/bin/sh
NAME=$(git branch | grep '*' | sed 's/* //')
sed -i '1i'$NAME' - ' $1

huangapple
  • 本文由 发表于 2023年5月25日 23:42:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334093.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定