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.
It's possible to do what you want using pre-commit hooks. We do something similar for a heroku deployment (compiling coffeescript to javascript). The reason your script isn't working is because you used the exec
command improperly.
From the man page:
The exec builtin is used to replace the currently running shells process image with a new command. On successful completion, exec never returns. exec can not be used inside a pipeline.
Only your first exec command is running. After that your script is basically terminated.
Give something like this a try (as a pre-commit hook):
#!/bin/sh
files=`git diff --cached --name-status`
re="<files of importance>"
if [[ $files =~ $re ]]
then
echo "Creating files"
bundle exec create_my_files
git add my_files
fi
#!/bin/sh
#
# .git/hooks/pre-commit
#
git add file.xyz
This worked just fine for me. It will be part of the current commit.
git version 1.7.12.4 (Apple Git-37)
You can use update-index
:
git update-index --add my_files