-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest-after-edit.sh
More file actions
executable file
·84 lines (73 loc) · 2.43 KB
/
Copy pathtest-after-edit.sh
File metadata and controls
executable file
·84 lines (73 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/bin/bash
# test-after-edit.sh
# PostToolUse hook for Edit|Write tools.
# After a file is written, attempts to locate and run a related test file.
# Test file discovery rules:
# foo.ts -> foo.test.ts, foo.spec.ts (same dir or __tests__/ sibling)
# foo.js -> foo.test.js, foo.spec.js
# foo.tsx -> foo.test.tsx, foo.spec.tsx
# foo.py -> test_foo.py, foo_test.py (same dir or tests/ sibling)
# foo.rb -> foo_spec.rb (same dir or spec/ sibling)
# foo.go -> foo_test.go (same dir)
# Non-blocking: always exits 0 regardless of test results.
set -euo pipefail
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
if [ -z "$FILE_PATH" ] || [ ! -f "$FILE_PATH" ]; then
exit 0
fi
DIR=$(dirname "$FILE_PATH")
BASENAME=$(basename "$FILE_PATH")
NAME="${BASENAME%.*}"
EXT="${BASENAME##*.}"
run_test() {
local test_file="$1"
local runner="$2"
if [ -f "$test_file" ]; then
echo "test-after-edit: running $test_file" >&2
$runner "$test_file" 2>&1 >&2 || true
return 0 # Found and attempted to run; stop searching.
fi
return 1
}
find_and_run_js_test() {
local base_dir="$1"
local name="$2"
local ext="$3"
# Check: <name>.test.<ext> and <name>.spec.<ext> in same dir.
run_test "$base_dir/$name.test.$ext" "npx jest --testPathPattern" && return 0
run_test "$base_dir/$name.spec.$ext" "npx jest --testPathPattern" && return 0
# Check inside __tests__/ sibling directory.
run_test "$base_dir/__tests__/$name.test.$ext" "npx jest --testPathPattern" && return 0
run_test "$base_dir/__tests__/$name.spec.$ext" "npx jest --testPathPattern" && return 0
return 1
}
case "$EXT" in
ts|js|tsx|jsx|mjs)
find_and_run_js_test "$DIR" "$NAME" "$EXT" || true
;;
py)
if command -v pytest &>/dev/null; then
RUNNER="pytest -q"
else
RUNNER="python -m pytest -q"
fi
run_test "$DIR/test_${NAME}.py" "$RUNNER" ||
run_test "$DIR/${NAME}_test.py" "$RUNNER" ||
run_test "$DIR/../tests/test_${NAME}.py" "$RUNNER" || true
;;
rb)
if command -v rspec &>/dev/null; then
run_test "$DIR/${NAME}_spec.rb" "rspec" ||
run_test "$DIR/../spec/${NAME}_spec.rb" "rspec" || true
fi
;;
go)
# Go tests live alongside source files with _test.go suffix.
run_test "$DIR/${NAME}_test.go" "go test" || true
;;
*)
# No test discovery configured for this file type.
;;
esac
exit 0