25 Mar 2013, 22:59

Git tip: rebase --autosquash

I found the --autosquash argument of git rebase --interactive to be very useful for my workflow. I usually keep a development branch, where I commit early and often. This means I'm usually left with a commit containing the actual feature, and then some smaller commits fixing bugs and other issues, that I later squash together using git rebase --interactive

Starting on 1.7.4, Git has two flags on commit that can help people who work this way: --fixup and --squash. They let you mark a commit as fixing up another one, and will automatically sort the commits on rebase --interactive as well as change the action to fixup or squash, respectively.

Here is an example case of how you would use --fixup

$ # We implement some awesome feature here
$ nano drivers/clk/sunxi/clk-sunxi.c
$ git add drivers/clk/sunxi/clk-sunxi.c
$ git commit -sm "clk: sunxi: implement some big feature"
[sunxi-clk 0867eea] clk: sunxi: implement some big feature
 1 file changed, 1 insertion(+)
$ # Then we enable it on the device tree
$ nano arch/arm/boot/dts/sun4i-a10-cubieboard.dtb
$ git add arch/arm/boot/dts/sun4i-a10-cubieboard.dts
$ git commit -sm "ARM: sunxi: enable the big feature"
[sunxi-clk b7f2640] ARM: sunxi: enable the big feature
 1 file changed, 1 insertion(+)
$ # And then we find a bug we need to fix!
$ nano drivers/clk/sunxi/clk-sunxi.c
$ git add drivers/clk/sunxi/clk-sunxi.c
$ git commit -s --fixup HEAD^
[sunxi-clk e9abc64] fixup! clk: sunxi: implement some big feature
 1 file changed, 1 insertion(+)
$ # Eventually we rebase
$ git rebase --interactive --autosquash torvalds/master

To make them even easier to use, you can add the following to your ~/.gitconfig:

[alias]
     fixup = !sh -c 'git commit --fixup=$1' -
     squash = !sh -c 'git commit --squash=$1' -
     ri = rebase --interactive --autosquash

Then you will be able to use git fixup, git squash and git ri, which are considerably easier to type and remember

Hat tip to Technosorcery for being the site on where I discovered this great feature