#!/bin/sh
# albums commit-msg hook.
#
# Commit messages must follow Conventional Commits (type, optional scope,
# subject) with a subject of at most 50 characters. The final message is
# checked with commitlint (@commitlint/cli, config in commitlint.config.js,
# which extends @commitlint/config-conventional and sets header-max-length
# to 50). Git-generated messages that are not conventional style (e.g.
# "Merge branch ..." and "Revert ..." messages) are accepted by commitlint
# itself.

set -u
root=$(git rev-parse --show-toplevel) || exit 1
cd "$root" || exit 1
[ -f hooks/lib.sh ] || {
    echo "albums hook: cannot find hooks/lib.sh next to this hook" >&2
    echo "albums hook: (is core.hooksPath set to this repo's hooks/ directory?)" >&2
    exit 1
}
. ./hooks/lib.sh

msg_file=${1-}
[ -n "$msg_file" ] && [ -f "$msg_file" ] || hook_fail "missing commit message file" \
    "This hook expects the commit message file as its first argument; this
should not happen. Re-run the git commit command."

# commitlint is a Node.js dev dependency (make install-js installs it). The
# pre-commit hook runs first and ensures dev dependencies are installed, but
# be explicit if it is missing anyway (e.g. after a fresh clone).
[ -x node_modules/.bin/commitlint ] || hook_fail "commitlint is not installed" \
    "Install the Node.js dev dependencies, then re-run the git commit command:
  make install-js  # or: npm ci
  git commit -m '<type>: <subject>'"

if ! npx --no-install commitlint --edit "$msg_file"; then
    hook_fail "the commit message is not Conventional Commits style" \
"Write the subject as '<type>(<scope>): <subject>' with a subject of at
most 50 characters. Refer to docs/developing.md.
Then re-run the git commit command, e.g.:
  git commit -m '<conventional commit subject of at most 50 characters>'"
fi
