Tuesday, December 18, 2018

How to quickly checkout github pull request

Two ways:

1.
$ git fetch origin pull/117/head:local-branch-name
$ git checkout local-branch-name

Or you can put in  ~/.profile following function:

checkoutPull() {
  #Usage: checkoutPull pr-number pr-branch
  #   or  checkoutPull pr-number user:pr-branch
  BRACH=$(echo $2 | sed -e "s/^.*://")
  if git branch | grep $BRACH; then
    echo "Branch $BRACH already exists and should be removed"
    read -p "Are you sure (y/n)? " -n 1 -r
    echo    # (optional) move to a new line
    if [[ $REPLY =~ ^[Yy]$ ]]
    then
      git branch -D $BRACH
    fi
  fi
  echo "git fetch upstream pull/$1/head:$BRACH"
  git fetch upstream pull/$1/head:$BRACH
  echo "git checkout $BRACH"
  git checkout $BRACH
}

And use it as:
$ checkoutPull 3058 my-coworker-username:issue-51502

2.
One more approach is or create function that consume easy to copy value from Github page. All PRs pages show this value as text "my-coworker-fork:his-branch".
Add to ~/.profile
checkoutForked() {
  #usage: checkoutForked another-fork:branch-in-fork
  FORK=$(echo $1 | cut -d ':' -f 1)
  BRANCH=$(echo $1 | cut -d ':' -f 2)
  REPO=$(grep -A 1 "\"origin\"" .git/config | grep github | sed -E "s/.*\///");
  if git remote | grep $FORK; then
    echo "Fork already exists"
  else
    echo "git remote add $FORK git@github.com:$FORK/$REPO;"
    git remote add $FORK git@github.com:$FORK/$REPO;
  fi
  echo "git fetch $FORK"
  git fetch $FORK
  if git branch | grep $FORK/$BRANCH; then
    echo "Branch $FORK/$BRANCH already exists"
  else
    echo "git checkout $FORK/$BRANCH"
    git checkout $FORK/$BRANCH
    echo "git checkout -b $FORK/$BRANCH"
    git checkout -b $FORK/$BRANCH
  fi
}
execute:
$ checkoutForked my-coworker-fork:his-branch

NOTE:
to push to forked repo remote you will need bind your branch and his branch:
git push my-coworker-fork my-coworker-fork/his-branch:his-branch -f