git – Move commit to different branch in Visual Studio?


This is an old question, but it was my question, and the answer is almost here but not quite, and perhaps the exact steps (in Visual Studio 2022, can’t speak for earlier versions) might save others the time I lost along the way. This is a pretty good workaround for those who a) are not already at ease in git commandline (rebase is not where you want to start) and b) just need to move a few (<25? ymmv) local changesets and c) you prefer to preserve change history as change history because source control. (I ended up using this method to reset to a private author email, so it’s not just for main vs. branch.)

Assumptions: start from a VS repo checked out (call it main) that’s n changesets ahead of where it should be. This will use only VS UI.

  1. Open Git Repository window (main menu > Git > Manage Repositories or Git Changes sidebar > View all commits both get you there)

  2. On the main repo, select the last changeset you did not make, right click, choose “New branch…” from the context menu, give it a name (I’ll call it test), verify (changeset id is correct and “checkout branch” is checked), and click “Create”.

  3. On the lefthand tree you should now see two branches, with test in bold (because checked out). Highlight main instead. Select your first changeset to keep (the one just above where you branched in the list, assuming you’re sorted reverse-chronologically).

  4. Right-click, choose Cherry-Pick from the context menu. Move to the next more recent commit, repeat n times. You now have a test branch with n local changesets. (If you’re hotkey-conversant, ^ then context then P n times)

Once you’ve pushed your branch, don’t forget to dump/reclone according to your style, because your local main is no good any more.

Leave a Reply

Your email address will not be published. Required fields are marked *