Roboko
Roboko

Reputation: 59

Move commit to different branch in Visual Studio?

Occasionally I commit work only to later realize that it would have been better off in it's own branch.

Hindsight is 20/20 and if I was thinking ahead I would have made a new branch and then committed onto that sparing me this problem in the first place.

Is it possible to move an existing commit onto a new Branch? If so, how is it done? and can it be achieved through Visual Studio?

Upvotes: 5

Views: 8435

Answers (1)

TTT
TTT

Reputation: 28954

It can be done in Visual Studio. Here are the steps:

  1. First make sure you don't have any pending changes. (Stash, commit, or undo them.)
  2. Right click on your checked out branch and choose "New Local Branch From..."
  3. Enter in the name of your new branch, but uncheck "Checkout branch".
  4. Now "View History" on your current branch.
  5. In the history view, right click on the commit you want to reset to. This would be the commit just before your first commit that you intended to add to the new branch. Select "Reset --> Delete Changes (--hard)".
  6. Now checkout your new branch.

You now will be in the exact same situation as if you created the new branch in the first place.

Side note: I do recommend learning how to do this from the command line rather than using the GUI. Once you know it, it's faster, easier, doesn't tie you to any particular UI, and enables you to script your favorite workflows more easily. As an example, here's the same workflow from the command line:

  1. First make sure you don't have any pending changes. (Stash, commit, or undo them.)
  2. git branch new-branch-name # create new branch like what's checked out now
  3. git reset --hard HEAD~1 # go back one commit (change 1 to however many you need)
  4. git checkout new-branch-name

Upvotes: 4

Related Questions