MW

Tag hook

Recent Posts

A git hook to prevent pushes with untracked source files (August 08, 2014)

Hey all,

do you know this: You work on something locally in git, ensure everything compiles and the tests pass, then commit and hit git push.What could possibly go wrong at that point, eh? Well, far too often I forgot to git add some new source file. Best-case I’ll notice this directly, worst-case I’ll see my CI complaining. But, like yesterday in kdev-clang, I might be afk at that point and someone else will have to revert my change and I’ll have to fix it up the day after, polluting the git history while at it…

Thanks to some simple shell scripting and the powerful git hook architecture, it is pretty simple to protect oneself against such issues:

    #!/bin/sh
     
    #
    # A hook script to verify that a push is not done with untracked source file
    #
    # To use it, either symlink this script to $your-git-clone/.git/hooks/pre-push
    # or include it in your existing pre-push script.
    #
     
    # Perl-style regular expression which limits the files we interpret as source files.
    # The default pattern here excludes CMakeLists.txt files and any .h/.cpp/.cmake files.
    # Extend/adapt this to your needs. Alternatively, set the pattern in your repo via:
    #     git config hooks.prepush.sourcepattern "$your-pattern"
    pattern=$(git config --get hooks.prepush.sourcepattern)
    if [ -z "$pattern" ]; then
      pattern="(?:(?:^|/)CMakeLists\.txt|\.h|\.cpp|\.cmake)$"
    fi
     
    files=$(git status -u --porcelain --no-column | sed "s/^?? //" | grep -P "$pattern")
    if [ -z "$files" ]; then
      exit 0
    fi
     
    echo
    echo "ERROR: Preventing push with untracked source files:"
    echo
    echo "$files" | sed "s/^/    /"
    echo
    echo "Either include these files in your commits, add them to .gitignore"
    echo "or stash them with git stash -u."
    echo
    exit 1

continue reading...