FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
thoth/.github/scripts/classify_ci_changes.py at master · thoth-pub/thoth · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
thoth-pub
/
thoth
Public
Notifications
You must be signed in to change notification settings
Fork
13
Star
53
Code
Issues
76
Pull requests
6
Discussions
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
thoth
/
.github
/
scripts
/
classify_ci_changes.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
420 lines (358 loc) · 13 KB
Breadcrumbs
thoth
/
.github
/
scripts
/
classify_ci_changes.py
Copy path
File metadata and controls
420 lines (358 loc) · 13 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
#!/usr/bin/env python3
"""Classify a complete Git change set for GitHub Actions CI gating."""
from
__future__
import
annotations
import
argparse
import
json
import
os
import
re
import
subprocess
import
sys
import
tempfile
from
dataclasses
import
asdict
,
dataclass
from
pathlib
import
Path
,
PurePosixPath
from
typing
import
Mapping
,
Sequence
SHA_PATTERN
=
re
.
compile
(
r"^[0-9a-fA-F]{40}$"
)
ALL_ZERO_SHA
=
"0"
*
40
BUILD_CONTROL_PATHS
=
{
".github/scripts/classify_ci_changes.py"
,
".github/workflows/build_test_and_check.yml"
,
".github/workflows/build_test_and_check_no_action.yml"
,
}
MIGRATION_CONTROL_PATHS
=
{
".github/scripts/classify_ci_changes.py"
,
".github/workflows/run_migrations.yml"
,
".github/workflows/run_migrations_no_action.yml"
,
}
class
ClassificationError
(
RuntimeError
):
"""Raised when a change set cannot be classified reliably."""
@
dataclass
(
frozen
=
True
)
class
Classification
:
docs_only
:
bool
run_build
:
bool
run_migrations
:
bool
run_docker
:
bool
@
classmethod
def
heavy
(
cls
)
->
"Classification"
:
return
cls
(
docs_only
=
False
,
run_build
=
True
,
run_migrations
=
True
,
run_docker
=
True
,
)
def
as_outputs
(
self
)
->
dict
[
str
,
str
]:
return
{
key
:
str
(
value
).
lower
()
for
key
,
value
in
asdict
(
self
).
items
()
}
def
normalize_path
(
raw_path
:
str
)
->
str
:
"""Validate and normalize a repository-relative Git path."""
if
not
raw_path
or
"
\x00
"
in
raw_path
or
"
\\
"
in
raw_path
:
raise
ClassificationError
(
f"invalid changed path:
{
raw_path
!r
}
"
)
path
=
PurePosixPath
(
raw_path
)
if
path
.
is_absolute
()
or
".."
in
path
.
parts
or
"."
in
path
.
parts
:
raise
ClassificationError
(
f"unsafe changed path:
{
raw_path
!r
}
"
)
normalized
=
path
.
as_posix
()
if
normalized
in
{
""
,
"."
}:
raise
ClassificationError
(
f"invalid changed path:
{
raw_path
!r
}
"
)
return
normalized
def
is_documentation_path
(
path
:
str
)
->
bool
:
return
path
==
"CHANGELOG.md"
or
path
.
startswith
(
"docs/"
)
def
is_build_path
(
path
:
str
)
->
bool
:
return
(
path
in
BUILD_CONTROL_PATHS
or
path
==
"Cargo.lock"
or
path
.
endswith
(
"Cargo.toml"
)
or
path
==
"diesel.toml"
or
path
.
endswith
((
".rs"
,
".js"
,
".json"
,
".html"
))
)
def
is_migration_path
(
path
:
str
)
->
bool
:
return
(
path
in
MIGRATION_CONTROL_PATHS
or
path
.
startswith
(
"src/bin/"
)
or
path
.
endswith
((
"up.sql"
,
"down.sql"
,
"db.rs"
))
)
def
classify_paths
(
raw_paths
:
Sequence
[
str
])
->
Classification
:
"""Classify a complete, non-empty changed-file set."""
if
not
raw_paths
:
raise
ClassificationError
(
"changed-file set is empty"
)
paths
=
tuple
(
normalize_path
(
path
)
for
path
in
raw_paths
)
docs_only
=
all
(
is_documentation_path
(
path
)
for
path
in
paths
)
if
docs_only
:
return
Classification
(
docs_only
=
True
,
run_build
=
False
,
run_migrations
=
False
,
run_docker
=
False
,
)
return
Classification
(
docs_only
=
False
,
run_build
=
any
(
is_build_path
(
path
)
for
path
in
paths
),
run_migrations
=
any
(
is_migration_path
(
path
)
for
path
in
paths
),
run_docker
=
True
,
)
def
validate_sha
(
value
:
object
,
label
:
str
)
->
str
:
if
not
isinstance
(
value
,
str
)
or
not
SHA_PATTERN
.
fullmatch
(
value
):
raise
ClassificationError
(
f"
{
label
}
is not a full Git SHA"
)
return
value
.
lower
()
def
changed_paths
(
base_sha
:
str
,
head_sha
:
str
,
cwd
:
Path
|
None
=
None
,
*
,
merge_base
:
bool
=
False
,
)
->
list
[
str
]:
"""Return all paths changed between two complete Git trees."""
base
=
validate_sha
(
base_sha
,
"base SHA"
)
head
=
validate_sha
(
head_sha
,
"head SHA"
)
if
base
==
ALL_ZERO_SHA
or
head
==
ALL_ZERO_SHA
:
raise
ClassificationError
(
"an all-zero Git SHA cannot define a change range"
)
comparison
=
f"
{
base
}
...
{
head
}
"
if
merge_base
else
f"
{
base
}
..
{
head
}
"
try
:
result
=
subprocess
.
run
(
[
"git"
,
"diff"
,
"--name-only"
,
"--no-renames"
,
"-z"
,
comparison
,
"--"
,
],
cwd
=
cwd
,
check
=
True
,
capture_output
=
True
,
)
except
(
OSError
,
subprocess
.
CalledProcessError
)
as
error
:
diagnostic
=
getattr
(
error
,
"stderr"
,
b""
)
detail
=
diagnostic
.
decode
(
"utf-8"
,
"replace"
).
strip
()
raise
ClassificationError
(
f"unable to calculate complete change range:
{
detail
or
error
}
"
)
from
error
paths
=
[
entry
.
decode
(
"utf-8"
,
"surrogateescape"
)
for
entry
in
result
.
stdout
.
split
(
b"
\x00
"
)
if
entry
]
if
not
paths
:
raise
ClassificationError
(
"Git change range produced an empty file set"
)
return
paths
def
load_event
(
path
:
str
)
->
Mapping
[
str
,
object
]:
if
not
path
:
raise
ClassificationError
(
"GITHUB_EVENT_PATH is not set"
)
try
:
with
Path
(
path
).
open
(
encoding
=
"utf-8"
)
as
event_file
:
event
=
json
.
load
(
event_file
)
except
(
OSError
,
json
.
JSONDecodeError
)
as
error
:
raise
ClassificationError
(
f"unable to read GitHub event:
{
error
}
"
)
from
error
if
not
isinstance
(
event
,
dict
):
raise
ClassificationError
(
"GitHub event payload is not an object"
)
return
event
def
classify_event
(
event_name
:
str
,
event
:
Mapping
[
str
,
object
],
github_sha
:
str
|
None
,
cwd
:
Path
|
None
=
None
,
)
->
Classification
:
"""Classify a supported GitHub Actions event."""
if
event_name
==
"workflow_dispatch"
:
return
Classification
.
heavy
()
if
event_name
==
"pull_request"
:
pull_request
=
event
.
get
(
"pull_request"
)
if
not
isinstance
(
pull_request
,
dict
):
raise
ClassificationError
(
"pull_request payload is missing"
)
base
=
pull_request
.
get
(
"base"
)
head
=
pull_request
.
get
(
"head"
)
if
not
isinstance
(
base
,
dict
)
or
not
isinstance
(
head
,
dict
):
raise
ClassificationError
(
"pull_request base or head is missing"
)
paths
=
changed_paths
(
validate_sha
(
base
.
get
(
"sha"
),
"pull-request base SHA"
),
validate_sha
(
head
.
get
(
"sha"
),
"pull-request head SHA"
),
cwd
=
cwd
,
merge_base
=
True
,
)
return
classify_paths
(
paths
)
if
event_name
==
"push"
:
before
=
validate_sha
(
event
.
get
(
"before"
),
"push before SHA"
)
head_value
=
github_sha
or
event
.
get
(
"after"
)
head
=
validate_sha
(
head_value
,
"push head SHA"
)
paths
=
changed_paths
(
before
,
head
,
cwd
=
cwd
)
return
classify_paths
(
paths
)
raise
ClassificationError
(
f"unsupported GitHub event:
{
event_name
or
'<empty>'
}
"
)
def
emit_outputs
(
classification
:
Classification
,
output_path
:
str
|
None
,
)
->
None
:
outputs
=
classification
.
as_outputs
()
if
output_path
:
with
Path
(
output_path
).
open
(
"a"
,
encoding
=
"utf-8"
)
as
output_file
:
for
key
,
value
in
outputs
.
items
():
output_file
.
write
(
f"
{
key
}
=
{
value
}
\n
"
)
print
(
json
.
dumps
(
outputs
,
sort_keys
=
True
))
def
git
(
repo
:
Path
,
*
args
:
str
)
->
str
:
result
=
subprocess
.
run
(
[
"git"
,
*
args
],
cwd
=
repo
,
check
=
True
,
capture_output
=
True
,
text
=
True
,
)
return
result
.
stdout
.
strip
()
def
run_self_tests
()
->
None
:
cases
=
[
(
"documentation_only"
,
[
"docs/engineering/example.md"
,
"docs/publisher-services/README.md"
],
Classification
(
True
,
False
,
False
,
False
),
),
(
"changelog_only"
,
[
"CHANGELOG.md"
],
Classification
(
True
,
False
,
False
,
False
),
),
(
"mixed_docs_and_rust"
,
[
"docs/example.md"
,
"thoth-api/src/lib.rs"
],
Classification
(
False
,
True
,
False
,
True
),
),
(
"migration_only"
,
[
"thoth-api/migrations/example/up.sql"
],
Classification
(
False
,
False
,
True
,
True
),
),
(
"dockerfile"
,
[
"Dockerfile"
],
Classification
(
False
,
False
,
False
,
True
),
),
(
"workflow_change"
,
[
".github/workflows/build_test_and_check.yml"
],
Classification
(
False
,
True
,
False
,
True
),
),
(
"classifier_change"
,
[
".github/scripts/classify_ci_changes.py"
],
Classification
(
False
,
True
,
True
,
True
),
),
(
"deleted_build_no_action_workflow"
,
[
".github/workflows/build_test_and_check_no_action.yml"
],
Classification
(
False
,
True
,
False
,
True
),
),
(
"deleted_migration_no_action_workflow"
,
[
".github/workflows/run_migrations_no_action.yml"
],
Classification
(
False
,
False
,
True
,
True
),
),
(
"root_readme"
,
[
"README.md"
],
Classification
(
False
,
False
,
False
,
True
),
),
]
for
name
,
paths
,
expected
in
cases
:
actual
=
classify_paths
(
paths
)
if
actual
!=
expected
:
raise
AssertionError
(
f"
{
name
}
: expected
{
expected
}
, got
{
actual
}
"
)
print
(
f"PASS
{
name
}
:
{
json
.
dumps
(
actual
.
as_outputs
(),
sort_keys
=
True
)
}
"
)
manual
=
classify_event
(
"workflow_dispatch"
, {},
None
)
if
manual
!=
Classification
.
heavy
():
raise
AssertionError
(
f"manual_dispatch: expected heavy, got
{
manual
}
"
)
print
(
"PASS manual_dispatch: "
f"
{
json
.
dumps
(
manual
.
as_outputs
(),
sort_keys
=
True
)
}
"
)
try
:
classify_paths
([])
except
ClassificationError
:
empty_result
=
Classification
.
heavy
()
else
:
raise
AssertionError
(
"empty_range: empty paths did not fail closed"
)
print
(
"PASS empty_range_fail_closed: "
f"
{
json
.
dumps
(
empty_result
.
as_outputs
(),
sort_keys
=
True
)
}
"
)
try
:
changed_paths
(
ALL_ZERO_SHA
,
ALL_ZERO_SHA
)
except
ClassificationError
:
invalid_range_result
=
Classification
.
heavy
()
else
:
raise
AssertionError
(
"invalid_range: all-zero range did not fail closed"
)
print
(
"PASS invalid_range_fail_closed: "
f"
{
json
.
dumps
(
invalid_range_result
.
as_outputs
(),
sort_keys
=
True
)
}
"
)
with
tempfile
.
TemporaryDirectory
(
prefix
=
"ci-docs-classifier-"
)
as
temp_dir
:
repo
=
Path
(
temp_dir
)
git
(
repo
,
"init"
,
"-q"
)
git
(
repo
,
"config"
,
"user.name"
,
"CI classifier self-test"
)
git
(
repo
,
"config"
,
"user.email"
,
"ci-classifier@example.invalid"
)
(
repo
/
"README.md"
).
write_text
(
"base
\n
"
,
encoding
=
"utf-8"
)
git
(
repo
,
"add"
,
"README.md"
)
git
(
repo
,
"commit"
,
"-qm"
,
"base"
)
base_sha
=
git
(
repo
,
"rev-parse"
,
"HEAD"
)
source
=
repo
/
"thoth-api"
/
"src"
source
.
mkdir
(
parents
=
True
)
(
source
/
"lib.rs"
).
write_text
(
"pub fn example() {}
\n
"
,
encoding
=
"utf-8"
)
git
(
repo
,
"add"
,
"thoth-api/src/lib.rs"
)
git
(
repo
,
"commit"
,
"-qm"
,
"source"
)
docs
=
repo
/
"docs"
docs
.
mkdir
()
(
docs
/
"example.md"
).
write_text
(
"# Example
\n
"
,
encoding
=
"utf-8"
)
git
(
repo
,
"add"
,
"docs/example.md"
)
git
(
repo
,
"commit"
,
"-qm"
,
"docs"
)
head_sha
=
git
(
repo
,
"rev-parse"
,
"HEAD"
)
paths
=
changed_paths
(
base_sha
,
head_sha
,
cwd
=
repo
,
merge_base
=
True
)
full_range
=
classify_paths
(
paths
)
expected
=
Classification
(
False
,
True
,
False
,
True
)
if
full_range
!=
expected
:
raise
AssertionError
(
f"full_pr_diff: expected
{
expected
}
, got
{
full_range
}
"
)
print
(
"PASS full_pr_diff: "
f"paths=
{
json
.
dumps
(
paths
)
}
"
f"outputs=
{
json
.
dumps
(
full_range
.
as_outputs
(),
sort_keys
=
True
)
}
"
)
print
(
f"PASS all_self_tests:
{
len
(
cases
)
+
4
}
cases"
)
def
parse_args
()
->
argparse
.
Namespace
:
parser
=
argparse
.
ArgumentParser
(
description
=
__doc__
)
mode
=
parser
.
add_mutually_exclusive_group
()
mode
.
add_argument
(
"--self-test"
,
action
=
"store_true"
,
help
=
"run deterministic classifier and full-range tests"
,
)
mode
.
add_argument
(
"--paths"
,
nargs
=
"+"
,
help
=
"classify an explicit complete changed-file set"
,
)
return
parser
.
parse_args
()
def
main
()
->
int
:
args
=
parse_args
()
if
args
.
self_test
:
run_self_tests
()
return
0
if
args
.
paths
is
not
None
:
try
:
classification
=
classify_paths
(
args
.
paths
)
except
ClassificationError
as
error
:
print
(
f"FAIL CLOSED:
{
error
}
"
,
file
=
sys
.
stderr
)
classification
=
Classification
.
heavy
()
emit_outputs
(
classification
,
None
)
return
0
try
:
event
=
load_event
(
os
.
environ
.
get
(
"GITHUB_EVENT_PATH"
,
""
))
classification
=
classify_event
(
os
.
environ
.
get
(
"GITHUB_EVENT_NAME"
,
""
),
event
,
os
.
environ
.
get
(
"GITHUB_SHA"
),
)
except
ClassificationError
as
error
:
print
(
f"FAIL CLOSED:
{
error
}
"
,
file
=
sys
.
stderr
)
classification
=
Classification
.
heavy
()
emit_outputs
(
classification
,
os
.
environ
.
get
(
"GITHUB_OUTPUT"
))
return
0
if
__name__
==
"__main__"
:
raise
SystemExit
(
main
())
Back
|
FazBrowse Home
|
New Git URL