-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaction.yml
More file actions
275 lines (250 loc) · 10.3 KB
/
Copy pathaction.yml
File metadata and controls
275 lines (250 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
name: CVector Python Test
description: Setup Python dependencies and run ruff, mypy, and pytest
inputs:
python-version:
description: Python version to use
required: false
default: "3.14"
package-manager:
description: "Package manager to use: auto, uv, or poetry (auto detects from lock file)"
required: false
default: "auto"
uv-version:
description: UV version to install
required: false
default: "0.11.2"
poetry-version:
description: Poetry version to install
required: false
default: "2.3.3"
src-dirs:
description: Source directories for linting (space-separated)
required: false
default: "."
working-directory:
description: Directory containing pyproject.toml (defaults to repo root)
required: false
default: "."
run-pytest:
description: Whether to run pytest
required: false
default: "true"
repair-token:
description: "Token for git push. When provided, enables a repair step that runs after check failures: sync, ruff check --fix, ruff format, then commit and push. Use a GitHub App token so the push triggers a new workflow run. The calling workflow must checkout the PR head branch."
required: false
default: ""
runs:
using: composite
steps:
- name: Setup Python ${{ inputs.python-version }}
id: setup
uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0
with:
python-version: ${{ inputs.python-version }}
- name: Detect package manager
id: pm
shell: bash
working-directory: ${{ inputs.working-directory }}
run: |
if [ "${{ inputs.package-manager }}" != "auto" ]; then
manager="${{ inputs.package-manager }}"
elif [ -f uv.lock ]; then
manager="uv"
elif [ -f poetry.lock ]; then
manager="poetry"
else
echo "::error::No lock file found. Create uv.lock or poetry.lock, or set package-manager input."
exit 1
fi
echo "manager=${manager}" >> "$GITHUB_OUTPUT"
if [ "$manager" = "uv" ]; then
echo "run=uv run" >> "$GITHUB_OUTPUT"
echo "sync=uv sync" >> "$GITHUB_OUTPUT"
else
echo "run=poetry run" >> "$GITHUB_OUTPUT"
echo "sync=poetry install --no-interaction" >> "$GITHUB_OUTPUT"
fi
- name: Install UV
if: steps.pm.outputs.manager == 'uv'
uses: astral-sh/setup-uv@5a095e7a2014a4212f075830d4f7277575a9d098 # v7.3.1
with:
version: ${{ inputs.uv-version }}
- name: Load cached Poetry installation
if: steps.pm.outputs.manager == 'poetry'
id: cached-poetry
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: ~/.local
key: poetry-${{ inputs.poetry-version }}-python-${{ steps.setup.outputs.python-version }}
- name: Install Poetry
if: steps.pm.outputs.manager == 'poetry'
uses: snok/install-poetry@76e04a911780d5b312d89783f7b1cd627778900a # v1.4.1
with:
version: ${{ inputs.poetry-version }}
virtualenvs-path: ~/.venv
- name: Load cached venv
id: venv
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: |
${{ inputs.working-directory }}/.venv
~/.venv
key: venv-${{ steps.pm.outputs.manager }}-${{ runner.os }}-${{ steps.setup.outputs.python-version }}-${{ inputs.working-directory }}-${{ hashFiles(format('{0}/uv.lock', inputs.working-directory), format('{0}/poetry.lock', inputs.working-directory)) }}
restore-keys: |
venv-${{ steps.pm.outputs.manager }}-${{ runner.os }}-${{ steps.setup.outputs.python-version }}-${{ inputs.working-directory }}-
- name: Sync dependencies (uv)
if: steps.pm.outputs.manager == 'uv' && steps.venv.outputs.cache-hit != 'true'
shell: bash
working-directory: ${{ inputs.working-directory }}
run: uv sync --frozen
- name: Sync dependencies (poetry)
if: steps.pm.outputs.manager == 'poetry' && steps.venv.outputs.cache-hit != 'true'
shell: bash
working-directory: ${{ inputs.working-directory }}
run: poetry sync --no-interaction --no-root
- name: Install project (poetry)
if: steps.pm.outputs.manager == 'poetry'
shell: bash
working-directory: ${{ inputs.working-directory }}
run: poetry install --no-interaction --only-root
# Note: no git-credential setup is needed. The Repair step pushes via the
# GitHub REST API rather than `git push`, because in this org's setup an
# App installation token authorized for Contents:Write at the API level
# is still rejected with 403 by git-receive-pack (verified by comparing
# PATCH /git/refs returning 422 vs git push returning 403 with the same
# token). The API path doesn't need git credentials at all.
- name: Run ruff format
shell: bash
working-directory: ${{ inputs.working-directory }}
run: ${{ steps.pm.outputs.run }} ruff format --exit-non-zero-on-format ${{ inputs.src-dirs }}
- name: Run ruff check
shell: bash
working-directory: ${{ inputs.working-directory }}
run: ${{ steps.pm.outputs.run }} ruff check --fix --exit-non-zero-on-fix ${{ inputs.src-dirs }}
- name: Repair
if: failure() && inputs.repair-token != ''
shell: bash
working-directory: ${{ inputs.working-directory }}
env:
REPAIR_TOKEN: ${{ inputs.repair-token }}
TARGET_BRANCH: ${{ github.head_ref || github.ref_name }}
run: |
if [ -z "$(git status --porcelain)" ]; then
exit 0
fi
python3 - <<'PYEOF'
import base64
import json
import os
import subprocess
import sys
import urllib.error
import urllib.request
token = os.environ["REPAIR_TOKEN"]
repo = os.environ["GITHUB_REPOSITORY"]
branch = os.environ["TARGET_BRANCH"]
def api(method, path, body=None):
url = f"https://api.github.com{path}"
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Authorization", f"token {token}")
req.add_header("Accept", "application/vnd.github+json")
if data is not None:
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req) as resp:
return json.loads(resp.read())
except urllib.error.HTTPError as e:
sys.stderr.write(f"{method} {path} -> {e.code}\n{e.read().decode()}\n")
raise
# Run from the repo root so paths from `git status` are repo-root-relative
# (which is what the GitHub trees API requires) and `open()` resolves
# correctly regardless of the action's working-directory input.
root = subprocess.check_output(
["git", "rev-parse", "--show-toplevel"]
).decode().strip()
os.chdir(root)
# Collect changes from the working tree (no local commit needed).
# `git status --porcelain -z` emits NUL-separated entries; for renames
# and copies the entry is `<new>\0<old>`, so we consume two tokens.
porcelain = subprocess.check_output(["git", "status", "--porcelain", "-z"]).decode()
changes = [] # list of ("write" | "delete", path)
entries = iter(porcelain.split("\0"))
for entry in entries:
if not entry:
continue
status, path = entry[:2], entry[3:]
if "R" in status or "C" in status:
new_path = path
old_path = next(entries, None)
if old_path is None:
break
if "R" in status:
changes.append(("delete", old_path))
changes.append(("write", new_path))
elif "D" in status:
changes.append(("delete", path))
elif "M" in status or "A" in status:
changes.append(("write", path))
# Untracked (??) and ignored (!!) are intentionally skipped.
if not changes:
print("No tracked changes to push.")
sys.exit(0)
print(f"Pushing {len(changes)} change(s) to {branch}: {changes}")
# Resolve the remote tip and its tree.
ref = api("GET", f"/repos/{repo}/git/refs/heads/{branch}")
parent_sha = ref["object"]["sha"]
parent_commit = api("GET", f"/repos/{repo}/git/commits/{parent_sha}")
parent_tree = parent_commit["tree"]["sha"]
# Upload each written file as a blob; emit `sha: null` to delete entries.
tree_entries = []
for action, path in changes:
if action == "delete":
tree_entries.append(
{"path": path, "mode": "100644", "type": "blob", "sha": None}
)
continue
with open(path, "rb") as f:
content = base64.b64encode(f.read()).decode()
blob = api(
"POST",
f"/repos/{repo}/git/blobs",
{"content": content, "encoding": "base64"},
)
mode = "100755" if os.access(path, os.X_OK) else "100644"
tree_entries.append(
{"path": path, "mode": mode, "type": "blob", "sha": blob["sha"]}
)
tree = api(
"POST",
f"/repos/{repo}/git/trees",
{"base_tree": parent_tree, "tree": tree_entries},
)
commit = api(
"POST",
f"/repos/{repo}/git/commits",
{
"message": "Fix lint and formatting issues",
"tree": tree["sha"],
"parents": [parent_sha],
},
)
api(
"PATCH",
f"/repos/{repo}/git/refs/heads/{branch}",
{"sha": commit["sha"]},
)
print(f"Pushed commit {commit['sha']} to refs/heads/{branch}")
PYEOF
- name: Run mypy
shell: bash
working-directory: ${{ inputs.working-directory }}
run: ${{ steps.pm.outputs.run }} mypy ${{ inputs.src-dirs }}
- name: Run pytest
if: inputs.run-pytest == 'true'
shell: bash
working-directory: ${{ inputs.working-directory }}
run: ${{ steps.pm.outputs.run }} pytest
branding:
icon: check-circle
color: orange