| 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 to N, `git diff` writes its first N |
| 13 | # NUL-terminated fields and then one byte of the next, |
| 14 | # with no NUL after it, as a diff cut short would |
| 15 | tool="${0##*/}" |
| 16 | real="$(PATH="$SHIM_REAL_PATH" command -v "$tool")" || { |
| 17 | echo "fail-nth: no real $tool on $SHIM_REAL_PATH" >&2 |
| 18 | exit 127 |
| 19 | } |
| 20 | if [ "${SHIM_TOOL:-}" = "$tool" ]; then |
| 21 | n=$(($(cat "$SHIM_COUNT") + 1)) |
| 22 | echo "$n" > "$SHIM_COUNT" |
| 23 | if [ "$n" -eq "${SHIM_FAIL_AT:-0}" ]; then |
| 24 | echo "$tool: injected failure of call $n" >&2 |
| 25 | exit "${SHIM_STATUS:-2}" |
| 26 | fi |
| 27 | fi |
| 28 | if [ -n "${SHIM_TRUNCATE:-}" ] && [ "$tool" = git ] && [ "${1:-}" = diff ]; then |
| 29 | PATH="$SHIM_REAL_PATH" |
| 30 | whole="$(mktemp)" |
| 31 | "$real" "$@" > "$whole" || exit |
| 32 | head -z -n "$SHIM_TRUNCATE" "$whole" |
| 33 | tail -z -n +"$((SHIM_TRUNCATE + 1))" "$whole" | head -c 1 |
| 34 | rm -f "$whole" |
| 35 | exit 0 |
| 36 | fi |
| 37 | exec "$real" "$@" |