Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge (with squash) all changes from another branch as a single commit

Tags:

git

In Git, is there a way to merge all changes from one branch into another, but squash to a single commit at the same time?

I often work on a new feature in a separate branch and will regularly commit/push - mainly for backup or to transfer what I'm working on to another machine. Mostly those commits say "Feature xxx WIP" or something redundant.

Once that work is finished and I want to merge WIP branch back into master, I'd like to discard all those intermediate commits, and just a have a single clean commit.

Is there an easy way to do this?

Alternatively, how about a command that squashes all commits on a branch since the point where it was branched?

like image 768
Brad Robinson Avatar asked Sep 12 '10 23:09

Brad Robinson


People also ask

How do I merge squash and branch commits?

You can choose to squash merge when completing a pull request in Azure Repos. Choose Squash commit under Merge type in the Complete pull request dialog to squash merge the topic branch.

What happens if you squash a merge commit?

Many of the git tricks exploit the way git walks the commit graph, and squashing creates a different graph from merging. Specifically, squashing throws away all our hard work in building a specific commit graph. Instead, squashing takes all the changes and squashes them together into a single commit.


2 Answers

Found it! Merge command has a --squash option

git checkout master git merge --squash WIP 

at this point everything is merged, possibly conflicted, but not committed. So I can now:

git add . git commit -m "Merged WIP" 
like image 45
Brad Robinson Avatar answered Sep 27 '22 19:09

Brad Robinson


Another option is git merge --squash <feature branch> then finally do a git commit.

From Git merge

--squash

--no-squash

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).

like image 113
fseto Avatar answered Sep 27 '22 18:09

fseto