I’m trying to write a Git pre-commit hook script. It should write the date of commit at the beginning of modified files.
My problem is that I can’t add modified files to the previous commit. When I am trying invoke to a Git commit again, it runs recursive. How can I write the script, which appends the time of modification at the end of modified files?
My code:
#!/bin/bash
files_modified=`git diff-index --name-only HEAD`
for f in $files_modified; do
if [[ $f == *.groovy ]]; then
$line = $(head -1 f)
if [[ $line == "/%%*" ]];
then
sed -i 1d
fi
echo "/%% " + $(date +"%m_%d_%Y") + " %%\\" >> f
git add f
fi
done
git commit --amend #recursive
exit
You cannot amend a commit in a pre commit hook.
And what you are doing is similar to the keyword expansion mechanism, which is not a best practice with Git (or any DVCS), as explained in “To put the prefix
?<revision-number>to codes by Git/Svn“.Other approaches include:
See for instance “Expanding Git SHA1 information into a checkin without archiving?“.
See “Adding Git notes to a blob“.