0

This is my pre-commit hook

#!/bin/sh

echo "pre-commit started"

filename="$1"
lineno=0

error() {
    echo "$1"
    exit 1
}

while read -r line
do
    [[ "$line" =~ ^#.* ]] && continue

    let lineno+=1
    length=${#line}

    if [[ $lineno -eq 1 ]]; then
        [[ $length -gt 50 ]] && error "Limit the subject line to 50 characters"
        [[ ! "$line" =~ ^[A-Z].*$ ]] && error "Capitalise the subject line"
        [[ "$line" == *. ]] && error "Do not end the subject line with a period"
    fi

    [[ $lineno -eq 2 ]] && [[ -n $line ]] && error "Separate subject from body with a blank line"
    [[ $lineno -gt 1 ]] && [[ $length -gt 72 ]] && error "Wrap the body at 72 characters"
done < "$filename"
exit 0

I am getting this error while running

› git commit -m "sfrewr"
pre-commit started
/Users/me/.git-templates/hooks/pre-commit: line 28: : No such file or directory
[master 6950a43] sfrewr
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 89

And line 28 reads

done < "$filename"
niksmac
  • 2,667
  • 3
  • 34
  • 50

2 Answers2

4

Git's pre-commit hook doesn't take any arguments, but your shell script expects one. When trying to read from an empty filename, you get the error you saw.

Since it looks like you're trying to sanity-check a commit message (a laudable goal), you probably want to use the commit-msg hook instead. It can both reject your message and edit it, should you want to do that. You can see a little more about which hooks do what by running man githooks.

bk2204
  • 64,793
  • 6
  • 84
  • 100
  • It worked but I am still getting the `line 28: : No such file or directory` message – niksmac Oct 06 '18 at 15:29
  • Did you remove the old `pre-commit` hook? As long as the old hook is present, you'll get that error. – bk2204 Oct 06 '18 at 19:04
  • May I suggest using a more structured way to manage hooks? Take a look at https://pypi.org/project/hooks4git – Lovato Oct 08 '18 at 11:35
0

I encountered the same error. Then I realized that I used a non-English character in the name of the project folder. : /