#!/usr/bin/env bash
# Get staged files and format them
git diff --cached --diff-filter=AM --name-only -z | xargs --null --no-run-if-empty bash -c '
  if [ $# -gt 0 ]; then
    echo "Formatting staged files: $@"
    # Avoid running bazel to build the formatter.
    # In theory it is more correct to build it since the one in bazel-out may be out-of-date.
    # However a "git commit" operation should always be fast, and accidental analysis or action cache misses are common.
    # So we take the tradeoff of running the existing binary if it exists.
    if [ -e "bazel-out/bazel_env-opt/bin/tools/bazel_env/bin/format" ]; then
      bazel-out/bazel_env-opt/bin/tools/bazel_env/bin/format "$@"
    else
      bazel run //tools/format -- "$@"
    fi
    
    # Check if any of the staged files were modified by the formatter
    if ! git diff --quiet -- "$@"; then
      echo "❌ Some staged files were modified by the pre-commit hook."
      echo "Please review and stage the changes before committing again."
      git diff --stat -- "$@"
      exit 1
    fi
  fi
' _
