Search code examples
gitversion-controlmergesquashgit-rewrite-history

Does 'git squash' (after pushing) rewrite the history?


I'm working on a separate branch for a feature.

Now I want this feature in my main branch, but just having all the commits squashed to a single one (with a recap into the commit message).

The thing is that I already pushed the branch to remote. So I'm not sure if I can perform a git merge --squash feature (from the main branch) or if that could rewrite my git history.

I don't get if git merge --squash will just create a new commit (containing, as a patch, all the changes of my merged branch. So in a safe way), or if it will remove the old commits from my branch or just do any alteration to the git history. (I want to avoid that cause I work in team).

Should I maybe opt for a commit-range cherry-pick, instead of a git squash? (but the cherry-pick would just copy all the commits without squashing them)

Or merging with squash is fine? (even after a push to the remote feature-branch)

I want to integrate my feature branch, as a single commit (possibly having all the commit messages that I get with --squash) in my main branch, but without rewriting the history.


Solution

  • No history is rewritten. From the high-level commands, only git rebase and git commit --amend perform history rewrites.

    git merge --squash simply prepares a working tree that contains all information from the branch you want to merge, just as the documentation says:

    Produce the working tree and index state as if a real merge happened (except for the merge information), but do not actually make a commit or move the HEAD, nor record $GIT_DIR/MERGE_HEAD to cause the next git commit command to create a merge commit. This allows you to create a single commit on top of the current branch whose effect is the same as merging another branch (or more in case of an octopus).