Skip to content

Instantly share code, notes, and snippets.

@rca
Last active Feb 25, 2022
Embed
What would you like to do?
An explanation of `git rebase --onto`

git rebase onto fu

Looking at the following git history, there are a few commits that were accidentally made on top of env/dev-auth that should be on a feature branch named experiments/sso-login-app (1. in the command below):

[0][~/Projects/openslate/thing(env/dev-auth:feb0ee9)]
$ git log
commit feb0ee98c8b77e929b9cc23442c5664c9d4986c9 (HEAD -> env/dev-auth)  # this is `0.` in the command below
Author: Roberto Aguilar <roberto@openslate.com>
Date:   Thu Sep 26 00:25:15 2019 -0400

    Accidental commit 3

commit 7592d4d1ab1a101ad654abc097672ab9bfecbd8a
Author: Roberto Aguilar <roberto@openslate.com>
Date:   Thu Sep 26 00:24:50 2019 -0400

    Accidental commit 2

commit 89fe221406158f5d069cbd669feddff28e307b4f
Author: Roberto Aguilar <roberto@openslate.com>
Date:   Thu Sep 26 00:24:08 2019 -0400

    Accidental commit 1

commit 58f4606f37359829c5b4f945a1a4c4a17c4428b4 (origin/env/dev-auth)  # this is `2.` in the command below
Merge: df3ebc5 3fee1eb
Author: Roberto Aguilar <roberto@openslate.com>
Date:   Thu Sep 26 00:01:42 2019 -0400

    The commit that accidental commits were commited on top of

[...]

In order to fix the problem git rebase —onto can be used, but it’s confusing.

The first thing to do is reset the desired branch to the HEAD of the accidental commits:

$ git checkout env/dev-auth  # this is `0.` from the git log above.
$ git checkout -b fix/rebase-onto  # create a temporary branch to house the resulting rebase

Next, run git rebase --onto, which will rewrite experiments/sso-login-app to the final result:

$ git rebase --onto experiments/sso-login-app origin/env/dev-auth fix/rebase-onto
                    \_______________________/ \_________________/ \_____________/
                                 |                     |                 |
1. the commit that accidental    |                     |                 |
commits should be on top of  ----+                     |                 |
                                                       |                 |
2. the branch/commit that additional commits were      |                 |
accidentally made on top of  --------------------------+                 |
                                                                         |
3. the local branch with accidental commits.                             |
it will be refrenced to find the commits to move as                      |
well as being re-written to have the final result  ----------------------+

Once fix/rebase-onto is confirmed to be correct:

$ git checkout experiments/sso-login-app
$ git reset --hard fix/rebase-onto
$ git branch -D fix/rebase-onto
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment