Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git hook, modify commit files

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
like image 679
SerCe Avatar asked Feb 01 '13 05:02

SerCe


2 Answers

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:

  • generating a separate file with the information you want in it (and then commit).
    See for instance "Expanding Git SHA1 information into a checkin without archiving?".
  • storing that information in git note (that are separates from commits and don't change the SHA1).
    See "Adding Git notes to a blob".
like image 126
VonC Avatar answered Sep 21 '22 07:09

VonC


May be git attribute with smudge/clean operation is what you are looking for:

enter image description here

enter image description here

Related: use git smudge/clean to replace file contents

like image 31
Kenny Ho Avatar answered Sep 20 '22 07:09

Kenny Ho