问题
A bunch of questions ask how to rewrite (rebase
) some commits so that they appear on a branch, but these all seem to assume that rebase is actually necessary, i.e. that the commits wanted for the branch are interspersed with commits wanted on master
(whether made by “you” or others).
This question is simpler: I have a clone of a repository on the master
branch, and I made a bunch of commits intending to create a GitHub pull request. Normally I would have run
git checkout -b new-feature
before starting the commits, but in this case I forgot. Can I retroactively mark this sequence as commits as being on a new branch (without needing to use git rebase
)?
回答1:
You can move the commits to a branch and reset your master branch to where it was with:
git branch new-feature
git reset --hard origin/master
Note that this will blow away any uncommitted changes, if that is a problem you should use git stash
before starting to save them away.
回答2:
Assuming fork
is a remote for your GitHub fork:
git checkout -b new-feature origin/master
git reset --hard master
git push fork new-feature
git checkout master
git reset --hard origin/master
I.e.:
- Create the new branch, rooted at the upstream tip.
- Force it to contain what was previously committed on
master
. - Push the branch to the forked repository in preparation for a pull request.
- Go back to the
master
branch. - Delete the new commits from it.
Maybe not the most elegant solution but appears to work. Might also want to pass --set-upstream
to the push
.
来源:https://stackoverflow.com/questions/17595353/retroactively-treat-line-of-git-commits-as-a-branch