Squashing multiple git commits in history

244 views Asked by At

I have a repository with around 3000 commits where i want to squash around 250 of them in the middle of history between two dates like this:

a--b--c--d--e--f--g--h--i--j--k--l--m--n

a--b--c--d'-------------------k--l--m--n

I already know the dates and shas of d and j. What is the best practice to do this?

2

There are 2 answers

1
pratZ On BEST ANSWER

You can also try a different approach which is kind of similar to the merge approach.

Note: Assuming n to be the latest and a be the oldest commit.

Create a new branch with commit k as head.

git checkout -b new-branch <commit hash of k>

Then, soft reset the head to the parent of commit d.

git reset --soft <commit hash of parent of d>

Commit the changes, as all the changes from commit d to k are not present in the staging area. (git status to verify)

git commit

Merge the commits post k,

git cherry-pick l^...n # Use SHA's of l and n
6
Andrejs Cainikovs On

Assuming a is the oldest, n is the latest commit:

git rebase method:

    git rebase <sha_of_d> -i
    # replace *pick* with *squash* for commits e..j
    # save and quit

git merge method:

    git reset --hard <sha_of_d>
    git merge --squash <sha_of_k>
    git commit
    git cherry-pick <sha_of_l>^..<sha_of_n>

Please note:

  • git reset --hard will throw away all your uncommitted changes.

  • git cherry-pick ranges are supported starting from git v1.7.2.