0

Often I want to squash several dozen commits in a junk branch to test things out on a staging server. Specially when using an issue tracker with issue auto-closing feature like bitbucket - I don't want to close the issues mentioned in the commit messages at that moment, so I need to squash.

There has to be something easier than changing each line individually on rebase or having to know how many commits ago is the target of the squash.

Something like "Squash everything until this commit with hash XXXXXX"

3 Answers 3

3

Yes, when you use rebase in interactive mode, you can squash commits by marking them to be squashed. Refer:

  1. https://robots.thoughtbot.com/git-interactive-rebase-squash-amend-rewriting-history#squash-commits-together
  2. http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html

You could also try git merge --squash which is a more direct approach and something that you are looking for - https://stackoverflow.com/a/5190323/7274758

Let us say you have the following set of commits

O - O - L1 - F1 - F2 - F3a - F3b - F4 - .... - FN
        |     |                                \_ master, HEAD
        |     \_ Fix for Issue 1 and so on.
        |
        \_ Last Tested. You would like to squash all from this point
  1. Reset the HEAD to L1 git reset --hard L1

    O - O - L1 - F1 - F2 - F3a - F3b - F4 - .... - FN
            |     |                                
            |     \_ Fix for Issue 1 and so on.
            |
            \_ (Last Tested), master, HEAD
    
  2. Now squash everything till previous head (viz FN) git merge --squash HEAD@{1}

    O - O - L1 - F1 - F2 - F3a - F3b - F4 - .... - FN
            | \ 
            |  \_ 0
            |
            \_ (Last Tested), master, HEAD
    
  3. Perform the commit - git commit This would commit all changes from F1 to FN (SF1_FN)

    O - O - L1 - SF1_FN
                |
                \_ master, HEAD
    
2

The most automatic way to do it is with git merge --squash. Whether you should use Libin Varghese's answer or this one probably depends on whether you intend to keep the original commits. If not, what he spells out is straightforward. But if so...

If you have

A --- B --- C --- D <--(branch)

and you want to squash B, C, and D, you could do

git checkout B^
git checkout -b squashed_branch
git merge --squash branch
git commit

and now you have

A --- B --- C --- D <--(branch)
  \
    BCD <--(squashed_branch)
1
  • Wish I could accept both answers, but yes, I want to keep the original commits. I guess @Libin Varghese also considered this and meant to do stuff after branching out to the junk branch.
    – rzb
    Commented Mar 3, 2017 at 0:30
0
git checkout --orphan wip
git commit

If you're just testing content you don't need ancestry.

Not the answer you're looking for? Browse other questions tagged or ask your own question.