name: Repository Hygiene

on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

concurrency:
  group: hygiene-${{ github.event_name }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  hygiene:
    name: Secrets and file size
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - name: Checkout
        uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
        with:
          fetch-depth: 0

      - name: Secret scan
        uses: gitleaks/gitleaks-action@e0c47f4f8be36e29cdc102c57e68cb5cbf0e8d1e # v3.0.0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITLEAKS_CONFIG: .gitleaks.toml
          GITLEAKS_VERSION: 8.30.1

      - name: Guard against files larger than 5 MB
        env:
          BEFORE: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }}
          AFTER: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
          LIMIT_BYTES: "5242880"
        run: |
          python3 - <<'PY'
          import os
          import subprocess
          import sys

          before = os.environ["BEFORE"]
          after = os.environ["AFTER"]
          limit = int(os.environ["LIMIT_BYTES"])
          empty = "0" * 40

          if not before or before == empty:
              before = subprocess.check_output(
                  ["git", "hash-object", "-t", "tree", "/dev/null"],
                  text=True,
              ).strip()

          changed = subprocess.check_output(
              ["git", "diff", "--name-only", "--diff-filter=ACMR", before, after],
              text=True,
          ).splitlines()

          offenders = []
          for path in changed:
              if not path or not os.path.exists(path):
                  continue
              size = os.path.getsize(path)
              if size > limit:
                  offenders.append((path, size))

          if offenders:
              print("Files larger than 5 MB are not allowed in changes:")
              for path, size in offenders:
                  print(f"- {path}: {size} bytes")
              sys.exit(1)

          print(f"Checked {len(changed)} changed files; none exceed {limit} bytes.")
          PY
