Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Step back a couple of revisions in git branch

Tags:

git

I'm still new to git, so bear with me. I started adding a feature to my project in my current branch and committed it, then found out that I needed to add a more important feature first. (If I had thought about it, I would have just put the new feature into another branch but alas - hindsight is 20/20.)

I want to go back to my previous commit, add the more important feature and then add the less important feature that I already committed. Any ideas?

Thanks in advance.

like image 972
mozillalives Avatar asked Dec 17 '22 01:12

mozillalives


2 Answers

Probably the best way is to check out a new branch based on the point where you want to add the new feature.

git checkout -b newfeature <oldcommit>

Where <oldcommit> is either a commit id or a relative reference such as (e.g.) HEAD~3 three commits before the current HEAD.

Once the feature is complete you can go back to your original branch and choose either to merge it in or to rebase the work on top of the newfeature branch. One of the great things about git is that you don't have to order all your work sequentially, indeed it often makes more sense to not force your history into one linear sequence of commits.

like image 118
CB Bailey Avatar answered Dec 26 '22 02:12

CB Bailey


That mean rewriting the commit history of your branch, which is possible (practical) only if you do not have already pushed said branch to another repo.

If you do not pushed that branch, you have:

o---x---x---F1a---F1b---F1c <-- current branch

Mark it as branch F1

$ git branch F1

o---x---x---F1a---F1b---F1c <-- current branch, F1

Reset your current branch to before F1

$ git reset x

o---x---x---F1a---F1b---F1c <-- F1
        ^
        |
       current branch    

Make your Feature 0 F0 (the one that should have been done before F1)

$ git commit ...

o---x---x---F0a---F0b <-- current branch
        ^
        |
        ---F1a---F1b---F1c <-- F1

Rebase F1 branch on top of current branch

$ git checkout F1
$ git rebase current
$ git checkout current
$ git merge F1 # fast-formward merge

o---x---x---F0a---F0b---F1a'---F1b'---F1c' <-- current branch, F1

If you did already pushed that feature, some revert is in order (see Diego's answer)

like image 28
VonC Avatar answered Dec 26 '22 01:12

VonC