git – How to split/glue an old commit?

Question:

A task from the field of synthetic, you need to understand how to do it correctly.

There is a history of 3 commits

git log --oneline
cccccc change c.txt
bbccaa add new two file (b.txt, c.txt) and change a.txt
aaaaaa add new file a.txt

Task 1: divide bbccaa by two so that the result is

git log --oneline
cccccc change c.txt
aaa111 change a.txt
bbbccc add two file (b.txt, c.txt)
aaaaaa add new file a.txt

Task 2: glue partially bbbccc with aaaaaa to get it out

git log --oneline
cccccc change c.txt
aaa111 change a.txt
ccc111 add file c.txt
aaabbb add files a.txt b.txt    

Answer:

Both are done with rebase (the scariest command in the git 🙂 ).

Let's start with the second one, as the simpler one.

git rebase -i HEAD~3

-i – interactive mode, HEAD~3 – last three commits.

The default editor will open with a list of commits. Older ones at the top, newer ones at the bottom (reverse to git log output!) Each will be labeled pick (that is, "take"). We find the commits that need to be merged and write s or squash opposite the top one from the pair. Save. Git itself will roll back the specified commits, and then roll on a new one. The commit message will be taken from the paired commit. If you need to correct it, then write edit opposite it – when rolling the commit, a standard editor window will open to enter the commit message.

Separation is a little more difficult. To do this, select a commit, write edit opposite it and save. Git will roll back the commits (not just the one that is selected, but everything up to the most recent – you need to understand this!). And he will start rolling them over again. When it comes to the one marked edit, it will be thrown out to the console. At this point, using git add/git reset (I like to use git add -i if you need to add "pieces") fix the commit, you can do one or two more, and then issue the command git rebase --continue and git will continue to roll commits . It is important to understand that the sha hashes of new commits will change.

For additional instructions, as always, read the help .

Scroll to Top