Can pre-receive hook edit commits?

落花浮王杯 提交于 2020-08-06 03:36:10

问题


I'm building a pre-receive hook to check the name and email address of the author.

I'm able to easily check if the name/email address of the commit using,

while read oldsha newsha refname; do
        authorEmail=$(git log -1 --pretty=format:%ae $newsha)
        if [[ $(grep -w $authorEmail ~/.ssh/authorized_keys | wc -w) -gt 1 ]]; then
                        echo "Author Email: $authorEmail"
                        exit 0
                else
                        echo "Unauthorized Email"
                        exit 1
                fi
done

But instead of simply rejecting it, I want to replace the email with the right one. I have authorized_keys set up like this,

environment="UserEmail=user@hostA" ssh-rsa AAAAAA... user@hostA

So I'd like to do something along the lines of

if [[ ... ]]; 
    then
        echo "Author Email: $authorEmail"
        exit 0
    else
        echo "Unauthorized Email detected"
        echo "Replacing email with: $UserEmail"
        git commit --amend --author "something <$UserEmail>"
        exit 0
    fi

But as expected, the git commit --amend .. throws an error that this should be used in a working tree. Is there any way I can accomplish this here in the pre-receive or possibly the update hook?


回答1:


Ankit,

I understand your motivation for wanting to edit a commit to correct what seems to be a "recoverable" error. Modifying the commit authorsip is not the way to go about it. Since changing a commit author changes the SHA-1 for the commit, the commit history between the local branch and the remote will be different as soon as the commit is pushed. That is most definitely not what you want.

A better solution (if it is practical in your situation, of course) would be to add local prepare-commit-msg and/or commit-msg hooks to developers git repos. You could then change the commit message before the commit is processed. That would solve the history rewriting problem. Unfortunately, you cannot FORCE a remote developer to use the hooks (git commit --no-verify will bypass the commit checks).

Therefore, I would recommend a combination approach. Make it easy to get the email address right by providing local hooks to check and correct author problems before a commit is pushed. Then, add the server hooks to prevent commits with invalid or unauthorized authors from being pushed. Developers that follow the rules for your repo will not be inconvenienced (beyond adding the hooks), and your remote repo will not get populated with unauthorized commit authors.

On an related note, why go to the trouble of checking for unauthorized authors if all you are going to do is update the author to some default "valid" author?



来源:https://stackoverflow.com/questions/34357216/can-pre-receive-hook-edit-commits

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