Skip to content

Commit 892da6a

Browse files
committed
Run pre-commit on PR changed files only
Switch workflow to run pre-commit only for pull requests and only on files changed in the PR. Adds a detect_changes job to fetch the base ref and output changed file list, then a conditional precommit job that runs only when there are changed files. Updates checkout and setup actions (actions/checkout@v4, setup-python@v5), bumps Python to 3.12, installs pre-commit, and runs pre-commit in a CI check-only mode on the changed files to speed up CI and avoid running on the whole repo.
1 parent caef5a8 commit 892da6a

File tree

1 file changed

+48
-10
lines changed

1 file changed

+48
-10
lines changed

.github/workflows/format.yml

Lines changed: 48 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,61 @@
1-
name: pre-commit-format
1+
name: pre-commit (PR only on changed files)
22

33
on:
4-
push:
5-
branches: [main]
64
pull_request:
7-
branches: [main]
5+
types: [opened, synchronize, reopened]
86

97
jobs:
10-
pre_commit_checks:
8+
detect_changes:
119
runs-on: ubuntu-latest
10+
outputs:
11+
changed: ${{ steps.changed_files.outputs.changed }}
12+
1213
steps:
13-
- uses: actions/checkout@v6
14+
- name: Checkout full history
15+
uses: actions/checkout@v4
16+
with:
17+
fetch-depth: 0
18+
19+
- name: Detect changed files
20+
id: changed_files
21+
run: |
22+
git fetch origin ${{ github.base_ref }}
23+
CHANGED_FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD)
24+
25+
{
26+
echo "changed<<EOF"
27+
echo "$CHANGED_FILES"
28+
echo "EOF"
29+
} >> "$GITHUB_OUTPUT"
30+
31+
- name: Show changed files
32+
run: |
33+
echo "Changed files:"
34+
echo "${{ steps.changed_files.outputs.changed }}"
35+
36+
precommit:
37+
needs: detect_changes
38+
runs-on: ubuntu-latest
39+
if: ${{ needs.detect_changes.outputs.changed != '' }}
40+
41+
steps:
42+
- name: Checkout PR branch
43+
uses: actions/checkout@v4
1444
with:
1545
fetch-depth: 0
1646
ref: ${{ github.head_ref }}
1747

18-
- uses: actions/setup-python@v6
48+
- name: Set up Python
49+
uses: actions/setup-python@v5
1950
with:
20-
python-version: '3.10'
51+
python-version: "3.12"
52+
53+
- name: Install pre-commit
54+
run: pip install pre-commit
2155

22-
- run: pip install pre-commit
23-
- run: pre-commit run --all-files
56+
- name: Run pre-commit (CI check-only stage) on changed files
57+
env:
58+
CHANGED_FILES: ${{ needs.detect_changes.outputs.changed }}
59+
run: |
60+
mapfile -t files <<< "$CHANGED_FILES"
61+
pre-commit run --hook-stage manual --files "${files[@]}" --show-diff-on-failure

0 commit comments

Comments
 (0)