Creating a Branch from the Current Git State

Kris Jenkins, whose wonderful video I’ve written about before, has posted a very handy Magit tip. What do you do if you want to add a feature branch but start working on it before creating the branch? What you’d like to do is move your unpushed work to a new branch and set your current branch back to the state it had before you started working on your changes. Neither of the two common solutions are very good but it turns out that Magit has a solution: magit-branch-spinoff.

It does exactly what you want: it creates a new branch with your unpushed commits and resets your current branch to the last commit it shares with the upstream repository. As far as I can tell, this functionality exists only in Magit and is not part of Git. It’s yet another reason to be using Magit (and, of course, Emacs). Take a look at Jenkins’ post for the details and more background. Also take a look at the documentation to see its full functionality.

This entry was posted in General and tagged , . Bookmark the permalink.
  • NoonianAtall

    Thanks for reminding me about this. Could have used this today but I forgot it existed, so I did it manually.

  • Eric James Michael Ritz

    That's cool that Magit provides that command, but the original article you link to makes it sound more difficult to deal with than it really is. This accomplishes the same thing: 'git stash; git reset --hard "@{u}"; git stash branch feature-name'. Sure---it's not as easy one command in Magit, but IMO it's easy to correct quickly, in those unfortunate situations where you did not start on a separate branch to begin with (which you always should, but all of us fail to follow best practices at times).

    • NoonianAtall

      I may be mistaken, but I think the scenario here is that you've already committed changes to master that should have been in a separate branch. In this case, stash won't stash anything, and hard-resetting to an earlier commit risks losing your work (you'd have to dig it out of the reflog). So all you have to do is "git checkout -b feature-name; git checkout master; git reset --hard old-master-tree-ish".