Git alias to squash feature-branch commits

Viewed 396

I'm frequently squashing all the commits on a feature branch before committing to master. Here's what I do currently:

git checkout master
git merge --squash {branch}
git commit -m "{feature_summary}"

Is there an git alias I can use to do this? The aliases I'm familiar with (e.g. stashes = stash list or uncommit = reset --soft HEAD~1) don't store variables, and in this case the second command needs to know which branch we came from at the beginning of the commands, so I imagine has to store this information.

Ideally I'd like a git alias such as git squash which does all those commands. I'm fine with either expecting a string as the commit message, or opening an editor to enter the message.

3 Answers

You can use the @{-1} construct which means "last checked out branch", and pass a parameter to an ad-hoc bash function :

# ms for merge-squash but call it as you prefer
git config --global alias.ms '!f() { git checkout master && git merge --squash @{-1} && git commit -m "$1"; }; f'

then an example use could be, from your feature branch :

git ms "My commit message"

You can create an alias yourself:

[alias]
    sf = !git checkout master && git merge --squash "$1" && git commit -m "$2"

You can run it with

git sf <branch> "<message>"

If you have in your PATH a program called git-command, git will use that program when you call git command [args].

So you can add the following script to your PATH, name it git-squash and make it executable.

#!/bin/bash
branch="${1}"
shift
git checkout master \
&& git merge --squash "${branch}" \
&& git commit "${@}"
Related