user4880619
user4880619

Reputation:

git - move specific commits from develop to feature branch

So, in our git repository, some commits were made (not the most recent commits now) into our develop branch, that should have been in a feature branch. The branch they should be is was made further down the line. The commits ended up being for functionality that still isn't completed, so now we really need to get them off of the develop branch so that we can go back to having a functioning develop branch.

Is there a way that I can move specific commits from the develop branch to the start of the feature branch? Not 100% familiar with git, so if any additional info is needed, please ask.

Upvotes: 2

Views: 1771

Answers (2)

Enrico Campidoglio
Enrico Campidoglio

Reputation: 59963

First, the usual disclaimer: what you want to do (i.e. removing commits from a branch) means rewriting history, so proceed with caution.

Assuming your history looks something like this:

A--B--C--D--E develop
         \
          F--G feature

And you want to "move"1 commits B and C from develop to feature, you can do that with the rebase --onto command:

git checkout develop
git rebase --onto feature A C
# This will apply commits B and C on top of the commit referenced by "feature"

Now you history will look like this:

A--B--C--D--E develop
         \
          F--G--B'--C' feature

Notice that B' and C' (read "B prime" and "C prime") are new commits that contain the same changes as B and C but have different commit IDs because they have different parents.

At this point you can remove B and C from the develop branch by saying:

git rebase --onto A C
# This means rebase the current branch on top of commit A instead of C

which will result in commits B and C no longer being reachable in develop:

A--D'--E' develop
A--B--C--D
         \
          F--G--B'--C' feature

However, you still have the feature based off of the old commit D, which has now be rewritten as D'. To solve that you need, once again, to rebase feature on top of the new D':

git checkout feature
git rebase --onto D' D

Finally resulting in:

A--D'--E' develop
    \
     F--G--B'--C' feature

which is probably what you wanted.


1) See @WilliamPursell's comment about what it means to "move" commits in Git.

Upvotes: 1

pramesh
pramesh

Reputation: 1964

Try cherry pick. With cherry pick you can get the selected commits of another branch to the current branch.

https://git-scm.com/docs/git-cherry-pick

Upvotes: 1

Related Questions