secf00tprint
secf00tprint

Reputation: 693

git hook to set username and email

Is it possible to write a git hook that sets the username and email before the first commit? The username and email should be set depending on configured parameters like repository / domain regex or other ones.

I tried to write different types, but I only succeeded in that the configuration change after the first commit.

Edit

My code looks like this (based on Create a global git commit hook):

.git-templates/hooks/ -> cat pre-commit 
#!/bin/bash
remote=$(git config --get remote.origin.url)
if [ -n "$remote" ]; then
    if [[ $remote =~ "specific_domain" ]]; then
        git config user.email "myname@specific_domain.tld"
        git config user.name "Firstname Lastname"
    else
        git config user.email "pseudonym@general_domain.tld"
        git config user.name "pseudonym"
    fi
fi

Upvotes: 2

Views: 1761

Answers (2)

secf00tprint
secf00tprint

Reputation: 693

I found an alias solution for the problem

# Git
# gcw
# sets local username + email in repo
# Usage: gcw git-repo-to-clone
git_clone_wrapper () {
    first_arg = "$ 1"
    if [$ # -ne 1]
    then
        echo "only works with one argument (repo)"
        exit
    fi
    git clone "$ first_arg"
    python - << EOF
import os
from urlparse import urlparse
result = urlparse ("$ first_arg")
git_repo_full = result.path.rpartition ('/') [2] # get last element
git_repo_dir = git_repo_full.split ('.') [0]
os.chdir (os.getcwd () + '/' + git_repo_dir)
os.system ('git config --local user.name "Firstname Lastname"')
os.system ('git config --local user.email "myname@specific_domain.tld"')
EOF
}
alias gcw = 'git_clone_wrapper'

You can use gcw for your private stuff and global git config using git clone for your public.

I wrote a little article about it here

Upvotes: 0

torek
torek

Reputation: 489898

Git has already set up all the information by the time it runs your pre-commit hook. You can observe this by writing this always-fail pre-commit hook:

#! /bin/sh

echo pre-commit hook run
env | grep GIT
exit 1

Observe that GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and GIT_AUTHOR_DATE are already set. These are the values that will go into the commit. As they are environment variables, any changes you make in the hook will have no effect on the parent Git process, either.

What you can do is write a pre-commit hook that checks whether the name ane email address are set correctly. If they are not, it can either update them immediately and exit 1, or print a reminder to configure them (along with the actual git config commands, suitable for cut-and-paste) and exit 1. This is not perfect but will handle many use cases.

Upvotes: 3

Related Questions