Skip to content

Commit 3786ef0

Browse files
authored
Create autoformat.yml
1 parent 0f2455e commit 3786ef0

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

.github/workflows/autoformat.yml

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
name: Autoformat Code on Push
2+
3+
on:
4+
push:
5+
branches:
6+
- main # Adjust the branch accordingly
7+
pull_request:
8+
branches:
9+
- main # Adjust the branch accordingly
10+
11+
permissions:
12+
checks: write
13+
actions: read
14+
contents: write
15+
16+
jobs:
17+
format:
18+
runs-on: ubuntu-latest
19+
20+
env:
21+
commit_message: "No formatting changes applied"
22+
23+
steps:
24+
- name: Checkout code
25+
uses: actions/checkout@v4
26+
with:
27+
token: ${{ secrets.GITHUB_TOKEN }} # Use GitHub token to push changes
28+
29+
- name: Set up Python
30+
uses: actions/setup-python@v5
31+
with:
32+
python-version: '3.12' # Adjust to your Python version
33+
34+
- name: Install dependencies
35+
run: |
36+
python -m pip install --upgrade pip
37+
pip install -r dev-requirements.txt
38+
39+
- name: Check import sorting with isort
40+
id: isort-check
41+
run: |
42+
isort --check-only .
43+
continue-on-error: true
44+
45+
- name: Format imports with isort
46+
if: steps.isort-check.outcome == 'failure'
47+
run: |
48+
isort .
49+
50+
- name: Check code formatting with Black
51+
id: black-check
52+
run: |
53+
black --line-length=120 --preview --enable-unstable-feature=string_processing --check .
54+
continue-on-error: true
55+
56+
- name: Format code with Black
57+
if: steps.black-check.outcome == 'failure'
58+
run: |
59+
black --line-length=120 --preview --enable-unstable-feature=string_processing .
60+
61+
- name: Set commit message
62+
id: set-message
63+
run: |
64+
if [[ "${{ steps.isort-check.outcome }}" == "failure" && "${{ steps.black-check.outcome }}" == "failure" ]]; then
65+
echo "commit_message=Sorted imports with isort & Autoformat code with Black" >> $GITHUB_ENV
66+
elif [[ "${{ steps.isort-check.outcome }}" == "failure" ]]; then
67+
echo "commit_message=Sorted imports with isort" >> $GITHUB_ENV
68+
elif [[ "${{ steps.black-check.outcome }}" == "failure" ]]; then
69+
echo "commit_message=Autoformat code with Black" >> $GITHUB_ENV
70+
fi
71+
72+
- name: Commit and push changes if formatting is applied
73+
if: steps.isort-check.outcome == 'failure' || steps.black-check.outcome == 'failure'
74+
run: |
75+
git config --local user.name "github-actions[bot]"
76+
git config --local user.email "github-actions[bot]@users.noreply.github.com"
77+
if [ -n "$(git status --porcelain)" ]; then
78+
git add .
79+
git commit -m "${{ env.commit_message }}"
80+
git push origin ${{ github.ref }}
81+
else
82+
echo "No changes to commit"
83+
fi

0 commit comments

Comments
 (0)