GIT预提交钩子修改了文件但没有添加到提交中

3
我正在使用 GIT 的 pre-commit 钩子来定位 README.md 文件中的字符串模式 例如 {{STRING_PATTERN}},然后将字符串模式更改为所需的文本/代码输出,其中还包含当前分支名称。
问题在于,pre-commit 脚本的工作原理是定位字符串模式并用正确的文本/代码替换它,但似乎在提交更改之前并没有这样做...这意味着在运行 git commit -m "Updated README.md" 并进行 git status 检查后,README.md 文件显示为已修改,如果我运行 git push origin branch_name,README.md 文件包含实际的 {{STRING_PATTERN}} 标识符(不想要的),而不是更新后的文本(这正是我想要的)。
这是 pre-commit 代码,请注意,从定位字符串 {{STRING_PATTERN}} 标识符并使用动态创建的文本/代码更新它的角度来看,它确实可以工作-只是没有真正提交这些更改,这就是问题所在。
#!/usr/bin/env bash

# Echo out text to ensure pre-commit is running
echo "pre-commit working"

# Get the current branch name
function git_branch {
    git rev-parse --abbrev-ref HEAD
}

# Set branch variable to current branch
branch=$(git_branch)

# Define the string/pattern marker to search for
# This pattern/string serves as a marker that
# gets replaced with the dynamically created text/code
id="{{STRING_PATTERN}}"

# Dynamically create text/code
# Inject the $branch variable into the correct location of the text
updated_text="Example text containing that is being added to the $branch branch"

# Find the string/pattern and replace it with the text/code
# Then replace it with the build status image
sed -i '' -e "s%{{STRING_PATTERN}}%$updated_text%g" README.md
1个回答

5

在 pre-commit 钩子中,您还应该执行 git add 命令将更改添加到代码库中。


当你说添加 git add 时,你是指它应该在脚本的末尾添加吗?所以在运行 sed 代码块之后?另外,这是否意味着我还需要重新运行 git commit - corey
是的,没错,在脚本的结尾处使用 git add 命令。 - Krzysztof Krasoń

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接