Search code examples
gitversion-controlsquashgit-squash

can we squash the latest commit to a specific previous commit?


For example, if we want to squash the commit at HEAD into commit HEAD~4, we have an option by which we can do so by

  1. resetting commits from HEAD to HEAD~3
  2. building a temporary commit with same changes as our old HEAD(say, temp)
  3. stashing other staged/unstaged changes
  4. squashing temp with our old HEAD~4
  5. popping our stashed changes
  6. building commits again as older commits(HEAD~3 to HEAD).

is there any other faster and convenient way of doing the same?


Solution

  • so as @jthill suggested, there exists an autosquash option for git.

    for example, in my case, let initial case be,

    $ git log --oneline --decorate
    ddd4444 (HEAD, my-feature-branch) A fourth commit
    ccc3333 A third commit
    bbb2222 A second commit
    aaa1111 A first commit
    9999999 (master) Old stuff on master
    

    I would now add the recent changes which i wanted to squash with HEAD~4 as:

    $ git add .
    $ git commit --fixup aaa1111
    [my-feature-branch eee5555] fixup! A first commit
    

    so, my history now looks like:

    $ git log --oneline --decorate
    eee5555 (HEAD, my-feature-branch) fixup! A first commit
    ddd4444 A fourth commit
    ccc3333 A third commit
    bbb2222 A second commit
    aaa1111 A first commit
    9999999 (master) Old stuff on master
    

    now rebasing using autosquash by $ git rebase --interactive --autosquash master gives automatically picked commits with --fixup commit at the correct place.

    Following the rebase and merge with commit-message edits, you will have the commit rebased successfully!

    works like magic! :)

    source: thoughtbot