Can a Git hook automatically add files to the commit?

Ian Terrell picture Ian Terrell · Jul 19, 2010 · Viewed 32.1k times · Source

I'd like to add an automatically generated file to the same commit using a pre- or post-commit hook in Git, dependent on the files that were modified in that commit. How would I go about this?

I've tried this as a pre-commit hook, but no luck:

#!/bin/sh
files=`git diff --cached --name-status`
re="<files of importance>"
if [[ $files =~ $re ]]
then
  echo "Creating files"
  exec bundle exec create_my_files
  exec git add my_files
  exec git commit --amend -C HEAD
fi

This successfully adds them to the repository, but does not add them to the commit. I've also tried using the last two exec lines in a post-commit hook along with the pre-commit inspection, but no good either.

Answer

bitluck picture bitluck · Oct 9, 2012

Since git add was also not working for me in a pre commit, I followed mark's idea of using a .commit file and splitting the process into pre- and post-commit.

Here is some code that should be easy to understand

In the pre-commit:

  • Touch a file .commit or something. (be sure to add this to .gitignore)
#!/bin/sh 
echo 
touch .commit 
exit

In the post-commit:

if .commit exists you know a commit has just taken place but a post-commit hasn't run yet. So, you can do your code generation here. Additionally, test for .commit and if it exists:

  • add the files
  • commit --amend -C HEAD --no-verify (avoid looping)
  • delete .commit file
#!/bin/sh
echo
if [ -e .commit ]
    then
    rm .commit
    git add yourfile
    git commit --amend -C HEAD --no-verify
fi
exit

Hope this makes it easier for people with few bash knowledge to follow mark's idea.