I know how to swap the last two commits using git rebase
interactively (git rebase -i HEAD~2
, ddjp:x
in Vim), but I'd like to do it programmatically with a wrapper script since it's something I end up doing relatively often.
To be more concrete, I want to rewrite history from
A---B---C---D HEAD
to
A---B---D---C HEAD
in an entirely scripted manner. Ideally, if the swap fails, it should either allow me to fix it interactively or just give up and tell me to do it manually.
Changing the Last Commit: git commit --amend. The git commit --amend command is a convenient way to modify the most recent commit.
To see the changes between two commits, you can use git diff ID1.. ID2 , where ID1 and ID2 identify the two commits you're interested in, and the connector .. is a pair of dots. For example, git diff abc123.. def456 shows the differences between the commits abc123 and def456 , while git diff HEAD~1..
The command you're looking for is git rebase , specifically the -i/--interactive option. I'm going to assume you want to leave commit c on branch A, and that you really do mean you want to move the other commits to the other branches, rather than merging, since merges are straightforward.
You can compare files between two Git commits by specifying the name of the ref that refers to the commits you want to compare. A ref may be a commit ID or HEAD, which refers to the current branch. Let's compare two commits in our Git repository. The above command will perform a diff operation across our two commits.
This should do it:
git tag old git reset --hard HEAD~2 git cherry-pick old git cherry-pick old~1 git tag -d old
First, you tag the place where you are as old
, then go back two commits, git cherry-pick
the commits in the other order, and delete the old
tag.
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