Skip to content

Pre-commit hook fails when no hook scripts exist #37

@Defilan

Description

@Defilan

Problem

The pre-commit hook runner in git/hooks/pre-commit fails when no *.pre-commit scripts exist in ~/.dotfiles/git/hooks/.

The glob $hooks/*.$hook_type doesn't expand when there are no matching files, so the shell tries to execute the literal string ~/.dotfiles/git/hooks/*.pre-commit as a command, which fails:

Executing pre-commit hook(s)
.git/hooks/pre-commit: line 14: /Users/defilan/.dotfiles/git/hooks/*.pre-commit: No such file or directory
Commit Failed.

This blocks all commits unless --no-verify is used.

Root Cause

for hook in $hooks/*.$hook_type; do
    echo ""
    echo "${COLOR_LIGHTPURPLE}Executing ${hook}${COLOR_NONE}"
    ${hook}
    EXIT_CODE=$((${EXIT_CODE} + $?))
done

When the glob has no matches, bash iterates once with the literal unexpanded glob string.

Fix

Add a guard before executing:

for hook in $hooks/*.$hook_type; do
    [ -f "$hook" ] || continue
    echo ""
    echo "${COLOR_LIGHTPURPLE}Executing ${hook}${COLOR_NONE}"
    ${hook}
    EXIT_CODE=$((${EXIT_CODE} + $?))
done

Or use nullglob at the top of the script.

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