Skip to content

Commit d350d3e

Browse files
committed
Add pre-commit PR workflow for changed files
Add a GitHub Actions workflow that runs pre-commit checks only on files changed in a pull request. The workflow triggers on PR opened/synchronize/reopened, fetches full git history to detect changed files against the base branch, and exposes that list as an output. A conditional precommit job runs only when changes exist: it checks out the PR branch, sets up Python 3.12, installs pre-commit, and executes pre-commit in CI check-only mode on the changed files (--hook-stage manual --show-diff-on-failure).
1 parent ab7bc1a commit d350d3e

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

.github/workflows/format.yml

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
name: pre-commit (PR only on changed files)
2+
3+
on:
4+
pull_request:
5+
types: [opened, synchronize, reopened]
6+
7+
jobs:
8+
detect_changes:
9+
runs-on: ubuntu-latest
10+
outputs:
11+
changed: ${{ steps.changed_files.outputs.changed }}
12+
13+
steps:
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
44+
with:
45+
fetch-depth: 0
46+
ref: ${{ github.head_ref }}
47+
48+
- name: Set up Python
49+
uses: actions/setup-python@v5
50+
with:
51+
python-version: "3.12"
52+
53+
- name: Install pre-commit
54+
run: pip install pre-commit
55+
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)