gunk-dev/the-valley

fail-nth.sh

sourcec56194c96d85main's published tip history
1.3 KiB
1# shellcheck shell=bash
2# A stand-in for one tool, linked first on PATH under that tool's name. It
3# passes every call through to the real tool, except that it can fail one
4# call on purpose, so a check can fail each call a program makes in turn
5# and watch what the program does with the failure.
6#
7# SHIM_REAL_PATH the PATH to find the real tool on
8# SHIM_TOOL the tool whose calls are counted; others pass through
9# SHIM_COUNT a file holding the count of that tool's calls so far
10# SHIM_FAIL_AT the call to fail, counting from 1; 0 fails none
11# SHIM_STATUS the status the failed call exits with (default 2)
12# SHIM_TRUNCATE when set, `git diff` writes only its first
13# NUL-terminated field, as a diff cut short would
14tool="${0##*/}"
15real="$(PATH="$SHIM_REAL_PATH" command -v "$tool")" || {
16 echo "fail-nth: no real $tool on $SHIM_REAL_PATH" >&2
17 exit 127
18}
19if [ "${SHIM_TOOL:-}" = "$tool" ]; then
20 n=$(($(cat "$SHIM_COUNT") + 1))
21 echo "$n" > "$SHIM_COUNT"
22 if [ "$n" -eq "${SHIM_FAIL_AT:-0}" ]; then
23 echo "$tool: injected failure of call $n" >&2
24 exit "${SHIM_STATUS:-2}"
25 fi
26fi
27if [ -n "${SHIM_TRUNCATE:-}" ] && [ "$tool" = git ] && [ "${1:-}" = diff ]; then
28 "$real" "$@" | PATH="$SHIM_REAL_PATH" head -z -n 1
29 exit 0
30fi
31exec "$real" "$@"