#!/bin/sh

# Only format/lint staged Swift files
FILES=$(git diff --cached --name-only --diff-filter=ACM -- '*.swift')
[ -z "$FILES" ] && exit 0

# Stash unstaged changes so formatters only touch the index snapshot.
# Without this, re-staging formatted files below would clobber any
# partial staging from `git add -p`.
STASHED=0
if ! git diff --quiet; then
    git stash push --keep-index --quiet -m "pre-commit-$$"
    STASHED=1
fi

restore_unstaged() {
    [ "$STASHED" = "1" ] || return 0
    git stash pop --quiet 2>/dev/null || \
        echo "pre-commit: could not auto-restore unstaged changes; run 'git stash pop' manually" >&2
}
trap restore_unstaged EXIT

echo "$FILES" | xargs swiftformat 2>/dev/null
echo "$FILES" | xargs swiftlint lint --fix 2>/dev/null | grep -v "^Linting\|^Done linting"
echo "$FILES" | xargs git add
