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

≯℡__Kan透↙ 提交于 2019-12-12 21:15:33

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/24095474/append-the-commit-message-automatically-to-the-file-being-committed-in-git

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!