From cf9bc0166433557df2a04bb05f9439580cac0b29 Mon Sep 17 00:00:00 2001 From: Sabin Shrestha Date: Mon, 21 Jul 2025 23:21:27 +0545 Subject: [PATCH] refactor: enhance pre-commit workflow with improved diff detection and caching --- .github/workflows/pre-commit.yml | 34 ++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 91ae6fd..348ed85 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -14,20 +14,46 @@ jobs: with: fetch-depth: 0 # Required for detecting diffs + - name: Fetch main branch + run: | + # Ensure we have the main branch reference for comparison + git fetch origin main:main 2>/dev/null || git fetch origin main 2>/dev/null || true + - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.12' + - name: Cache pre-commit environments + uses: actions/cache@v4 + with: + path: ~/.cache/pre-commit + key: pre-commit-${{ hashFiles('.pre-commit-config.yaml') }} + restore-keys: | + pre-commit- + - name: Install pre-commit run: | pip install pre-commit + - name: Install hook environments (cache) + run: | + pre-commit install-hooks + - name: Run pre-commit on changed files run: | - CHANGED_FILES=$(git diff --name-only origin/main...HEAD | tr '\n' ' ') - if [ -n "$CHANGED_FILES" ]; then - pre-commit run --files $CHANGED_FILES + # Use pre-commit's native diff detection with fallback strategies + if git show-ref --verify --quiet refs/heads/main; then + # Main branch exists locally, use pre-commit's native diff mode + echo "Running pre-commit with native diff detection against main branch" + pre-commit run --from-ref main --to-ref HEAD + elif git show-ref --verify --quiet refs/remotes/origin/main; then + # Origin/main exists, use it as reference + echo "Running pre-commit with native diff detection against origin/main" + pre-commit run --from-ref origin/main --to-ref HEAD else - echo "No changed files to check." + # Fallback: run on all files (for first commits or when main is unavailable) + echo "Main branch reference not found, running pre-commit on all files" + echo "⚠️ This may take longer and show more issues than normal" + pre-commit run --all-files fi