Skip to content

Commit 7af99ef

Browse files
Fix pre-commit hook to handle swiftformat better (#308)
- Use --lint to detect formatting issues first - Prompt user interactively before making changes [f/r/a] - Fail fast in non-interactive mode (CI) - Use /dev/tty for interactive prompts in git hooks Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com>
1 parent 43c83f4 commit 7af99ef

1 file changed

Lines changed: 48 additions & 7 deletions

File tree

Scripts/git-hooks/pre-commit

Lines changed: 48 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,57 @@
11
#!/bin/bash
22
set -euo pipefail
33

4-
repo_root="$(git rev-parse --show-toplevel)"
5-
cd "$repo_root"
4+
cd "$(git rev-parse --show-toplevel)"
65

7-
# Verify mise is available
86
if ! command -v mise >/dev/null 2>&1; then
97
echo "mise is required. Refer to Example/README.md for setup instructions." >&2
108
exit 1
119
fi
1210

13-
# Use mise exec to ensure we run the versions specified in .mise.toml,
14-
# regardless of what's installed globally via Homebrew or other means
15-
echo "Running SwiftFormat..."
16-
mise exec -- swiftformat .
11+
staged_swift_files=$(git diff --cached --name-only --diff-filter=d | grep '\.swift$' || true)
12+
13+
if [ -z "$staged_swift_files" ]; then
14+
exit 0
15+
fi
16+
17+
echo "Checking SwiftFormat..."
18+
if mise exec -- swiftformat --lint $staged_swift_files 2>/dev/null; then
19+
exit 0
20+
fi
21+
22+
echo ""
23+
echo "SwiftFormat found formatting issues."
24+
25+
format_files() {
26+
echo "Formatting..."
27+
mise exec -- swiftformat $staged_swift_files
28+
}
29+
30+
if [ ! -e /dev/tty ]; then
31+
echo "Run 'swiftformat .' to fix, then commit again."
32+
exit 1
33+
fi
34+
35+
echo ""
36+
echo " [f] Fix and commit"
37+
echo " [r] Review - fix only, abort to review"
38+
echo " [a] Abort"
39+
echo ""
40+
read -r -p "Choice [f/r/a]: " choice < /dev/tty
41+
42+
case "$choice" in
43+
f|F)
44+
format_files
45+
git add $staged_swift_files
46+
echo "Proceeding with commit."
47+
;;
48+
r|R)
49+
format_files
50+
echo "Fixed but not staged. Run 'git diff' to review, then 'git add -u' and commit."
51+
exit 1
52+
;;
53+
*)
54+
echo "Aborted."
55+
exit 1
56+
;;
57+
esac

0 commit comments

Comments
 (0)