regexgitpre-commit-hook

Git commit hook to prepend message


I originally had a slightly different need and was given a great answer: Prepend Git commit message with partial branch name

However, my needs have changed a bit and the regex I have is not working as intended, I'm hoping someone can give me a little guidance.

My current branch naming convention is: bug/ab-123/branch-description

What I need to do is prepend every git commit message with the values in between each forward slash, so in this case ab-123. Additionally, I'd like it capitalized as AB-123.

The end result I'm looking for is:

AB-123 my commit message goes here

My current prepare-commit-message regex is:

branch=$(git symbolic-ref --short HEAD)

trimmed=$(echo "$branch" | sed -e 's:^[a-z]+\/\([a-z]{2,}-\d+\):\1:' -e \
    'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/')

echo $trimmed | sed -e 's/f/b/' | tr [a-z] [A-Z] | awk '{print("ls " $1)}'

This does nothing however. Any ideas on what I'm doing wrong? Thanks!


Solution

  • You don't really need regular expressions if you've got a nice delimited string like that:

    branch=$(git symbolic-ref --short HEAD)
    trimmed=$(echo $branch | cut -f2 -d/ | tr '[:lower:]' '[:upper:]')
    

    So given:

    $ git status
    On branch bug/ab-123/foobar
    nothing to commit, working directory clean
    

    We get:

    $ branch=$(git symbolic-ref --short HEAD)
    $ echo $branch
    bug/ab-123/foobar
    

    And:

    $ trimmed=$(echo $branch | cut -f2 -d/ | tr '[:lower:]' '[:upper:]')
    $ echo $trimmed
    AB-123
    

    And this gives you "the values in between each forward slash", converted to uppercase.