Search code examples
gitbashgithubpre-commit-hookpre-commit

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


I'm using a GIT pre-commit hook to locate a string pattern in my README.md file ex. {{STRING_PATTERN}} and then changing the string pattern into the desired text/code output, which also contains the current branch name.

Here is the issue. The pre-commit script works from the standpoint that it locates the string pattern and replaces it with the correct text/code BUT it doesn't appear to do this prior to committing the changes... meaning that after I run git commit -m "Updated README.md" and do a git status check the README.md file shows as being modified and if I were to run git push origin branch_name the README.md file contains the actual {{STRING_PATTERN}} identifier (not wanted) and not the text that it was updated with (which is what I do want).

Here is the pre-commit code, as I said, please note that this does work from the standpoint that it locates the string {{STRING_PATTERN}} identifier and updates it with the dynamically created text/code – it's just not actually committing those changes, which is the problem.

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

Solution

  • You should do also git add in the pre-commit hook to add the changes to the repo.