-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrelease_notes.py
More file actions
2698 lines (2340 loc) · 105 KB
/
Copy pathrelease_notes.py
File metadata and controls
2698 lines (2340 loc) · 105 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
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Copyright (c) Contributors to the Open 3D Engine Project.
# For complete copyright and license terms please see the LICENSE at the root of this distribution.
#
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
import argparse
import contextlib
import json
import logging
import os
import pathlib
import re
import shlex
import shutil
import stat
import subprocess
import sys
import tempfile
import time
from datetime import datetime, timezone
from typing import Any, cast
LOG_FORMAT = '[%(levelname)s] %(name)s: %(message)s'
logger = logging.getLogger('o3de.release_notes')
__version__ = '0.8.1-beta'
# 6: adds metadata.reused_from_cache, recording how many PRs were served from
# the previous report instead of re-fetched.
# 5: adds per-PR `files_truncated` and metadata.file_list_truncated, so a
# curator can see which entries were categorised from a partial file list.
# 4: adds metadata.tool_version; `flags` no longer carries `stabilization-sync`
# and descriptions are no longer truncated mid-sentence, so data written by
# <=0.5.0-beta is structurally readable but semantically stale. Version 3
# files still load (renderer ignores the legacy flag); re-fetch for accuracy.
SCHEMA_VERSION = 6
GIT_REF_PATTERN = re.compile(r'^[a-zA-Z0-9._/\-]+$')
REPO_SLUG_PATTERN = re.compile(r'^[a-zA-Z0-9_.\-]+/[a-zA-Z0-9_.\-]+$')
REPO_PATH_MAPPING_PATTERN = re.compile(r'^([a-zA-Z0-9_.\-]+/[a-zA-Z0-9_.\-]+)=(.+)$')
PR_NUMBER_PATTERN = re.compile(r'\(#(\d+)\)')
# O3DE uses two merge strategies on `development`. Squash-merges put the PR
# number in the subject as `(#NNNN)`; merge-commit PRs produce
# `Merge pull request #NNNN from owner/branch` with no parentheses, and their
# constituent commits carry no PR reference at all. Matching only the squash
# form (and passing --no-merges to git log) silently loses every merge-commit
# PR: 19 of them in the 2605.0..development window alone.
MERGE_COMMIT_PR_PATTERN = re.compile(r'^Merge pull request #(\d+)\b')
DEFAULT_REPOS = ['o3de/o3de']
SIG_CANONICAL_ORDER = [
'sig/build',
'sig/content',
'sig/core',
'sig/docs-community',
'sig/graphics-audio',
'sig/network',
'sig/platform',
'sig/release',
'sig/security',
'sig/simulation',
'sig/testing',
'sig/ui-ux',
]
SIG_DISPLAY_NAMES = {
'sig/build': 'SIG-Build',
'sig/content': 'SIG-Content',
'sig/core': 'SIG-Core',
'sig/docs-community': 'SIG-Docs-Community',
'sig/graphics-audio': 'SIG-Graphics-Audio',
'sig/network': 'SIG-Network',
'sig/platform': 'SIG-Platform',
'sig/release': 'SIG-Release',
'sig/security': 'SIG-Security',
'sig/simulation': 'SIG-Simulation',
'sig/testing': 'SIG-Testing',
'sig/ui-ux': 'SIG-UI-UX',
}
SIG_TITLE_KEYWORDS = {
'sig/build': [
'cmake', 'compiler', ' ci ', ' ci/', 'ci:', 'automated review', ' ar ',
'workflow', 'installer', 'ninja', 'build error', 'build fix', 'compile',
'linker', 'linking', 'monolithic', 'ccache', 'sccache', 'gradle',
'clang', 'msvc', 'gcc', 'xcode', 'msbuild', 'vcpkg', 'conan',
'github actions', 'gha ', 'pipeline', '3p ', 'third-party',
'third party', '3rdparty', 'fetchpackage', 'fetchcontent',
],
'sig/content': [
'editor', 'asset processor', 'asset browser', 'assetprocessor',
'prefab', 'scriptcanvas', 'script canvas', 'lua editor', 'lua script',
'outliner', 'inspector', 'lyshine', 'ui canvas', 'viewport',
'entity inspector', 'component inspector', 'project manager',
'material editor', 'scene settings', 'fbx', 'gltf', 'glb',
'asset bundl', 'asset editor', 'asset import',
'emotionx', 'emotionfx', 'emfx', 'motion', 'animation graph',
],
'sig/core': [
'azcore', 'azframework', 'aztoolsframework', 'azstd', 'az::',
'settings registry', 'settingsregistry', 'allocator', 'rtti',
'behaviorcontext', 'behavior context', 'serializ', 'reflect',
'component descriptor', 'az_component', 'az_class', 'az_type',
'json', 'xml', 'streamer', 'io scheduler', 'module',
'gem.json', 'engine.json', 'o3de cli', 'register',
'std::move', 'std::array', 'std::span',
],
'sig/graphics-audio': [
'atom', ' rhi', 'vulkan', 'dx12', 'directx', 'metal',
'shader', 'material', 'render', 'pass ', 'pass:', 'passes',
'light', 'lighting', 'shadow', 'texture', 'mesh',
'ray trac', 'raytrac', 'tlas', 'blas', 'acceleration structure',
'bloom', 'ssao', 'ssr', 'hdr', 'tonemapp', 'exposure',
'srg', 'drawsrg', 'materialsrg', 'azsl',
'diffuse probe', 'global illumination', 'skybox', 'sky atmosphere',
'skyatmosphere', 'fog', 'particle', 'openparticle',
'terrain', 'stars', 'miniaudio', 'audio',
'imgui', 'meshlet', 'lod', 'occlusion', 'culling',
'unlit', 'emissive', 'irradiance', 'parallax',
],
'sig/network': [
'network', 'multiplayer', 'netbind', 'replica', 'replication',
],
'sig/platform': [
'android', ' ios', 'macos', 'mac ', 'linux', 'wayland', 'xcb',
'emscripten', 'wasm', 'webassembly', 'windows platform',
'platform tab', 'arm64', 'aarch64', 'x86_64',
'objective-c', 'apple',
],
'sig/simulation': [
'physx', 'physics', 'rigid body', 'collider', 'articulation',
'recast', 'navigation', 'navmesh', 'detour',
'hinge', 'joint', 'ragdoll', 'character controller',
'ros2', 'ros 2', 'robot', 'gripper', 'simulation interface',
],
'sig/security': [
'security', 'bounds check', 'cve', 'owasp', 'vulnerability',
'buffer overflow', 'out of bounds', 'oom dos', 'sanitiz',
],
'sig/testing': [
'googletest', 'gtest', 'gmock', 'benchmark', 'unit test',
'test fix', 'test compilation', 'ctest', 'asan', 'tsan',
],
}
SIG_FILE_PATH_PATTERNS = {
'sig/testing': [
'cmake/LYTestWrappers.cmake',
'Code/Framework/AzTest',
'Code/Tools/AzTestRunner/',
'Tools/LyTestTools/',
'Tools/RemoteConsole/',
'scripts/ctest/',
],
'sig/core': [
'Code/CrashHandler/',
'Code/Framework/AzCore/',
'Code/Framework/AzFramework/',
'Code/Framework/AzGameFramework/',
'Code/LauncherUnified/',
'engine.json',
'Gems/Archive/',
'Gems/Compression/',
'Gems/CrashReporting/',
'Gems/ImGui/',
'Gems/LmbrCentral/',
'Gems/Profiler/',
'Registry/',
'scripts/lldb/',
'scripts/o3de/',
'Code/Legacy/',
'Code/Tools/SerializeContextTools/',
'Templates/',
'Tools/EventLogTool/',
],
'sig/content': [
'Code/Framework/AzToolsFramework/',
'Code/Tools/',
'Code/Framework/AzQtComponents/',
'Code/Editor/',
'Gems/EditorPythonBindings/',
'Gems/GraphCanvas/',
'Gems/GraphModel/',
'Gems/LandscapeCanvas/',
'Gems/QtForPython/',
'Gems/LyShine/',
'Gems/ScriptCanvas/',
'Gems/ScriptEvents/',
'Gems/SceneProcessing/',
'Gems/WhiteBox/',
'Gems/Prefab/',
'Code/Framework/AzManipulatorTestFramework/',
'Tools/',
],
'sig/simulation': [
'Code/Framework/AzCore/AzCore/Math/',
'Code/Framework/AzFramework/AzFramework/Physics/',
'Gems/MotionMatching/',
'Gems/NvCloth/',
'Gems/PhysX/',
'Gems/PhysXDebug/',
'Gems/EMotionFX/',
'Gems/RecastNavigation/',
'Gems/ROS2/',
'Gems/ROS2Sensors/',
'Gems/ROS2Controllers/',
'Gems/SimulationInterfaces/',
],
'sig/build': [
'cmake/Platform/',
'cmake/Packaging/',
'scripts/build/',
'scripts/commit_validation/',
'scripts/license_scanner/',
'scripts/signer/',
'.github/workflows/',
'python/',
# Catch-alls for the two build-owned trees. Safe because matching is
# longest-wins: 'cmake/LYTestWrappers.cmake' and 'scripts/ctest/' still
# resolve to sig/testing, and 'scripts/o3de/' still resolves to
# sig/core. Without these, files sitting directly in cmake/ or scripts/
# (o3deConfigVersion.cmake, LYPython.cmake, 3rdPartyPackages.cmake,
# o3de.sh) matched nothing and fell through to uncategorized.
'cmake/',
'scripts/',
],
'sig/network': [
'Code/Framework/AzFramework/AzFramework/Network/',
'Code/Framework/AzNetworking/',
'Code/Tools/AWSNativeSDKInit/',
'Gems/AWSClientAuth/',
'Gems/AWSCore/',
'Gems/AWSGameLift/',
'Gems/AWSMetrics/',
'Gems/HttpRequestor/',
'Gems/Metastream/',
'Gems/Multiplayer/',
'Gems/MultiplayerCompression/',
'Gems/Twitch/',
],
'sig/graphics-audio': [
'Gems/Atom/',
'Gems/AtomLyIntegration/',
'Gems/AtomTressFX/',
'Gems/Terrain/',
'Gems/Audio/',
'Gems/Microphone/',
'Gems/DiffuseProbeGrid/',
'Gems/Stars/',
'Gems/SkyAtmosphere/',
'Gems/OpenParticleSystem/',
'Gems/MiniAudio/',
],
'sig/platform': [
'restricted/',
],
}
CHERRY_PICK_PATTERNS = [
re.compile(r'cherry[\s-]*pick', re.IGNORECASE),
re.compile(r'merge\s+stabilization', re.IGNORECASE),
re.compile(r'merge\s+from\s+stabilization', re.IGNORECASE),
re.compile(r'merge\s+changes\s+from\s+stabilization', re.IGNORECASE),
re.compile(r'\[stabilization\]', re.IGNORECASE),
re.compile(r'sync.*to.*development', re.IGNORECASE),
]
# Containers are commit/PR titles that bundle multiple cherry-picks from another
# branch, distinct from plain "cherry-pick" because we expect their bodies to
# enumerate the bundled PR numbers via the `(#NNNN)` convention.
POINTRELEASE_CONTAINER_PATTERNS = [
re.compile(r'cherry[\s-]*pick.+(?:from|point[\s-]*release|dev|development)', re.IGNORECASE),
re.compile(r'merg(?:e|ing).*point[\s-]*release', re.IGNORECASE),
re.compile(r'merg(?:e|ing).*upstream.*point[\s-]*release', re.IGNORECASE),
]
# Matches X.Y.Z-style point-release tags (e.g., 2510.2, 2605.1). Only used to
# detect when --from-ref points at a point release so we can scan its
# predecessors for cherry-pick containers. Year + month encoded in X, patch in Z.
POINT_RELEASE_TAG_PATTERN = re.compile(r'^(\d{2,4})\.(\d+)$')
# Release-engineering PRs that aren't product changes (version bumps, point-
# release branch admin, GPG key rotations, SBOM/dependency-only auto-updates).
# Matched against the PR title. We require AT LEAST ONE of these patterns AND
# typically a small/narrow file set; see is_release_machinery for the conjunction.
RELEASE_MACHINERY_TITLE_PATTERNS = [
re.compile(r'^update\s+(?:version|copyright)', re.IGNORECASE),
re.compile(r'^update\s+(?:linux\s+)?gpg\s+key', re.IGNORECASE),
re.compile(r'^update\s+sbom\b', re.IGNORECASE),
re.compile(r'^point[\s-]*release\b', re.IGNORECASE),
re.compile(r'\bmerge\b.*\bpoint[\s-]*release\b', re.IGNORECASE),
re.compile(r'\bmerging[_\s]*point[\s-]*release\b', re.IGNORECASE),
re.compile(r'\bcherry[\s-]*pick.*\bpoint[\s-]*release\b', re.IGNORECASE),
re.compile(r'\bmerging[_\s]+pointrelease', re.IGNORECASE),
re.compile(r'\bcherrypick\d*\s+from\s+dev\s+to\s+pointrelease', re.IGNORECASE),
re.compile(r'\badd\s+point[\s-]*release\s+branch\s+to\s+ar\b', re.IGNORECASE),
]
# Files whose presence-only (i.e. when ALL changed files match one of these
# patterns) indicates a non-product PR. Deliberately narrow: only files whose
# diff is unambiguous machinery (version bumps, SBOMs). We do NOT include
# `.github/workflows/` here. Workflow-only PRs are often substantive CI
# improvements (e.g. "Add check for adequate free space in linux AR workspace")
# that curators want to keep, and we'd rather under-flag than incorrectly
# exclude real content. Title patterns above carry the bulk of the load.
RELEASE_MACHINERY_FILE_PATTERNS = [
re.compile(r'(^|/)engine\.json$'),
re.compile(r'^sbom\.cdx\.json$'),
re.compile(r'/version\.txt$'),
# Repository governance, owned by the TSC rather than by any SIG. The
# release notes are organised entirely by SIG, so there is no correct
# heading for this: filing it under sig/release or sig/docs-community would
# credit a SIG with work it did not do. It is not an engine change, so it
# does not belong in the notes at all.
#
# Classified here rather than left uncategorized so the exclusion is a
# decision instead of a failure. "Uncategorized" is a triage signal, and a
# PR that recurs there every cycle with the same answer trains curators to
# skim the one list they most need to read.
#
# Deliberately the exact file, not `.github/`: workflows and issue
# templates under that directory are real work by real SIGs.
re.compile(r'^\.github/FUNDING\.yml$'),
]
def validate_git_ref(ref: str) -> str:
if not ref or len(ref) > 256:
raise ValueError(f'Invalid git reference: length must be 1-256, got {len(ref) if ref else 0}')
if not GIT_REF_PATTERN.match(ref):
raise ValueError(f'Invalid git reference: {ref!r} contains disallowed characters')
if ref.startswith('-'):
raise ValueError(f'Invalid git reference: {ref!r} must not start with a hyphen')
return ref
def validate_repo_slug(slug: str) -> str:
if not slug or len(slug) > 128:
raise ValueError(f'Invalid repo slug: length must be 1-128, got {len(slug) if slug else 0}')
if not REPO_SLUG_PATTERN.match(slug):
raise ValueError(f'Invalid repo slug: {slug!r} must be in owner/repo format')
return slug
def validate_output_path(path: pathlib.Path, base_dir: pathlib.Path | None = None) -> pathlib.Path:
resolved = path.resolve()
if base_dir is not None:
base_resolved = base_dir.resolve()
if not resolved.is_relative_to(base_resolved):
raise ValueError(f'Path traversal detected: {resolved} is outside {base_resolved}')
if not resolved.parent.exists():
raise ValueError(f'Parent directory does not exist: {resolved.parent}')
return resolved
def parse_repo_path_mappings(
repo_paths: list[str] | None,
default_path: str,
repos: list[str],
) -> dict[str, pathlib.Path]:
default = pathlib.Path(default_path).resolve()
mappings: dict[str, pathlib.Path] = {}
if repo_paths:
for entry in repo_paths:
match = REPO_PATH_MAPPING_PATTERN.match(entry)
if match:
slug, path_str = match.group(1), match.group(2)
validate_repo_slug(slug)
mappings[slug] = pathlib.Path(path_str).resolve()
else:
raise ValueError(
f'Invalid --repo-path mapping: {entry!r}. '
f'Use owner/repo=/path/to/clone format.'
)
for repo in repos:
if repo not in mappings:
mappings[repo] = default
return mappings
def parse_repo_ref_mappings(
entries: list[str] | None,
default_ref: str,
repos: list[str],
flag_name: str,
) -> dict[str, str]:
"""Resolve per-repo git refs, falling back to the global ref.
Release lines do not tag every repo. `o3de/o3de` carries `2605.0` but
`o3de/o3de-extras` does not, so a single global --from-ref aborts the whole
multi-repo run on the repo that lacks the tag.
"""
mappings: dict[str, str] = {}
for entry in entries or []:
match = REPO_PATH_MAPPING_PATTERN.match(entry)
if not match:
raise ValueError(
f'Invalid {flag_name} mapping: {entry!r}. Use owner/repo=REF format.'
)
slug, ref = match.group(1), match.group(2)
validate_repo_slug(slug)
mappings[slug] = validate_git_ref(ref)
for repo in repos:
if repo not in mappings:
mappings[repo] = validate_git_ref(default_ref)
return mappings
def ref_exists(repo_path: pathlib.Path, ref: str) -> bool:
ref = validate_git_ref(ref)
try:
result = subprocess.run(
['git', 'rev-parse', '--verify', '--quiet', f'{ref}^{{commit}}'],
cwd=str(repo_path.resolve()),
capture_output=True,
text=True,
encoding='utf-8',
errors='replace',
timeout=15,
)
except (subprocess.SubprocessError, OSError) as e:
logger.warning('git rev-parse failed for %s in %s: %s', ref, repo_path, e)
return False
return result.returncode == 0
def verify_refs_exist(
repo_path_map: dict[str, pathlib.Path],
from_ref_map: dict[str, str],
to_ref_map: dict[str, str],
repos: list[str],
) -> list[str]:
"""Preflight every (repo, ref) pair and return human-readable problems.
Catching this upfront turns a mid-run `git log` abort, after minutes of
GitHub API calls, into an actionable error before any work starts.
"""
problems: list[str] = []
for repo_slug in repos:
repo_path = repo_path_map.get(repo_slug)
if repo_path is None:
continue
for label, ref in (('--from-ref', from_ref_map.get(repo_slug, '')),
('--to-ref', to_ref_map.get(repo_slug, ''))):
if not ref:
continue
if not ref_exists(repo_path, ref):
problems.append(
f'{repo_slug}: {label} {ref!r} does not resolve in {repo_path}. '
f'Fetch tags (`git -C {repo_path} fetch --tags`) or override with '
f'--repo-from-ref/--repo-to-ref {repo_slug}=<ref>.'
)
return problems
MAX_STDERR_LOG_LEN = 200
# Defense-in-depth: scrub GitHub token shapes from stderr before logging.
# gh CLI is unlikely to print tokens, but if it ever does, we don't want them
# in CI logs.
# Classic tokens (ghp_/gho_/ghu_/ghs_/ghr_) and fine-grained PATs, which use a
# github_pat_ prefix and may contain underscores in the body.
GH_TOKEN_PATTERN = re.compile(
r'\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b'
)
def _safe_stderr(text: str) -> str:
redacted = GH_TOKEN_PATTERN.sub('<redacted-token>', text)
return redacted.strip()[:MAX_STDERR_LOG_LEN]
def parse_point_release_tag(ref: str) -> tuple[int, int] | None:
"""Return (major_token, patch) if ref looks like a point-release tag, else None.
The major_token is the integer before the dot (e.g. 2510 in '2510.2'); the
O3DE convention encodes year and month there, but for our purposes it's an
opaque key used to group sibling tags.
"""
if not ref:
return None
m = POINT_RELEASE_TAG_PATTERN.match(ref.strip())
if not m:
return None
return int(m.group(1)), int(m.group(2))
def find_sibling_point_release_tags(repo_path: pathlib.Path, ref: str) -> list[str]:
"""Given a point-release tag, return all sibling tags sharing the same major
token (e.g. given '2510.2' returns ['2510.0', '2510.1', '2510.2'])."""
parsed = parse_point_release_tag(ref)
if parsed is None:
return []
major_token = parsed[0]
try:
result = subprocess.run(
['git', 'tag', '-l', f'{major_token}.*'],
cwd=str(repo_path.resolve()),
capture_output=True,
text=True,
encoding='utf-8',
errors='replace',
timeout=15,
)
except (subprocess.SubprocessError, OSError) as e:
logger.warning('git tag failed for %s: %s', repo_path, e)
return []
if result.returncode != 0:
return []
tags = []
for line in result.stdout.splitlines():
candidate = line.strip()
if parse_point_release_tag(candidate) is not None:
tags.append(candidate)
tags.sort(key=lambda t: parse_point_release_tag(t) or (0, 0))
return tags
def extract_merge_base(
repo_path: pathlib.Path,
from_ref: str,
to_ref: str,
) -> tuple[str, str] | None:
"""Return (sha, committer_date_iso) of the merge-base, or None on failure.
Used to anchor the "effective window" of the diff in release_data.json
metadata. Silently degrades to None if git fails; callers should treat
this metadata as best-effort.
"""
from_ref = validate_git_ref(from_ref)
to_ref = validate_git_ref(to_ref)
try:
mb = subprocess.run(
['git', 'merge-base', from_ref, to_ref],
cwd=str(repo_path.resolve()),
capture_output=True,
text=True,
encoding='utf-8',
errors='replace',
timeout=30,
)
except (subprocess.SubprocessError, OSError) as e:
logger.warning('git merge-base failed for %s: %s', repo_path, e)
return None
if mb.returncode != 0:
logger.warning('git merge-base %s..%s failed in %s: %s',
from_ref, to_ref, repo_path, _safe_stderr(mb.stderr))
return None
sha = mb.stdout.strip()
if not sha:
return None
try:
show = subprocess.run(
['git', 'show', '-s', '--format=%cI', sha],
cwd=str(repo_path.resolve()),
capture_output=True,
text=True,
encoding='utf-8',
errors='replace',
timeout=15,
)
except (subprocess.SubprocessError, OSError):
return (sha, '')
date = show.stdout.strip() if show.returncode == 0 else ''
return (sha, date)
# Maximum bytes we'll read from a single commit body when scanning for bundled
# PR references in a cherry-pick container. Bounds memory if a malformed commit
# has an enormous body.
MAX_CONTAINER_BODY_BYTES = 32768
def extract_pointrelease_containers(
repo_path: pathlib.Path,
predecessor_tag: str,
from_ref: str,
) -> list[dict[str, Any]]:
"""Walk commits between predecessor_tag and from_ref looking for cherry-pick
containers (PRs whose title matches POINTRELEASE_CONTAINER_PATTERNS) and
extract the bundled PR numbers from each commit's body.
Returns a list of {container_pr, title, bundled_prs: [int, ...]} dicts.
"""
predecessor_tag = validate_git_ref(predecessor_tag)
from_ref = validate_git_ref(from_ref)
sep = '@@CONTAINER_BOUNDARY@@'
try:
result = subprocess.run(
['git', 'log', f'--format=%H%n%s%n%b%n{sep}',
f'{predecessor_tag}..{from_ref}'],
cwd=str(repo_path.resolve()),
capture_output=True,
text=True,
encoding='utf-8',
errors='replace',
timeout=60,
)
except (subprocess.SubprocessError, OSError) as e:
logger.warning('git log failed when scanning containers in %s: %s', repo_path, e)
return []
if result.returncode != 0:
logger.warning(
'Container scan: git log %s..%s in %s returned %d',
predecessor_tag, from_ref, repo_path, result.returncode,
)
return []
containers: list[dict[str, Any]] = []
chunks = result.stdout.split(sep + '\n')
for chunk in chunks:
chunk = chunk.strip()
if not chunk:
continue
lines = chunk.split('\n', 2)
if len(lines) < 2:
continue
sha = lines[0].strip()
title = lines[1].strip()
body = lines[2] if len(lines) > 2 else ''
if len(body) > MAX_CONTAINER_BODY_BYTES:
body = body[:MAX_CONTAINER_BODY_BYTES]
if not any(p.search(title) for p in POINTRELEASE_CONTAINER_PATTERNS):
continue
# PR number in the title itself is the container PR (e.g. "(#19506)").
# Bundled PRs come from the body.
title_match = PR_NUMBER_PATTERN.search(title)
container_pr = int(title_match.group(1)) if title_match else None
bundled = set()
for m in PR_NUMBER_PATTERN.finditer(body):
n = int(m.group(1))
if n != container_pr:
bundled.add(n)
containers.append({
'container_pr': container_pr,
'container_sha': sha,
'title': title,
'bundled_prs': sorted(bundled),
})
return containers
def write_pointrelease_audit(
audit_data: dict[str, Any],
output_path: pathlib.Path,
) -> None:
"""Write a human-readable audit sidecar listing each container and showing
whether its bundled PRs are accounted for in the rendered report set.
audit_data must contain:
- from_ref, to_ref, predecessor_tag
- per_repo: {repo_slug: {containers: [...], present_pr_numbers: set[int]}}
"""
lines: list[str] = []
lines.append(f"# Point-release audit for {audit_data.get('to_ref', '')}\n")
lines.append(
f"Predecessor major tag: `{audit_data.get('predecessor_tag', '')}` \n"
f"From-ref (point release): `{audit_data.get('from_ref', '')}` \n"
f"To-ref (next major): `{audit_data.get('to_ref', '')}`\n"
)
lines.append(
"Each entry below is a cherry-pick container PR found on the previous\n"
"stabilization branch between the predecessor major tag and the from-ref.\n"
"The bundled PRs are extracted from the container's commit body, then\n"
"checked against what the report actually renders:\n"
"\n"
"- ✓ present in the rendered report, via its development-side merge\n"
"- ⚠ collected but filtered OUT of the report (reason shown). These are\n"
" the dangerous ones: the fix shipped in the point release, so a reader\n"
" expects it here. Confirm the filter is right before publishing.\n"
"- ✗ not found at all. Investigate.\n"
"\n"
"The ⚠ state exists because comparing against the collected JSON rather\n"
"than the rendered output reports a green tick for a fix the reader will\n"
"never see.\n"
)
grand_total_containers = 0
grand_total_bundled = 0
grand_total_present = 0
grand_total_filtered = 0
grand_total_missing = 0
for repo_slug, repo_audit in audit_data.get('per_repo', {}).items():
containers = repo_audit.get('containers', [])
present = repo_audit.get('present_pr_numbers', set())
filtered = repo_audit.get('filtered_pr_numbers', {})
lines.append(f"\n## {repo_slug}\n")
if not containers:
lines.append("_No cherry-pick containers found in this repo._\n")
continue
for entry in containers:
cpr = entry.get('container_pr')
cpr_label = f"#{cpr}" if cpr else f"sha:{entry.get('container_sha','')[:8]}"
bundled = entry.get('bundled_prs', [])
grand_total_containers += 1
grand_total_bundled += len(bundled)
lines.append(f"- **{cpr_label}**: {entry.get('title', '')}")
if not bundled:
lines.append(" - _(no bundled PRs parsed from body)_")
continue
for b in bundled:
if b in present:
grand_total_present += 1
lines.append(f" - ✓ #{b}: present in report via dev-side merge")
elif b in filtered:
grand_total_filtered += 1
lines.append(
f" - ⚠ #{b}: collected but FILTERED OUT of the report "
f"({filtered[b]}); shipped in the point release, so verify"
)
else:
grand_total_missing += 1
lines.append(f" - ✗ #{b}: NOT found at all (investigate)")
lines.append('')
verdict = (
"All bundled fixes are present in the rendered report."
if not grand_total_filtered and not grand_total_missing
else "**Action required before publishing.**"
)
lines.append(
f"---\n\n"
f"**Summary:** {grand_total_containers} container(s) checked, "
f"{grand_total_bundled} bundled PR reference(s) parsed: "
f"{grand_total_present} rendered, "
f"{grand_total_filtered} filtered out, "
f"{grand_total_missing} not found. {verdict}\n"
)
content = '\n'.join(lines)
write_markdown_atomic(content, output_path)
def is_release_machinery(pr_data: dict[str, Any]) -> bool:
"""Heuristically detect release-engineering PRs that aren't product changes.
True when EITHER:
- the title matches one of RELEASE_MACHINERY_TITLE_PATTERNS, OR
- every changed file matches one of RELEASE_MACHINERY_FILE_PATTERNS
(and there is at least one file).
The file-only path catches version-bump / SBOM / workflow-only PRs whose
titles don't fit a fixed pattern.
"""
title = pr_data.get('title', '') or ''
if any(p.search(title) for p in RELEASE_MACHINERY_TITLE_PATTERNS):
return True
files = pr_data.get('files', []) or []
if not files:
return False
return all(
any(p.search(fpath) for p in RELEASE_MACHINERY_FILE_PATTERNS)
for fpath in files
)
def extract_pr_numbers_from_git_log(
repo_path: pathlib.Path,
from_ref: str,
to_ref: str,
) -> list[int]:
from_ref = validate_git_ref(from_ref)
to_ref = validate_git_ref(to_ref)
# Merge commits are deliberately included: they are the only place a
# merge-commit PR's number appears. Duplicates across the two patterns are
# collapsed by the set.
try:
result = subprocess.run(
['git', 'log', '--format=%s', f'{from_ref}..{to_ref}'],
cwd=str(repo_path.resolve()),
capture_output=True,
text=True,
encoding='utf-8',
errors='replace',
timeout=60,
)
except (subprocess.SubprocessError, OSError) as e:
raise RuntimeError(f'git log {from_ref}..{to_ref} failed in {repo_path}: {e}') from e
if result.returncode != 0:
logger.error('git log failed: %s', _safe_stderr(result.stderr))
raise RuntimeError(f'git log failed with exit code {result.returncode}')
pr_numbers = set()
merge_commit_prs = 0
for line in result.stdout.splitlines():
for match in PR_NUMBER_PATTERN.finditer(line):
pr_numbers.add(int(match.group(1)))
merge_match = MERGE_COMMIT_PR_PATTERN.match(line)
if merge_match:
number = int(merge_match.group(1))
if number not in pr_numbers:
merge_commit_prs += 1
pr_numbers.add(number)
if merge_commit_prs:
logger.info(
'%d PR(s) found via merge commits (`Merge pull request #N`) in %s',
merge_commit_prs, repo_path,
)
return sorted(pr_numbers)
# GraphQL page sizes. The truncation check below reads these, so changing a
# page size cannot leave the check testing the old bound.
FILES_PAGE_SIZE = 100
LABELS_PAGE_SIZE = 20
def _build_graphql_query(pr_numbers: list[int]) -> str:
# Owner/name are GraphQL variables ($owner, $name); never interpolated as
# strings. PR numbers are integer-validated before they reach this function
# and become GraphQL aliases (pr_<n>), which require literal numbers.
fragments = []
for num in pr_numbers:
fragments.append(
f' pr_{num}: pullRequest(number: {int(num)}) {{\n'
f' number\n'
f' title\n'
f' body\n'
f' mergedAt\n'
f' url\n'
f' author {{ login }}\n'
f' labels(first: {LABELS_PAGE_SIZE}) {{ nodes {{ name }} }}\n'
f' files(first: {FILES_PAGE_SIZE}) {{ nodes {{ path }} }}\n'
f' }}'
)
return (
'query($owner: String!, $name: String!) {\n'
' repository(owner: $owner, name: $name) {\n'
+ '\n'.join(fragments) +
'\n }\n'
'}'
)
class GhCommandError(RuntimeError):
"""A `gh` invocation failed. Carries the scrubbed stderr for classification."""
def __init__(self, message: str, stderr: str = '') -> None:
super().__init__(message)
self.stderr = stderr
# A PR number that GitHub cannot resolve is permanent: retrying cannot help.
# It usually means the number came from an issue reference in a commit subject,
# e.g. "Fix prefab path expansion (#18886) (#19254)" where only the second is
# the PR. Parse the offending numbers out so the batch can drop them and retry,
# instead of degrading to one request per PR.
UNRESOLVABLE_PR_PATTERN = re.compile(
r'Could not resolve to a PullRequest with the number of (\d+)', re.IGNORECASE,
)
# Failures worth retrying. Anything else is treated as permanent.
TRANSIENT_ERROR_MARKERS = (
'rate limit', 'secondary rate', 'abuse detection',
'timed out', 'timeout', 'connection reset', 'connection refused',
'temporary failure', 'bad gateway', 'service unavailable',
'502', '503', '504',
)
MAX_BATCH_ATTEMPTS = 3
BACKOFF_BASE_SECONDS = 2.0
MAX_BACKOFF_SECONDS = 30.0
def _unresolvable_pr_numbers(stderr: str) -> set[int]:
return {int(m.group(1)) for m in UNRESOLVABLE_PR_PATTERN.finditer(stderr or '')}
def _is_transient_error(stderr: str) -> bool:
lowered = (stderr or '').lower()
return any(marker in lowered for marker in TRANSIENT_ERROR_MARKERS)
def _backoff_seconds(attempt: int) -> float:
"""Exponential, capped. attempt is 0-based."""
return float(min(BACKOFF_BASE_SECONDS * (2 ** attempt), MAX_BACKOFF_SECONDS))
def _run_gh_command(args: list[str], timeout: int = 30) -> dict[str, Any]:
# A timeout or a missing binary must surface as RuntimeError like any other
# gh failure. Letting TimeoutExpired escape aborted the whole run with a
# traceback and discarded every batch already fetched.
try:
result = subprocess.run(
args,
capture_output=True,
text=True,
encoding='utf-8',
errors='replace',
timeout=timeout,
)
except subprocess.TimeoutExpired as e:
raise GhCommandError(f'gh command timed out after {timeout}s', 'timed out') from e
except (subprocess.SubprocessError, OSError) as e:
raise GhCommandError(f'gh command failed to run: {e}', str(e)) from e
if result.returncode != 0:
stderr = _safe_stderr(result.stderr)
if 'rate limit' in stderr.lower() or '403' in stderr:
logger.error('GitHub API rate limit exceeded. Backing off.')
else:
logger.error('gh command failed: %s', stderr)
raise GhCommandError(f'gh command failed with exit code {result.returncode}', stderr)
try:
return cast(dict[str, Any], json.loads(result.stdout))
except json.JSONDecodeError as e:
raise GhCommandError(f'gh returned non-JSON output: {e}', str(e)) from e
def _check_gh_available() -> bool:
if not shutil.which('gh'):
logger.error('gh CLI is required but not found. Install from https://cli.github.com/')
return False
try:
result = subprocess.run(
['gh', 'auth', 'status'],
capture_output=True,
text=True,
encoding='utf-8',
errors='replace',
timeout=10,
)
except (subprocess.SubprocessError, OSError) as e:
logger.error('Could not run `gh auth status`: %s', e)
return False
if result.returncode != 0:
logger.error('gh CLI is not authenticated. Run: gh auth login')
return False
return True
MAX_PR_NUMBER = 999999
def _fetch_batch_with_retry(
batch: list[int],
batch_num: int,
owner: str,
repo: str,
) -> dict[str, Any] | None:
"""Fetch one batch, handling the two failure modes that are worth handling.
Returns the response, or None when the batch could not be salvaged and the
caller should fall back to one request per PR.
An unresolvable PR number is permanent, so the batch drops it and retries
immediately: previously a single bad number (an issue reference picked up
from a commit subject) failed the whole batch and cost 30 individual
requests. A transient failure backs off exponentially instead of instantly
degrading to 30 requests, which is the worst possible response to a rate
limit.
"""
remaining = list(batch)
for attempt in range(MAX_BATCH_ATTEMPTS):
if not remaining:
return None
try:
return _run_gh_command(
['gh', 'api', 'graphql',
'-f', f'query={_build_graphql_query(remaining)}',
'-f', f'owner={owner}',
'-f', f'name={repo}'],
timeout=60,
)
except GhCommandError as e:
unresolvable = _unresolvable_pr_numbers(e.stderr) & set(remaining)
if unresolvable:
remaining = [n for n in remaining if n not in unresolvable]
logger.warning(
'Batch %d: %s not resolvable as pull request(s) (likely an issue '
'reference in a commit subject); dropping and retrying %d PR(s)',
batch_num, ', '.join(f'#{n}' for n in sorted(unresolvable)), len(remaining),
)
continue
if _is_transient_error(e.stderr) and attempt < MAX_BATCH_ATTEMPTS - 1:
delay = _backoff_seconds(attempt)
logger.warning(
'Batch %d failed transiently (attempt %d/%d); retrying in %.0fs',
batch_num, attempt + 1, MAX_BATCH_ATTEMPTS, delay,
)