Retroactively treat line of Git commits as a branch

A bunch of questions ask how to rewrite (rebase) some commits so that they appear on a branch, but these all seem to assume that rebase is actually necessary, i.e. that the commits wanted for the branch are interspersed with commits wanted on master (whether made by “you” or others).

This question is simpler: I have a clone of a repository on the master branch, and I made a bunch of commits intending to create a GitHub pull request. Normally I would have run

  • Perforce equivalent of git local commit
  • Accessing a repo in Netbeans with git
  • Using feature, story and task branches?
  • How to realise a deployment branch in Git
  • Can a branch be made from a previous changeset?
  • Git pull a certain branch from GitHub
  • git checkout -b new-feature
    

    before starting the commits, but in this case I forgot. Can I retroactively mark this sequence as commits as being on a new branch (without needing to use git rebase)?

  • Git clean/smudge filters for ansible vault secrets
  • Project using git with MonoDevelop / Windows 7
  • Github ERROR: Repository not found (yes, another one)
  • Switching Git to use SSH
  • Remove a previous commit without touching files
  • Difference between `git branch -f <branch_name> <hash>` and `git checkout <branch_name>; git reset --hard <hash>` under a clean working tree?
  • 2 Solutions collect form web for “Retroactively treat line of Git commits as a branch”

    You can move the commits to a branch and reset your master branch to where it was with:

    git branch new-feature
    git reset --hard origin/master
    

    Note that this will blow away any uncommitted changes, if that is a problem you should use git stash before starting to save them away.

    Assuming fork is a remote for your GitHub fork:

    git checkout -b new-feature origin/master
    git reset --hard master
    git push fork new-feature
    git checkout master
    git reset --hard origin/master
    

    I.e.:

    1. Create the new branch, rooted at the upstream tip.
    2. Force it to contain what was previously committed on master.
    3. Push the branch to the forked repository in preparation for a pull request.
    4. Go back to the master branch.
    5. Delete the new commits from it.

    Maybe not the most elegant solution but appears to work. Might also want to pass --set-upstream to the push.

    Git Baby is a git and github fan, let's start git clone.