问题
My plan is to use git to keep track of changes in /etc but when committing I want to have the person making the change specify themselves as author by adding the --author option on the commandline.
So I would like to stop accidental commits as root.
I tried creating this pre-commit hook but it is not working - git var is still returning root even if I specify the author on commit line.
AUTHOR=`git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/\1/p'`
if [ "$AUTHOR" == "root <root@localhost>" ];
then
echo "Please commit under your own user name instead of \"$AUTHOR\":"
echo 'git commit --author="Adrian"'
echo "or if your name is not already in logs use full ident"
echo 'git commit --author="Adrian Cornish <a@localhost>"'
exit 1
fi
exit 0
回答1:
The current version of Git does not make --author
information available to Git hooks via environment variables, command-line arguments, or stdin. However, instead of requiring the use of the --author
command line, you can instruct users to set the GIT_AUTHOR_NAME
and GIT_AUTHOR_EMAIL
environment variables:
#!/bin/sh
AUTHORINFO=$(git var GIT_AUTHOR_IDENT) || exit 1
NAME=$(printf '%s\n' "${AUTHORINFO}" | sed -n 's/^\(.*\) <.*$/\1/p')
EMAIL=$(printf '%s\n' "${AUTHORINFO}" | sed -n 's/^.* <\(.*\)> .*$/\1/p')
[ "${NAME}" != root ] && [ "${EMAIL}" != "root@localhost" ] || {
cat <<EOF >&2
Please commit under your own name and email instead of "${NAME} <${EMAIL}>":
GIT_AUTHOR_NAME="Your Name" GIT_AUTHOR_EMAIL="your@email.com" git commit
EOF
exit 1
}
Like the --author
argument, these environment variables control the commit's author. Because these environment variables are in Git's environment, they're also in the environment of the pre-commit
hook. And because they're in the environment of the pre-commit
hook, they're passed to git var GIT_AUTHOR_IDENT
which uses them like git commit
does.
Unfortunately, setting these variables is much less convenient than using --author
. I suggest contacting the Git developers and requesting that they set these environment variables (using the value passed via --author
) before launching the pre-commit
hook.
回答2:
I used the following, adding this to the systems .bashrc.
It won't catch folk who actually su to root and live in that shell, (bad!) But it does keep my logs useful when folk just use sudo. I too am trying to keep a /etc changelog with git - so I can see what's been done month-by-month.
#I want everyone to check in changes to /etc files, but also want their names even when they use sudo.
export GIT_COMMITTER_EMAIL=${USER}@ourcompany.co.nz
export GIT_AUTHOR_EMAIL=${USER}@ourcompany.co.nz
https://serverfault.com/questions/256754/correct-user-names-when-tracking-etc-in-git-repository-and-committing-as-root
来源:https://stackoverflow.com/questions/9627198/stop-a-git-commit-by-a-specific-author-using-pre-commit-hook