Skip to content

Instantly share code, notes, and snippets.

@boechat107
Last active February 15, 2022 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boechat107/8ebccb4e45abc191a32a40afd4cb7a95 to your computer and use it in GitHub Desktop.
Save boechat107/8ebccb4e45abc191a32a40afd4cb7a95 to your computer and use it in GitHub Desktop.
Bash function to update a branch based on a just merged to "master" branch
#!/bin/bash
# This script is useful to update branches that are based on a branch
# that was just merged to "master".
#
# As an example, suppose you have an open Merge Request based on branch "B1"
# and, while you are waiting for reviews, you start working on another
# branch, "B2", which is created directly from "B1".
# After a few commits on "B2", your MR gets reviewd and "B1" is merged to
# "master".
# Now your code on "B2" is ready for review and you want to create a new
# Merge Request based on "B2", but you need to update "B2" from "master".
# The solution proposed below creates a fresh "B2" branch from an up-to-date
# "master" and cherry-picks those commits newer than "B1"'s last commit.
set -euo pipefail
# With "HEAD" at the branch you want to update, issue this command passing
# the base branch's name.
# ARG1: base branch
# ARG2 (optional, default "master"): the repo's main branch
basebranch=$1
mainbranch=${2:-master}
currentbranch=$(git rev-parse --abbrev-ref HEAD)
tmpbranch="$currentbranch"-TMP
# Creating a temporary branch.
git branch "$currentbranch"-TMP
# Taking the last master version.
git checkout $mainbranch
git pull origin $mainbranch
# Creating a fresh new branch.
git branch -D "$currentbranch"
git branch "$currentbranch"
git checkout "$currentbranch"
git cherry-pick $(git rev-parse $basebranch)..$(git rev-parse $tmpbranch)
git branch -D "$tmpbranch"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment