2

I have a hook that will prepend the JIRA ticket number before the commit message. I want to be able to share it with the rest of my team, which is why I am using Husky. It worked fine when in .git/hooks, however, after changing folders and calling it using Husky, I can't seem to get it to work.

I have looked at other solutions but I am not sure how to use them myself. Do I need some sort of a backup file for this operation? If so, how would I declare that?

ticket-number-to-commit-msg:

#!/bin/bash

# get branch name
branch=$(git symbolic-ref --short HEAD)

# remove ticket text
trimmed=$(echo $branch | sed -e 's:^\([^-]*-[^-]*\)-.*:\1:' -e \
    'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/')

# get ticket name (i.e., MJ-204)
jiraTicket=$(echo $trimmed | cut -f2 -d/ | tr '[:lower:]' '[:upper:]')

echo "Prepending '$jiraTicket' to commit message..."
if [[ ! -z $jiraTicket ]]; then
    # $1 is the name of the file containing the commit message
    sed -i.bak -e "1s/^/$jiraTicket\: /" $1
fi

package.json:

...
"husky": {
    "hooks": {
      "pre-commit": "./git-hooks/ticket-number-to-commit-msg"
    }
  }
...

Output:

➜ git commit -am "should prepend 'MJ-498'"
husky > pre-commit (node v10.15.0)
Prepending 'MJ-498' to commit message...
sed: -i may not be used with stdin
husky > pre-commit hook failed (add --no-verify to bypass)

Any help would be greatly appreciated. Thank you.

  • 10
    The fact that `sed` is reading stdin indicates that `$1` is the empty string. You can help mitigate this by properly quoting the variable, and writing `sed -i.bak -e "1s/^/$jiraTicket\: /" "${1:?}"` – William Pursell Jul 26 '19 at 22:42

0 Answers0