Skip to content

Can't execute a prepare-commit-msg hook which sh works #1453

Open
@endika-campo

Description

@endika-campo

Troubleshoot
I have created an sh hook that runs correctly in the terminal creating temp files and executing it as a bash, but when I try to put the file into husky I get the following error when I try to commit:

→ No staged files match any configured task.
husky - prepare-commit-msg script failed (code 1)

The contents of the prepare-commit-msg hook are as follows:

#!/bin/sh

COMMIT_TYPE_LITERALS='feat|fix|docs|style|refactor|test|chore|perf|test|build|ci|chore|revert'

BRANCH_NAME=$(git symbolic-ref --short HEAD)
TICKET_ID=$(echo $BRANCH_NAME | grep -Eo 'CU-.{9}')
COMMIT_TYPE=$(echo $BRANCH_NAME | grep -Eo "^(${COMMIT_TYPE_LITERALS})")
COMMIT_MESSAGE=$(cat $1)

COMMIT_TYPE_PRESENT_IN_MESSAGE=$(echo $COMMIT_MESSAGE | grep -Eo "^(${COMMIT_TYPE_LITERALS}):")

if [ $COMMIT_TYPE_PRESENT_IN_MESSAGE ];
then
    echo "HOLA"
    CLEAN_COMMIT_MESSAGE=$(echo $COMMIT_MESSAGE | grep -E "^(${COMMIT_TYPE_LITERALS}):" | sed 's/^.*://')
    sed -i.bak -e "s/.*:/$COMMIT_TYPE_PRESENT_IN_MESSAGE $TICKET_ID | /" $1
else
    sed -i.bak -e "1s~^~$COMMIT_TYPE: $TICKET_ID | ~" $1
fi

I can be able to debug that the line that is failing is COMMIT_TYPE_PRESENT_IN_MESSAGE=$(echo $COMMIT_MESSAGE | grep -Eo "^(${COMMIT_TYPE_LITERALS}):"). If I comment that line, the last part of the file gets executed and works correctly. It appears as it is unable to grep inside the contents of the file COMMIT_EDITMSG.

Can't figure why... And as I stated, executing the code as a bash file with a fake COMMIT_EDITMSG file as input it works correctly...

Context
Please describe your issue and provide some context:

  • The version of terminal is zsh 5.9 on a Mac
  • Husky version 9.0.11
  • Put the aforementioned code on a file named prepare-commit-msg on a husky folder, on a git repository, and try to commit with a message.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions