#!/usr/bin/env bash
# Checks commit prose and trailers with the commit message hook.
set -euo pipefail
cd "$(dirname "$0")/.."

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT

accept() {
  cat > "$work/message"
  if ! sh .githooks/commit-msg "$work/message" > "$work/output" 2>&1; then
    printf 'commit-msg-test: valid message rejected\n' >&2
    cat "$work/output" >&2
    exit 1
  fi
}

reject() {
  cat > "$work/message"
  if sh .githooks/commit-msg "$work/message" > "$work/output" 2>&1; then
    printf 'commit-msg-test: invalid message accepted\n' >&2
    cat "$work/message" >&2
    exit 1
  fi
  grep -q "$1" "$work/output"
}

# The next word has 13 characters. Its preceding line has 60, so the combined
# line has 74 characters and cannot fit the 72-column limit.
accept <<'MESSAGE'
Reflow comments and expand event literals

Comment paragraphs use the repository reflow tool, and event literals
put each field on its own line. The Telegram request comment
distinguishes method-bearing setup errors from safe network causes. Code
behavior and error values stay unchanged.

Issue: 3cdc678
MESSAGE

reject 'unnecessary line break after line 3' <<'MESSAGE'
Reflow comments and expand event literals

Comment paragraphs use the repository reflow tool, and event
literals put each field on its own line. The Telegram request comment
distinguishes method-bearing setup errors from safe network causes. Code
behavior and error values stay unchanged.

Issue: 3cdc678
MESSAGE

accept <<'MESSAGE'
Check a filled paragraph

The paragraph fills each line before the next word starts another line.
Its next word does not fit the line before it.

Issue: abc1234
MESSAGE

reject 'longer than 72 characters' <<'MESSAGE'
Reject a wide paragraph

This paragraph has more than seventy-two characters because this extra word extends it.

Issue: abc1234
MESSAGE

reject 'unnecessary line break after line 3' <<'MESSAGE'
Reject a short paragraph line

This line can hold
the next word.

Issue: abc1234
MESSAGE

accept <<'MESSAGE'
Keep trailer lines separate

The message has a body.

Issue: abc1234
Parent: def5678
MESSAGE

accept <<'MESSAGE'
Keep formatted blocks separate

- First list item
- Second list item

    first example line
    second example line

Issue: abc1234
MESSAGE

printf 'commit-msg-test: all cases pass\n'
