不幸的是,我也找不到真正令人满意的解决方案。我将列出到目前为止我找到的所有解决方案(我认为您已经提出了问题中最好的 3 个)。
(1) 禁止在没有 --author 的情况下提交
将以下脚本另存为pre-commit
hook in.git/hooks/pre-commit
以禁止:
#!/bin/sh
if echo $GIT_AUTHOR_NAME | grep -q "XXX" 2> /dev/null; then
echo 'You tried to commit as XXX, please use git commit --author="your name".'
return 1
fi
将用户名设置为 XXX:
git config user.name XXX
警告:这仅适用于正常提交。合并提交将作为 XXX 提交。可能也有办法完成这项工作
(2a) 提交前提示作者信息(使用钩子)
使用钩子设置作者的唯一方法似乎是用钩子修改提交post-commit
,另请参见此处。
这是一个带有丑陋副作用的奇怪 hack(例如,提交消息中的作者显示错误)。
#!/bin/sh
# env variable to prevent recursion
test -z $AMMEND_COMMIT || exit 0
export AMMEND_COMMIT=1
exec < /dev/tty
echo -n "Author for previous commit: "
read author
git commit -q --no-edit --amend --author "$author"
使用以下脚本根据上次提交获取作者建议:
#!/bin/sh
# TODO this doesn't work for repos with <15 commits
NUM_LAST_COMMITS=15 # how many commits in the past to look for authors
# env variable to prevent recursion
test -z $ammend_commit || exit 0
export ammend_commit=1
exec < /dev/tty
last_authors=$(git shortlog -s -e HEAD~${NUM_LAST_COMMITS}..HEAD|sed 's/^\W*[0-9]*\W*//g')
echo "Select an author from list or enter an author:"
echo
echo "$last_authors" | awk '{print " [" NR "] " $s }'
echo
echo -n "Enter number or author: "
read author
if echo "$author" | egrep -q '^[0-9]+$'; then
author=$(echo "$last_authors" | sed "${author}q;d")
fi
git commit -q --no-edit --amend --author "$author"
看起来像这样:
$ git commit -am "My message"
Select an author from list or enter an author:
[1] First Author <first_author@domain.com>
[2] Second Author <second_author@domain.com>
[3] Third Author <third_author@domain.com>
Enter number or author: 3
(2b) 提交前提示作者信息(使用自定义脚本或别名)
您可以创建一个脚本git-commit.sh
或 git 别名git commit-author
,提示使用作者,然后调用git commit --author=<user's selection>
. 不幸的是,无法覆盖 git commit
.
中的git-commit.sh
脚本/usr/local/bin
可能如下所示:
#!/bin/sh
# TODO this doesn't work for repos with <15 commits
NUM_LAST_COMMITS=15 # how many commits in the past to look for authors
last_authors=$(git shortlog -s -e HEAD~${NUM_LAST_COMMITS}..HEAD|sed 's/^\W*[0-9]*\W*//g')
echo "Select an author from list or enter an author:"
echo
echo "$last_authors" | awk '{print " [" NR "] " $s }'
echo
echo -n "Enter number or author: "
read author
if echo "$author" | egrep -q '^[0-9]+$'; then
author=$(echo "$last_authors" | sed "${author}q;d")
fi
git commit "$@" --author "$author"
要将脚本添加为别名运行:
$ git config alias.commit-author '!git-commit.sh'
(3) 根据登录时使用的 ssh-key 自动设置作者
这是您自己的答案,复制到此处以获得更好的概述:
在共享部署用户的/home/deploy/.ssh/authorized_keys
文件中,我为每个键添加了一个环境变量,例如,我的如下所示:
environment="GIT_AUTHOR_EMAIL=ry4an@host.com",environment="GIT_AUTHOR_NAME=Ry4an on Dev" ssh-rsa AAAA...cXBcmHr ry4an@host.com
这还需要添加:
PermitUserEnvironment yes
到/etc/ssh/sshd_config
文件。