mammenx
mammenx

Reputation: 21

Append the commit message automatically to the file being committed in Git

My aim is to maintain a log of all the commit history/messages at the end of each file in my repository. I used the commit-msg hook to get the commit message, prepare it and append it to the file.

However, I notice that since the file changes after staging, git status still shows as modified. What is the proper way to do this?

Upvotes: 2

Views: 1990

Answers (2)

nirmalraj17
nirmalraj17

Reputation: 494

I adapted the post-commit hook from @hvd and was able to modify the code to automatically add the commit message details to the checked in file location.

#!/bin/sh
path="D:/temp.txt"
git diff HEAD~1 --name-only > ${path}
if ! test ${GIT_BYPASS_POST_COMMIT+set}
then
    export GIT_BYPASS_POST_COMMIT=1
    for line in `cat $path`; do
        if [[ ! $line =~ version.txt ]];then
            file_path=`dirname $line`
            git show --format=%B -s | cut -d '#' -f2 > ${file_path}/version.txt
            echo " - " >> ${file_path}/version.txt
            echo $line >> ${file_path}/version.txt
            git add ${file_path}/version.txt
        fi  
    done    
    git commit --amend -C HEAD
fi

Initially it will capture all the files changed during the commit and it will save to a file. Now this will read each files in the file list excluding the version.txt file and will add the version.txt which contains *"commit message - file name"* And it will commit again to the last commit.

Note : if there are changes to specific directories, those directories will have a version file added.

Upvotes: 1

user743382
user743382

Reputation:

Although I agree with Oli Charlesworth's comments that you should not be doing this, it is actually possible. Here is a simple post-commit hook that rewrites the commit, appending the commit message to the file "changelog".

if ! test ${GIT_BYPASS_POST_COMMIT+set}
then
    export GIT_BYPASS_POST_COMMIT=1

    git show --format=%B -s >>changelog
    git add changelog
    git commit --amend -C HEAD
fi

If you try this, I expect you will quickly find that it does not play nice with normal use of git. The simplest example is that if you amend a commit, you will be amending the commit that already changes changelog, so the hook ends up duplicating the commit message.

It's up to you to say whether you want to make an attempt to get this to work, or just give up on it, but I recommend the latter.

Upvotes: 2

Related Questions