Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop a git commit by a specific author using pre-commit hook

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
like image 675
Adrian Cornish Avatar asked Mar 09 '12 00:03

Adrian Cornish


People also ask

Can you commit pre-commit hooks?

pre-commit hooks are a mechanism of the version control system git. They let you execute code right before the commit. Confusingly, there is also a Python package called pre-commit which allows you to create and use pre-commit hooks with a way simpler interface.

How do you ignore a pre-commit hook?

Use the --no-verify option to skip git commit hooks, e.g. git commit -m "commit message" --no-verify . When the --no-verify option is used, the pre-commit and commit-msg hooks are bypassed.


Video Answer


1 Answers

Until v1.7.10.1 (released 2012-05-01), Git did 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="[email protected]" 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. If you can, upgrade to v1.7.10.1 or later.

like image 55
Richard Hansen Avatar answered Sep 19 '22 12:09

Richard Hansen