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 开发者_Python百科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.
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.
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)
If you have just commited to your local branch, its an easy task
- go to another branch:
git checkout -b moreimportantfeature
. The new branch won't have the changes you commited. So you can add the new feature and push to the remote repo, or do agit rebase otherbranch
to push both changes
If you have pushed to the repo:
- use
git revert HEAD
(or some variant HEAD^n if you want to get back on more commits). Then push your changes.
精彩评论