DEV Community

David Cantrell
David Cantrell

Posted on • Updated on

I have banned 'git commit -a'

Some time ago I wrote that git commit -a ... was my least favourite git command, because it "makes it too easy to commit many unrelated changes with an unhelpful message. And of course I use it all the damned time."

Well, I finally got sufficiently annoyed at myself to do something about it.

On one of my machines this now lives in my ~/bin, which is first in my $PATH. Only time will tell whether I find it more annoying than what it prevents:

#!/bin/bash

set -euo pipefail

function main {
    MYDIR="$( cd "$(dirname "$0")"; pwd -P)"
    export PATH=$(
        echo $PATH | sed -E "
            s@$MYDIR@@g
            s/::/:/g
            s/^:+//
            s/:+\$//
        "
    )

    if [ "$#" -ge 2 ] && [ "$1" == "commit" ]; then
        for i in "$@"; do
            if [ "$i" == "-a" ] || [ "$i" == "--all" ]; then
                echo NO\! SHAN\'T\! $i is BAD\!
                exit 1;
            fi
        done
    fi
    exec git "$@"
}

main "$@"
Enter fullscreen mode Exit fullscreen mode

Update: 24 Apr 2020: I've moved this code into a function that is sourced into my shell and which also applies some default args to git log. I've found it sufficiently un-annoying and useful that it's now part of my config on every machine I use.

Patches welcome on Github!

Top comments (2)

Collapse
 
kwstannard profile image
Kelly Stannard

I have run into this too which is part of why I did this: dev.to/kwstannard/how-to-plan-an-i...

It uses -a but, this allows me to very quickly commit while saving the information for git to use in a later squash. Since I can do it quickly without thinking too hard I can commit often and get fine grained commits and less unrelated changes in commits.

Collapse
 
cescquintero profile image
Francisco Quintero 🇨🇴

Nice approach. I also am guilty of using git commit -a for many files(some unrelated) but I just live with it.

However, what I do try to do every time I can, is adding patches of files with git add -p and choosing a patch.

This one is sometimes complicated because if the patches are too close, Git treats them as one :(