TyphoonOfDvina
TyphoonOfDvina

Reputation: 185

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 the respective file name.

I am using git bash on windows.

Upvotes: 2

Views: 1170

Answers (2)

Mureinik
Mureinik

Reputation: 312289

You can achieve this by placing a commit-msg hook (read: script) in the .git/hooks 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"
then
    echo "Affected files: $modified_files" >> $1
fi

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.

EDIT:
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"
then
    echo "Affected files: $modified_files" >> $1
fi

Upvotes: 3

HappyFace
HappyFace

Reputation: 4133

Needs zsh, GNU sed, ripgrep and NightMachinary/prefixer.

trimsed () {
    gsed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
}
git-commitmsg () {
    local msg="$(git -c color.status=false status | command rg --color never -e 'deleted:' -e 'modified:' -e 'new file:'| trimsed | prefixer --skip-empty -o '; ')"
    print -r -- "${msg:-.}"
}

Upvotes: 0

Related Questions