#!/bin/sh

# Only normalize and validate the first non-empty, non-comment subject line.
set -u

message_file="${1:-}"
[ -n "$message_file" ] && [ -f "$message_file" ] || exit 0
[ "${PAI_SKIP_HOOKS:-0}" = "1" ] && exit 0

subject="$(sed -n -e 's/\r$//' -e '/^#/d' -e '/^[[:space:]]*$/d' \
    -e '1p' "$message_file")"

if [ -z "$subject" ]; then
  printf '%s\n' '[commit-msg] 标题为空，请使用 type(scope): 描述' >&2
  exit 1
fi

case "$subject" in
  Merge*|Revert*|fixup!*|squash!*) exit 0 ;;
esac

# The project uses Chinese descriptions, so the check only constrains the
# conventional type and the presence of a non-empty description.
if ! printf '%s' "$subject" | grep -Eq \
  '^(feat|fix|refactor|perf|test|docs|build|ci|chore|revert|wip)(\(.+\))?:[[:space:]]*[^[:space:]].*$'; then
  printf '%s\n' '[commit-msg] 标题格式应为 type(scope): 描述' >&2
  exit 1
fi

exit 0
