Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically swap last two commits

Tags:

git

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.

like image 475
nneonneo Avatar asked Apr 24 '13 22:04

nneonneo


People also ask

What is a convenient way to swap last two commits?

Changing the Last Commit: git commit --amend. The git commit --amend command is a convenient way to modify the most recent commit.

How do I see changes between two commits?

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..

How do I change the order of my commits?

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.

Can we compare two commits in git?

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.


1 Answers

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.

like image 117
Neil Forrester Avatar answered Oct 02 '22 13:10

Neil Forrester