Search code examples
gitgit-config

Using gitconfig per branch


Our company uses many customized opensource project. Whenever I contribute upstream branch I have change to use my personal email/name. Is there any way to have gitconfig per branch?

For example what I want is

[remote 'gerrit']
name = 'Personal Name'

[branch 'origin']
name = 'Name in company'

Solution

  • You can use post-checkout hook for this. Run

    $ touch .git/hooks/post-checkout 
    $ chmod a+x .git/hooks/post-checkout 
    

    Add contents to post-checkout script (edit names and branches as neccessary)

    #!/bin/bash
    # $3 "0" - checking out file. "1" - checking out branch.
    [[ "$3" == "0" ]] && exit 0 
    branch=$(git status --short -b | cut -d' ' -f2-)
    case $branch in
      gerrit*)
        git config user.name "Personal Name"
        echo "changed user.name to Personal Name"
        ;;
      master*)
        git config user.name "Company Name"
        echo "changed user.name to Company Name"
        ;;
      *)
        echo "Some other branch, what should user.name be?"
        ;;
    esac