TyphoonOfDvina TyphoonOfDvina - 9 days ago 4x
Git Question

Automatically generated git commit message with regex

I'd like to set up a git alias that would execute git commit with auto generated message like this:

"Affected files: [...], [...], [...]."

Whereby [...] is a regex match against respective file name.

  • I want to use it only when updating existing files (no additions, deletions).

  • If regex part is too clunky, I'd be fine with full file names.

  • Having inline comma separated list (as opposed to multi-line) is critical requirement.

  • Not having to touch message in editor is critical requirement.

I am using git bash on windows.
My skills with git are very basic (add, commit, push).



You can achieve this by placing a commit-msg hook (read: script) in the .git/hook directory of your project.

Running git diff --cached --name-status should give you all the information about the [about to be] committed files, which you can parse with awk (or a bunch of greps and cuts) and then organize it with paste. Putting it all together, your script should look more or less like this:

modified_files=`git diff --cached --name-status | awk '$1 == "M" { print $2 }'| paste -d', ' -s`
if test "" != "$modified_files"
    echo "Affected files: $modified_files" >> $1

Note that by default this will still open the editor window, but you could work around it by just running git commit -m "" (or some other message) when you commit.

Note: I tested this with /bin/sh on my Fedora 24 laptop, and it works fine. I'm not sure git bash on Windows has all of these capabilities, but at the very least it should have equivalent facilities.

As @torek suggested in the comments, this can be simplified using the --diff-filter option:

modified_files=`git diff --cached --diff-filter='M' --name-only | paste -d', ' -s`
if test "" != "$modified_files"
    echo "Affected files: $modified_files" >> $1