git: merge branch and use meaningful merge commit message?

When you have different changesets in master and the local branch, git creates an extra commit for the merge automatically. To stop such extra commits from happening, you can rebase the master in the branch before merging it to the master.

$ git pull(in master which retrieves the new changes>
$ git checkout <local_branch>
$ git rebase master 
$ git checkout master
$ git merge local_branch.

If the commit has been already done, you would just amend the commit.

If before the commit, use a git merge like in the example below:

$ git checkout mainBranch
$ git merge featureBranch --squash --no-commit

You may have to resolve conflicts.

This method avoids the automatic commit, and all files are left on the index; thus, you can commit the code with any commit message you want.


You basically have two option.

Easy solution: don't merge, Rebase
Rebase your branch on top of the main branch, resolve conflict, and then merge. As you'll have a straight history, you'll be able to fast-forward to merge and this won't create any merge commit.

git checkout feature
git rebase main
# Resolve conflict if there is
git checkout main
git merge feature

Second option: Rebase -i
You can edit your history after your merge (before you push to a remote). You can manage this with rebase interactive mode.

git checkout main
git merge feature
#You merge and resolve conflict
git rebase -i <sha of the commit before the merge>

Then you'll be taken into an interactive shell with the list of the commits, e.g.:

pick 73c991e Create progress bar module
pick b8a0b83 merge branch feature
pick 2120f47 Add user form
pick 70c55e4 Quiz prototype system

You just need to add squash or s instead of pick:

pick 73c991e Create progress bar module
pick b8a0b83 merge branch feature
s 2120f47 Add user form
pick 70c55e4 Quiz prototype system

This command would squash together b8a0b83 and 2120f47. The next step will be a commit text editor where you have both commit message combined, and it's now up to you to edit them correctly to only keep your original message.


Just pass the -m parameter to the merge command:

$ git merge other-branch -m "Commit Message"