Posted 02/28/2024
If you accidentally commit directly to master, you can safely move that commit to a new branch without losing your work. Below are two common approaches: using Bash and using SourceTree.
This approach rewinds master while keeping your changes staged. Git allows you to switch branches afterward, assuming the branches are reasonably in sync.
git reset --soft HEAD^
This removes the commit from master while preserving the changes in the index.
git checkout -b <branch>
Commit the changes. In case you want to use original commit message, you can use -c ORIG_HEAD
git commit -c ORIG_HEAD
Reset current branch to this commitMost Git GUI tools offer a similar workflow: when you select a specific commit in the history view, there is usually an option to Reset to this commit, which can be used to undo the commit on master and reapply it elsewhere.