简体   繁体   中英

How to move some last Git commits currently on a branch, onto another branch?

I have a repository where I had been working on master branch having last added some 10 or so commits which I now wish were on another branch, as they describe work that I now consider experimental (I am still learning good Git practices).

In light of this consideration, I would now like to have these last 10 commits form their own branch so to speak, so that I can have master clean and reserved for "release" / "stable" commits only.

To illustrate, what I have is:

        b--b (feature B)
       /       
X--X--X--Z--Z--Z--Z--Z--Z (master)
    \
     a--a--a (feature A)

You can see that commits marked with X and Z are all on the master branch, while what I want is commits marked with Z (the now considered experimental "feature Z" work) to lie on their own branch and master ending with the rightmost X . To illustrate, the desired graph:

        b--b (feature B)
       /       
X--X--X (master)
    \  \
     \  Z--Z--Z--Z--Z--Z (feature Z - the new branch I want)
      \
       a--a--a (feature A)

That way I will have my master reserved for releases and otherwise stable commits, being able to merge in A, B and Z features as needed.

So how do I move the "Z" commits onto their own branch?

git checkout master
git branch feature-Z
git reset <commit_id>

where commit_id is an identifier of that last X commit before b branches off.

For completeness, the answer is here - http://git-scm.com/docs/git-reset - search for the text "Undo a commit, making it a topic branch" - the example shows making the last 3 commits a branch and resetting master to the commit previous to those 3 commits:

$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 3 commits.
#
nothing to commit (working directory clean)
$ git branch topic/wip
$ git reset --hard HEAD~3
$ git checkout topic/wip
Switched to branch topic/wip

只需重命名master并在最后一个X处启动一个新master:

git checkout master; git branch -m feature; git checkout -b master HEAD~6

Create and checkout in desired new branch
Force master branch N commits back (in your case 10)

git checkout -b feature-z
git branch -f master HEAD~10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM