#!/bin/bash
## Error presentation: when child git fails, our message leads and git's
## stderr follows indented beneath it (in a multi-file patch it's the only
## source of which file or hunk failed); patch paths in our messages are
## relative to the patches dir and quoted.
set -euo pipefail
cd "$(dirname "$0")"
source ./lib.sh

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

make_corpus "$work/corpus"
source "$work/corpus/FACTS"

"$PATCHETTE" export "$work/corpus/dev" "$work/patches" "$base" topic/fancy >/dev/null
# Corrupt a context line in the diff so git apply itself fails.
sed -i 's/^ gear 4 turns smoothly$/ gear 4 turns wrongly/' "$work/patches/topic¦fancy/teach-gizmo-to-hum.patch"

rc=0
"$PATCHETTE" verify "$work/corpus/dev" "$work/patches" >"$work/out" 2>&1 || rc=$?
EXPECT equal "an unapplicable diff still fails verify" -- "$rc" "1"
EXPECT success "our message leads, with the patch path relative and quoted" -- \
	grep -q "^patchette: 'topic¦fancy/teach-gizmo-to-hum.patch': diff does not apply onto its parent$" "$work/out"
EXPECT success "git's own stderr follows, indented as detail" -- \
	grep -q "^    error: patch failed" "$work/out"
ours=$(grep -nm1 '^patchette:' "$work/out") && ours=${ours%%:*}
detail=$(grep -nm1 '^    error:' "$work/out") && detail=${detail%%:*}
EXPECT success "and in that order" -- \
	test "$ours" -lt "$detail"

exit "$RESULT"
