Search code examples
gitformattinggithooks

git pre-commit hook to format and re-add files at the same time


We're currently using a git hook (below) to run astyle on our source code before allowing the user to commit. This has the caveat that the user must commit, have their code formatted, then commit again which is a bit of a nuisance. Ideally we'd want the hook to format the code and then include that formatted code in the original commit instead. I've tried re-adding the changed files but it causes ref errors (obviously). I've also tried getting the history in the pre-commit hook and trying to exit the hook and re-run the git commit command with no luck.

# Run astyle on changed .cs files, ignoring $ignored
res=$(exec git diff --cached --name-only | \
    grep -Ev $ignored | \
    xargs astyle --options=conf/astylerc | \
    tail -n 1)
num_formatted=$(echo $res | cut -b 1) # We are only interested in the number preceeding 'formatted'.
[[ $num_formatted -ne 0 ]] && echo "WARNING: Code has been automatically formatted. Please re-add and re-commit" && exit 1 || echo "No code to format! Continuing commit"

Does anyone have any ideas?


Solution

  • In your pre-commit hook, you need to add your files, so if your hook is something like:

    #!/bin/bash
    echo 1 > file
    exit 0
    

    then you would need to modify it to have the add:

    #!/bin/bash
    echo 1 > file
    git add file
    exit 0
    

    To get a list of all modified files, you could use git-ls-files:

    git ls-files -m

    However, it would be better if you could just get a list from your code of which files are modified or just add all files again. git diff-tree -r --name-only --no-commit-id <tree-ish> should work for you to get a list of all files.

    Basically, adding the files again after modifying works because the commit does not occur until after your pre-commit hook runs, so whatever is staged in the working tree at that point is committed.