Skip to content

Branches and Merges

Martin Trigaux edited this page Jun 6, 2017 · 4 revisions

Features branches

Rebase your feature branch, instead of merging mainline

$ git pull --ff-only

Merging into mainline

Squash branch instead of commit and mergge commit

A simple way to do so is to use cherry-pick:

$ git remote update   # load latest PR refs
$ git cherry-pick <commit>
$ git commit --amend  # fix commit message that usually sucks

If there is more than one commit to merge, you can use:

$ git cherry-pick <commit1> <commit2> ...

in the chronological order en order, but this is often an indication that the commits needs to rebase/squash the commits in a clean single one. The commands would then be:

$ git remote update
$ git cherry-pick <commit1> <commit2> ...
$ git rebase -i   # squash commits + fix commit message 

Rebase and merge an external pull request

Will be useful if:

  • don't have the remote locally (external contributions)
  • the target branch is wrong
  • the code needs to be amended
  • needs to keep commits but rewrite commit message

Add the following alias in your ~/.gitconfig or local .git/config file.

[alias]
    # rebase a given pull request number on current branch
    rebase-pr = "!f() {\
        p=$1 && \
        b=`git symbolic-ref -q --short HEAD` && \
        r=`git config branch.$b.remote`; \
        r=${r:-origin} && \
        git fetch $r pull/$p/head:pr-$p && \
        git fetch -f $r pull/$p/merge:PR_MERGE_HEAD && \
        git rebase --onto $b PR_MERGE_HEAD^ pr-$p && \
        git checkout $b && \
        git merge --quiet --ff-only pr-$p && \
        git branch -D PR_MERGE_HEAD && \
        git branch -D pr-$p && \
        echo && \
        git diff --stat $b..$r/$b && echo && \
        git rebase -i $r/$b;}; f"

and then, use

$ git rebase-pr 42

to rebase and merge the pull request 42 into the current branch. Don't forget to close it afterwards (or do it from the commit message).