Can a Git hook automatically add files to the commit?

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.

Leave a Comment