#!/bin/sh

# Get the staged files before running check so formatter changes can be restaged.
STAGED_FILES=$(git diff --cached --name-only)

echo "Running formatting, linting, and type checking..."
npm run check
if [ $? -ne 0 ]; then
  echo "Checks failed. Please fix the errors before committing."
  exit 1
fi

# Restage files that were previously staged and may have been modified by formatting. A staged path
# can also be a deletion, or live inside a submodule (native/usage is its own repository now), and
# `git add` refuses those; only paths this repository itself tracks belong in the restage.
for file in $STAGED_FILES; do
  if [ -f "$file" ] && git ls-files --error-unmatch -- "$file" >/dev/null 2>&1; then
    git add -- "$file"
  fi
done

echo "All pre-commit checks passed."
