GIT 预提交挂钩更改文件但不添加到提交

GIT Pre-Commit Hook Changes File but Doesn't Add to Commit

我正在使用 GIT pre-commit 挂钩在我的 README.md 文件 ex 中定位字符串模式。 {{STRING_PATTERN}} 然后将字符串模式更改为所需的 text/code 输出,其中还包含当前分支名称。

问题来了。 pre-commit 脚本的工作原理是它找到字符串模式并将其替换为正确的 text/code 但是在提交更改之前它似乎没有这样做......这意味着在我 运行 git commit -m "Updated README.md" 并执行 git status 检查 README.md 文件显示是否已修改,如果我要 运行 git push origin branch_name README.md文件包含实际的 {{STRING_PATTERN}} 标识符(不需要)而不是更新的文本(这是我想要的)。

这是 pre-commit 代码,正如我所说,请注意,从它定位字符串 {{STRING_PATTERN}}[=27 的角度来看,它确实有效=] 标识符并用动态创建的 text/code 更新它——它实际上并没有提交这些更改,这就是问题所在。

#!/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

您还应该 git add 在预提交挂钩中将更改添加到存储库。