%%{init: { 'logLevel': 'debug', 'theme': 'base', 'gitGraph': {'rotateCommitLabel': true}} }%%
gitGraph
commit id: "813faa2"
branch test
commit id: "28a8bf7"
commit id: "466fbe7"
commit id: "30bf56a"
commit id: "6159140"
This post is based on Dangit, I accidentally committed something to master that should have been on a brand new branch!
Problem
Let’s say you have just set up a new git repository. Initially, you planned to create a new branch named test to work on after the first commit, which involved editing the README.md file. However, in practice, you continued to make changes on the main branch instead.
▶ What I originally planned to do
▶ What I’ve actually done…
%%{init: { 'logLevel': 'debug', 'theme': 'base', 'gitGraph': {'rotateCommitLabel': true}} }%%
gitGraph
commit id: "813faa2"
commit id: "28a8bf7"
commit id: "466fbe7"
commit id: "30bf56a"
commit id: "6159140"
Solution: using git reset
▶ Steps
- Create a new test branch based on the current
HEADstate. - Reset the
mainbranch to the state immediately after the first commit. - Switch to the
testbranch.
▶ Commands
## Step 1: keep the current repository state into test branch
% git branch test
## Step 2: clean the main branch
% git reset 813faa2 --hard
## Step 3: moving to the test branch
% git switch test▶ Explains
- You can create a new branch based on the current HEAD without switching using
git branch <branch-name>. - Using
git reset --hardinstead ofgit reset --softensures that by default, changes are not left in the current branch’s index or files. - If changes remain in the current branch, you would need to execute
git stashorgit clean.
!!WARNING
If you have already pushed to the remote repository with the wrong commits, it’s better not to execute the above solution because it could inconvenience other developers.