I'm on branch master, head is pointing to my last commit A which is on master and I'm wondering if the following is possible:
All my commits are already pushed to origin, and my working directory is clean (no staged or unstaged changes).
Any guidance would be appreciated.
It's possible and it has no side effects if you didn't push the commits from B
to A
to a remote repository.
This is how you do it, in a different order than your list:
- Move all the commits from B to A (B excluded) to a new branch "experimental"
git branch experimental
git branch
creates the branch experimental
that points to the current HEAD
(which is on commit A
). The current branch remains master
.
- Revert back to a previous commit B.
- After this master's last commit should be B and "experimental"'s last commit should be A.
git reset --hard B
git reset
moves the current branch (master
) to commit B
. The --hard
option tells it to also update the index and the working tree to match the commit B
(so git status
will report "nothing to commit, working directory clean").
- Make a new commit C after B under branch master. After this master's last commit should be C
The current branch is master
. Do the changes you want, add them to the index and commit as usual.
Congratulations! Your master
just diverged from experimental
.
You must have the working tree clean before starting. That means git status
must report "nothing to commit, working directory clean" (it must also report you have untracked files that are not added to the index; you don't have to worry as long as the files are not tracked in commit B
or any later commit).
If the working tree is not clean then you can use git stash
to put the changes aside to be recovered later. When you reach step 3 you restore the stashed changes using git stash apply
.
git checkout -b experimental // Will Create and Switch your branch to "experimental" with the existing changes from master.
git push origin experimental // Will Push "experimental" to remote origin.
git checkout master // Will Switch branch back to "master"
git reset --hard <commit> // Will bring the head to the <commit> mentioned. Also, will remove uncommitted changes from "master"
git add <files> // Add files to be committed to "master"
git commit -m "new commit C" // Now you can do the new commit "C" to master which is your current branch.
git push origin master // Will Push master to remote
Hope this solves the issue.
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