简体   繁体   中英

Accidentally branched from a topic branch instead of master

I'm working on multiple topic branches. One topic branch has a lot of new features and is 17 commits ahead of master.

Now I decided to work on another topic, and branched off to a new topic. I made a commit and this single commit is ready for a pull request on GitHub. However I noticed that I accidentally branched off my previous topic branch instead of master, so GitHub is previewing me with the other 17 commits of the other topic branch. How do I move this new commit to a topic branch which doesn't have the commits of the previous topic branch?

Well the problem is that it is not said that this will be straight forward, since perhaps you have changed files that were already changed by your previous file. In case the changes are thus dependent , then you will have to resolve conflicts.

Nevertheless you can do the following:

  1. go to the master git checkout master
  2. create a topic branch (another name than the "accidental" topic branch): git checkout -b new_topic_branch
  3. inspect your git tree and take a look at the commit hashes (the first and the last of the "accidental" branch).
  4. cherry pick these commits with git cherry-pick A..B with A the hash of the first commit of the "accidental" branch, and B the last commit of that branch). In this particular case you seem to have made only one commit, so you can git cherry-pick commit with commit the hash of that single commit
  5. if that succeeds, than the last changes are also processed on the new branch.

Optionally you can then merge that branch into the master.

Perhaps the conceptually easiest and cleanest way to handle this situation would be to create a new topic branch from the latest master , and then cherry-pick your single commit onto it:

First find the SHA-1 hash of the latest commit on your old topic branch:

git checkout old_topic
git log

The first entry is the latest commit which you had intended to be in its own branch. Record the SHA-1 hash of this commit (the first 8 characters should be enough).

Now create a new topic branch from master and cherry-pick the commit you want:

git checkout master
git pull origin master
git checkout -b new_topic

Now cherry pick the commit

git cherry-pick SHA-1

Just rebase the new branch onto master:

git checkout new-topic
git rebase --onto master old-topic

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