Wednesday, March 17, 2010

Git Branching with Remote Tracking Made Easy

I wanted to be able to just create or switch to a new or existing remote/local git branch with a single command, so that you don't have to worry about whether you or a teammate already created a remote branch for a specific development request. It just works. While it can be used for any branch name, if you are using Jira, Trac, or a similar ticketing system, it might be good to use gbranch (ticket name). Then because the branches it creates are remotely tracked, you can git push and git pull without specifying the origin.

To use it, create a file called gbranch.sh and chmod +x gbranch.sh and execute it in your start script (like .bash_profile, or whatever shell you use).

This script is also included in my git-scripts project.

# gbranch.sh
#
# Written by Gary S. Weaver
#
# Release: 2010-03-17
# This tracks a remote branch if it already exists, or
# makes a remotely tracking git branch if one doesn't exist, or
# just switches to the local branch by that name.

function gbranch () {
  branch=$1
  if test $# -eq 1
  then
    rbrch=`git branch -r`
    if [ "$?" -eq "0" ]
    then
      if [[ "$rbrch" =~ "origin/$branch" ]]
      then
        git checkout -b "$branch" --track "origin/$branch"
        if [ "$?" -ne "0" ]
        then
          git checkout "$branch"
        fi
      else
        git checkout -b "$branch"
        if [ "$?" -eq "0" ]
        then
          # The following lines track the remote branch per: http://djwonk.com/blog/2009/04/18/tracking-remote-git-branches/
          # note: first two lines help avoid  "fatal: Cannot force update the current branch." error per DJWonk.
          git push origin "$branch"
          git checkout master
          git branch -f "$branch" "origin/$branch"
          git checkout "$branch"
        else
          git checkout "$branch"
        fi
      fi
    fi
  else
    echo usage: gbranch \(branch_name\)
  fi
}

No comments: