TIL: aliases for git merge-delete

A couple of the projects I’m involved in use short-lived feature branches. Sometimes branches are merged via git commands, sometimes via Pull Requests on Github. Merged branches are usually deleted.

The following two aliases automate these use cases. They could really be functions but I tend to prefer aliases, even if it involves a subshell and exporting a variable.

# cd to git root, checkout master, merge branch into master,
# push and delete branch, cd back to previous PWD
alias gmbx='(
    export _git_branch=$(git rev-parse --abbrev-ref HEAD) &&
    cd "$(git rev-parse --show-toplevel 2>/dev/null)" &&
    git checkout master &&
    git merge --no-ff --no-edit ${_git_branch} &&
    git push &&
    git branch -d ${_git_branch} &&
    git push origin --delete ${_git_branch} &&
    popd
)'

# when PR merged: cd to git root, checkout master,
# pull rebase, delete branch, cd back to previous PWD
alias gmBx='(
    export _git_branch=$(git rev-parse --abbrev-ref HEAD) &&
    cd "$(git rev-parse --show-toplevel 2>/dev/null)" &&
    git checkout master &&
    git pull --rebase &&
    git branch -d ${_git_branch} &&
    popd
)'

These are really one-liners in my config, I’ve split them up for readability.

First change directory to the root of the git repo since the current working directory might not yet exist in master. Checking out a branch in a directory that doesn’t exist in that branch results in an error.

I follow a mnemonic pattern for my git aliases. Aliases starting with gm pertain to merge-related commands. In this case, gmbx stands for “git merge branch and delete”, while gmBx stands for “git merge already-merged branch and delete”.

(I’m aware that the second alias isn’t a merge at all, since it’s really merged by Github, but it helps my lazy brain if I organize it as a merge anyways.)


← back to main page

Comments