This is a use case which has come up a couple of times. Because I'm (unfortunately) not in the habit of branching for every feature, sometimes I start work on a task, make a couple of commits, and then say "Crap...this is more complicated than I thought...I wish I'd created a branch three commits ago."
At that point, I can go back to a particular commit and branch from there, but that leaves those new commits on the master, and not on the feature branch. I could cherry-pick each commit, or maybe rebase it onto the new branch somehow, but that still leaves the branch commits on the master.
How can I make this happen?
To hard reset files to HEAD on Git, use the “git reset” command with the “–hard” option and specify the HEAD. The purpose of the “git reset” command is to move the current HEAD to the commit specified (in this case, the HEAD itself, one commit before HEAD and so on).
Git Checkout File Checking out a file is similar to using git reset with a file path, except it updates the working directory instead of the stage. Unlike the commit-level version of this command, this does not move the HEAD reference, which means that you won't switch branches.
Remember that the HEAD is Git's way of referring to the current snapshot. Internally, the git checkout command simply updates the HEAD to point to either the specified branch or commit. When it points to a branch, Git doesn't complain, but when you check out a commit, it switches into a “detached HEAD” state.
Shortest thing to do:
Suppose you are on master and you realize the last two commits on master should be on a feature branch:
git branch feature-A
git reset --hard HEAD~2
That's it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With