Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git: Interactively rebase a range of commits

I'm trying to rebase -i a few commits that occurred a while back in my history. Say I have a log like this:

* 5e32fb0 (HEAD -> master) Add latest feature
* 106c31a Add new feature
* 2bdac33 Add great feature
...100 other commits...
* 64bd9e7 Add test 3
* 3e1066e Add test 2
* 26c612d Add test 1
* 694bdda Initialize repo

and I want to squash the 3 test commits. In these circumstances, git rebase -i HEAD~106 isn't very practical. What I'm looking for instead is something like git rebase -i 64bd9e7:26c612d.

Does git have this sort of behaviour, and if so, how can I use it?

I had a look at this post, but it didn't answer my question.

like image 453
achalk Avatar asked Jul 26 '17 20:07

achalk


People also ask

How do you rebase interactively?

You can run rebase interactively by adding the -i option to git rebase . You must indicate how far back you want to rewrite commits by telling the command which commit to rebase onto. Remember again that this is a rebasing command — every commit in the range HEAD~3..

How do you squash range of commits?

In the list of branches, select the branch that has the commits that you want to squash. Click History. Select the commits to squash and drop them on the commit you want to combine them with. You can select one commit or select multiple commits using Command or Shift .

How do I save a git rebase interactive?

Press the Esc key, type :wq! and press Enter key to save and exit the document.


1 Answers

You say "git rebase -i HEAD~106 isn't very practical".

If you mean that the resultant script file is >100 lines long, it's not great, but it'll work.

If you mean that it's tedious to count back, to work out that you need the 106 commits - as sometimes happens to me, then there is a solution.

You need the hash of the parent of the earliest commit you want, then you can do:

git rebase -i <parent-hash> my-branch

Or you can do

git rebase -i <parent-hash> HEAD

which afterwards will leave you on a detached head that you can do what you want with.

So in your example, you could have done

git rebase -i 694bdda HEAD

(But I would still agree with the other comments, about whether you really want to be changing things that far back. I think it's a bit of a code smell, when I find myself doing it. It's unusual for me to have such a long branch without pushing/sharing it. I'd make a backup branch to test it on, too.)

like image 69
ayeseeem Avatar answered Oct 21 '22 12:10

ayeseeem