Search code examples
gitbashsedosx-elcapitanpre-commit-hook

Git Pre-Commit Using Sed To Dynamically Inject Branch Name


I am using a git pre-commit hook to:

  1. Get the current branch name
  2. Insert the branch name into a build status image code
  3. Search the README.md file for a string/pattern and then use that string/pattern as a marker for where I want to insert the dynamically generated build status image.

Note that I am using OSX El Capitan v10.11.5 and in order to execute this code I had to run chmod +x .git/hooks/pre-commit on the pre-commit script.

Here is the code that I'm using:

#!/bin/bash

function git_branch {
    git rev-parse --abbrev-ref HEAD
}

branch=$(git_branch)
id="{{CODESHIP_CODE}}"

codeship_build_status="[ ![Codeship Status for ExampleUser/exampleRepo](https://codeship.com/projects/a99d9999-9b9f-9999-99aa-999k9b9b0999/status?branch=$branch)](https://codeship.com/projects/999999)"

sed -i -e "s%{{CODESHIP_CODE}}%$codeship_build_status%g" README.md

As of right now the code is kind of working. By that I mean it is:

  1. Correctly searching the README.md file
  2. Removing the string/pattern marker
  3. Replacing the string/pattern marker with the codeship_build_status variable.

The issue is that this doesn't appear to be actually changing the README.md file prior to the git commit and instead it generates another file called README.md-e

When I go to git pushand view the code in the repo the README.md file has not been updated and instead still contains the string/pattern marker instead of the updated build status image. Ironically enough the README.md file does get changed inside my local development branch.

Any ideas how to fix this issue or what may be causing it?


Solution

  • The problem is sed -i. That tells sed to create a new file, and retain the old file with a new name, using the next parameter (in your case, -e) as the suffix.

    For the Mac version of sed, you must provide a qualifying parameter for -i. To make it do the same thing the gnu / linux version would with those command line options, you want to provide a blank option, like this:

    sed -i '' -e "s%{{CODESHIP_CODE}}%$codeship_build_status%g" README.md