Repository navigation
Expand file tree
/
Copy pathspec_metadata.py
More file actions
executable file
·561 lines (479 loc) · 23.8 KB
/
Copy pathspec_metadata.py
File metadata and controls
executable file
·561 lines (479 loc) · 23.8 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
#! /usr/bin/env python3
"""
Copyright (C) 2026 Intel Corporation
SPDX-License-Identifier: MIT
Drives regeneration of the loader sources that scripts/templates/*.mako owns,
using the specification metadata archived under scripts/spec_metadata/.
A large share of the files committed under source/ (and
include/layers/zel_tracing_register_cb.h) are generated by scripts/json2src.py
from Mako templates. Editing one of those files directly instead of editing its
template appears to work until the next regeneration silently discards the edit
and the build breaks. Archiving the metadata lets CI regenerate and rebuild on
every change, so that class of mistake is caught while it is still cheap.
Subcommands:
regen regenerate the loader sources in place from the archived metadata
check report which files a regeneration would change (never fails)
refresh re-archive the metadata from a specification repository clone
'regen' and 'check' need only Mako. 'refresh' additionally needs PyYAML, plus a
clone of https://github.com/oneapi-src/level-zero-spec.
"""
import argparse
import difflib
import filecmp
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
SCRIPTS_DIR = os.path.dirname(os.path.realpath(__file__))
DEFAULT_REPO_ROOT = os.path.dirname(SCRIPTS_DIR)
MANIFEST_NAME = "spec_metadata.json"
def metadata_dir(repo_root):
return os.path.join(repo_root, "scripts", "spec_metadata")
# Subtrees written by scripts/json2src.py. 'check' compares these in full, so a
# file the generator newly introduces is reported alongside modified ones.
GENERATED_ROOTS = ["source", os.path.join("include", "layers")]
TEMPLATE_HINT = (
"A generated file was edited directly instead of its template.\n"
"Move the change into the matching template under scripts/templates/ so that\n"
"it survives the next regeneration."
)
def eprint(*args):
print(*args, file=sys.stderr)
def sha256_of(path):
digest = hashlib.sha256()
with open(path, "rb") as fin:
for chunk in iter(lambda: fin.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def sha256_of_lf(path):
"""sha256 of 'path' with CRLF normalised to LF, to recognise a converted checkout."""
digest = hashlib.sha256()
with open(path, "rb") as fin:
trailing_cr = b""
for chunk in iter(lambda: fin.read(1 << 20), b""):
chunk = trailing_cr + chunk
# A CR at the very end may pair with an LF in the next chunk, so hold it.
trailing_cr = b"\r" if chunk.endswith(b"\r") else b""
if trailing_cr:
chunk = chunk[:-1]
digest.update(chunk.replace(b"\r\n", b"\n"))
digest.update(trailing_cr)
return digest.hexdigest()
def load_manifest(repo_root):
path = os.path.join(metadata_dir(repo_root), MANIFEST_NAME)
if not os.path.isfile(path):
eprint("error: missing %s" % path)
eprint(" Run 'scripts/spec_metadata.py refresh --help' to create it.")
sys.exit(1)
with open(path, "r") as fin:
manifest = json.load(fin)
for key in ("api_version", "input_json", "input_json_sha256"):
if key not in manifest:
eprint("error: %s is missing required key '%s'" % (path, key))
sys.exit(1)
return manifest
def archived_input_json(repo_root, manifest):
path = os.path.join(metadata_dir(repo_root), manifest["input_json"])
if not os.path.isfile(path):
eprint("error: archived metadata not found: %s" % path)
sys.exit(1)
return path
def verify_archive(repo_root, manifest):
"""Guard against a corrupted or partially updated archive."""
path = archived_input_json(repo_root, manifest)
actual = sha256_of(path)
expected = manifest["input_json_sha256"]
if actual != expected:
eprint("error: %s does not match the sha256 recorded in %s" % (path, MANIFEST_NAME))
eprint(" expected %s" % expected)
eprint(" actual %s" % actual)
if sha256_of_lf(path) == expected:
# By far the likeliest cause on Windows, and unrecoverable by
# re-archiving: the archive is intact, the checkout converted it.
eprint(" The contents are intact; only the line endings differ, so this")
eprint(" checkout converted LF to CRLF. Confirm .gitattributes marks")
eprint(" scripts/spec_metadata/input.json as '-text', then re-checkout:")
eprint(" git rm --cached -r . && git reset --hard")
else:
eprint(" Re-run 'scripts/spec_metadata.py refresh' to re-archive the metadata.")
sys.exit(1)
def spec_version_from_headers(repo_root):
"""Read the '@version v1.17-r1.17.24' banner the spec stamps into ze_api.h.
Returns (api_version, revision), either of which may be None.
"""
header = os.path.join(repo_root, "include", "ze_api.h")
try:
with open(header, "r") as fin:
for line in fin:
match = re.search(r"@version\s+v(\d+\.\d+)-r(\S+)", line)
if match:
return match.group(1), match.group(2)
if "@version" in line:
break
except IOError:
pass
return None, None
def check_metadata_matches_headers(repo_root, manifest):
"""The archived metadata must describe the same spec release as the headers.
If the headers are bumped without re-archiving, a regeneration would rewrite
every source file against the *previous* spec -- exactly the silent breakage
this tooling exists to prevent, so an API version mismatch is fatal. The
revision suffix is only a commit count, so a mismatch there is a warning.
"""
api_version, revision = spec_version_from_headers(repo_root)
if api_version is None:
eprint("warning: could not read the @version banner from include/ze_api.h;")
eprint(" skipping the archived-metadata version cross-check.")
return
if api_version != manifest["api_version"]:
eprint("error: archived spec metadata does not match the committed headers.")
eprint(" include/ze_api.h declares API version %s" % api_version)
eprint(" %s pins API version %s" % (MANIFEST_NAME, manifest["api_version"]))
eprint(" Regenerating would rewrite the sources against the wrong spec.")
eprint(" Re-archive with 'scripts/spec_metadata.py refresh'.")
sys.exit(1)
pinned_revision = manifest.get("spec_revision")
if pinned_revision and revision and revision != pinned_revision:
eprint("warning: include/ze_api.h was generated from spec revision %s but the" % revision)
eprint(" archived metadata is from %s. The API version matches, so this" % pinned_revision)
eprint(" is usually harmless, but consider re-archiving.")
def run_json2src(work_root, manifest, input_json, quiet=True):
"""Invoke scripts/json2src.py against 'work_root'.
json2src.py accepts an output root but still resolves several intermediate
files relative to the current directory, so it must run with cwd set to the
tree being generated into.
"""
generator = os.path.join(work_root, "scripts", "json2src.py")
command = [
sys.executable,
generator,
"--api-json", input_json,
"--ver", manifest["api_version"],
".",
]
result = subprocess.run(
command,
cwd=work_root,
stdout=subprocess.DEVNULL if quiet else None,
stderr=subprocess.PIPE if quiet else None,
)
if result.returncode != 0:
eprint("error: source generation failed (%s)" % " ".join(command))
if quiet and result.stderr:
eprint(result.stderr.decode("utf-8", "replace"))
if quiet:
eprint(" Re-run with --verbose for the full generator output.")
sys.exit(1)
def require_mako():
try:
import mako # noqa: F401
except ImportError:
eprint("error: the Mako templating package is required to regenerate sources.")
eprint(" Install it with: pip install Mako")
sys.exit(1)
def cmd_regen(args):
require_mako()
repo_root = args.repo_root
manifest = load_manifest(repo_root)
verify_archive(repo_root, manifest)
check_metadata_matches_headers(repo_root, manifest)
print("Regenerating loader sources from spec %s (API version %s)"
% (manifest.get("spec_tag") or manifest.get("spec_commit", "?"), manifest["api_version"]))
run_json2src(repo_root, manifest, archived_input_json(repo_root, manifest),
quiet=not args.verbose)
print("Regeneration complete.")
return 0
def collect_files(root):
"""Relative paths of every file under 'root', which may not exist."""
found = set()
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames if d != "__pycache__"]
for name in filenames:
found.add(os.path.relpath(os.path.join(dirpath, name), root))
return found
def first_difference_line(original, regenerated):
"""1-based line number of the first difference, for a source annotation."""
for index, (lhs, rhs) in enumerate(zip(original, regenerated), start=1):
if lhs != rhs:
return index
return min(len(original), len(regenerated)) + 1
def read_lines(path):
with open(path, "r", encoding="utf-8", errors="replace") as fin:
return fin.readlines()
def cmd_check(args):
require_mako()
repo_root = args.repo_root
manifest = load_manifest(repo_root)
verify_archive(repo_root, manifest)
check_metadata_matches_headers(repo_root, manifest)
input_json = archived_input_json(repo_root, manifest)
work_root = tempfile.mkdtemp(prefix="l0-regen-check-")
try:
# Generate into a throwaway copy so the caller's working tree is never
# touched. Copying the existing sources (rather than starting empty)
# means an unchanged file simply compares equal.
# The generator and templates are copied along with the sources so the
# check always exercises this tree's own scripts/templates/. The archived
# metadata is passed by path instead, so there is no need to copy it.
for subdir in ["scripts"] + [r.split(os.sep)[0] for r in GENERATED_ROOTS]:
source = os.path.join(repo_root, subdir)
destination = os.path.join(work_root, subdir)
if os.path.isdir(source) and not os.path.exists(destination):
shutil.copytree(source, destination,
ignore=shutil.ignore_patterns("__pycache__",
"spec_metadata"))
run_json2src(work_root, manifest, input_json, quiet=not args.verbose)
modified, added = [], []
for relative_root in GENERATED_ROOTS:
original_root = os.path.join(repo_root, relative_root)
regenerated_root = os.path.join(work_root, relative_root)
for name in sorted(collect_files(regenerated_root)):
regenerated = os.path.join(regenerated_root, name)
original = os.path.join(original_root, name)
display = os.path.join(relative_root, name).replace(os.sep, "/")
if not os.path.exists(original):
added.append(display)
elif not filecmp.cmp(original, regenerated, shallow=False):
modified.append((display, original, regenerated))
if not modified and not added:
print("No drift: the committed sources match a regeneration from the "
"archived spec metadata.")
return 0
print("%d file(s) differ from a regeneration of the archived spec metadata."
% (len(modified) + len(added)))
print("")
print(TEMPLATE_HINT)
print("")
print("Note: this is advisory. The build-and-test job is what gates the change;")
print(" comment-only or wording-only drift is expected after the spec is")
print(" edited upstream and is safe to ignore.")
print("")
for display in added:
print(" added by regeneration: %s" % display)
if args.github:
print("::warning file=%s,line=1::This file would be created by regeneration "
"from the archived spec metadata." % display)
for display, original, regenerated in modified:
original_lines = read_lines(original)
regenerated_lines = read_lines(regenerated)
line = first_difference_line(original_lines, regenerated_lines)
print(" would change: %s (first difference at line %d)" % (display, line))
if args.github:
print("::warning file=%s,line=%d::Regenerating from the archived spec "
"metadata changes this file. If the change here was hand-written, "
"move it into the matching scripts/templates/*.mako template or it "
"will be lost." % (display, line))
if args.diff:
diff = difflib.unified_diff(
original_lines, regenerated_lines,
fromfile="%s (committed)" % display,
tofile="%s (regenerated)" % display)
sys.stdout.writelines(diff)
# Drift alone never fails: the gate is whether the regenerated tree still
# builds and passes its tests.
return 0
finally:
shutil.rmtree(work_root, ignore_errors=True)
def git_output(repo, *arguments):
result = subprocess.run(["git", "-C", repo] + list(arguments),
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
if result.returncode != 0:
return None
return result.stdout.decode().strip()
def detect_api_version(spec_repo):
"""Derive the MAJOR.MINOR API version from the spec clone's checked-out release.
Deliberately the same rule as the spec repository's own
run.py:detect_version_git_major_minor() -- the most recent tag *reachable from
the current checkout*, not the highest tag in the clone. Those differ once a
newer release exists: archiving a v1.17.24 checkout must yield 1.17 even when
v1.18.0 is present, because the API version is a max-version filter and a
value that overshoots the checkout silently admits functions the metadata does
not describe.
"""
described = git_output(spec_repo, "describe", "--tags", "--abbrev=0")
if not described:
return None
parts = described.lstrip("v").split(".")
if len(parts) >= 2 and parts[0].isdigit() and parts[1].isdigit():
return "%s.%s" % (parts[0], parts[1])
return None
def generate_input_json(spec_repo, api_version, destination):
"""Dump the spec's intermediate metadata without its documentation toolchain.
This mirrors phases 1 and 2 of the spec repository's scripts/run.py. run.py
itself is not reused because it validates the full Sphinx documentation
toolchain up front and exits when any of it is missing, even when only the
metadata is wanted. Driving parse_specs directly needs Mako and PyYAML only,
and produces a byte-identical file.
Runs in a subprocess so the spec repository's 'util' module cannot collide
with the loader's module of the same name.
"""
program = (
"import json, os, sys\n"
"scripts = sys.argv[1]\n"
"version = sys.argv[2]\n"
"destination = sys.argv[3]\n"
"sys.path.insert(0, scripts)\n"
"os.chdir(scripts)\n"
"import util, parse_specs\n"
"parser = util.configRead('config.ini')\n"
"data = {'configs': [], 'specs': [], 'meta': {}, 'ref': {}}\n"
"for section in parser.sections():\n"
" data['configs'].append({\n"
" 'name': section,\n"
" 'namespace': parser.get(section, 'namespace'),\n"
" 'tags': {'$' + key: parser.get(section, key)\n"
" for key in parser.get(section, 'tags').split(',')},\n"
" })\n"
"for config in data['configs']:\n"
" specs, data['meta'], data['ref'] = parse_specs.parse(\n"
" config['name'], version, config['tags'], data['meta'], data['ref'])\n"
" data['specs'].append(specs)\n"
"with open(destination, 'w') as fout:\n"
" fout.write(json.dumps(data, indent=4, sort_keys=True))\n"
)
spec_scripts = os.path.join(spec_repo, "scripts")
if not os.path.isdir(spec_scripts):
eprint("error: %s does not look like a level-zero-spec clone (no scripts/)" % spec_repo)
sys.exit(1)
result = subprocess.run([sys.executable, "-c", program, spec_scripts, api_version, destination],
stdout=subprocess.DEVNULL)
if result.returncode != 0:
eprint("error: failed to generate metadata from %s" % spec_repo)
eprint(" 'refresh' needs both Mako and PyYAML: pip install Mako PyYAML")
sys.exit(1)
def cmd_refresh(args):
spec_repo = os.path.abspath(args.spec_repo)
if not os.path.isdir(spec_repo):
eprint("error: no such directory: %s" % spec_repo)
sys.exit(1)
commit = git_output(spec_repo, "rev-parse", "HEAD")
described = git_output(spec_repo, "describe", "--tags")
exact_tag = git_output(spec_repo, "describe", "--tags", "--exact-match")
# Guard against archiving from an unintended checkout.
if args.ref:
wanted = git_output(spec_repo, "rev-parse", "%s^{commit}" % args.ref)
if wanted is None:
eprint("error: '%s' is not a valid ref in %s" % (args.ref, spec_repo))
sys.exit(1)
if wanted != commit:
eprint("error: %s is checked out at %s, not at %s (%s)."
% (spec_repo, commit, args.ref, wanted))
eprint(" Check out the wanted ref there first; this command does not")
eprint(" modify the specification clone.")
sys.exit(1)
if exact_tag is None:
eprint("warning: %s is not checked out at a tagged release (describe: %s)."
% (spec_repo, described))
eprint(" Archived metadata is normally taken from an official spec release.")
# The API version is a max-version filter on the spec metadata, not a label:
# too low silently drops functions, too high admits ones the checkout does not
# describe. Derive it from the checkout rather than carrying it by hand.
detected = detect_api_version(spec_repo)
api_version = args.ver or detected
if not api_version:
eprint("error: could not determine the specification API version.")
eprint(" %s has no reachable version tag; pass --ver explicitly." % spec_repo)
sys.exit(1)
if args.ver and detected and args.ver != detected:
eprint("warning: --ver %s was given, but %s is checked out at %s (API version %s)."
% (args.ver, spec_repo, described or "an untagged commit", detected))
eprint(" Archiving %s anyway. A version below the checkout drops every"
% args.ver)
eprint(" function added after it, which still compiles but yields a")
eprint(" loader missing those exports.")
elif not args.ver:
nearest = git_output(spec_repo, "describe", "--tags", "--abbrev=0")
print("Detected API version %s from the nearest release tag %s"
% (api_version, nearest))
archive_dir = metadata_dir(args.repo_root)
os.makedirs(archive_dir, exist_ok=True)
destination = os.path.join(archive_dir, "input.json")
if args.input_json:
# Reuse metadata the spec's own run.py already produced, so a CI job that
# has just generated it does not pay to build it twice.
if not os.path.isfile(args.input_json):
eprint("error: no such file: %s" % args.input_json)
sys.exit(1)
shutil.copyfile(args.input_json, destination)
else:
generate_input_json(spec_repo, api_version, destination)
revision = None
if described:
# 'v1.17.24' or 'v1.17.24-14-gdeadbee' -> '1.17.24'
revision = described.lstrip("v").split("-")[0]
manifest = {
"_comment": [
"Pinned Level Zero specification metadata for the spec release this loader targets.",
"'input.json' is the verbatim intermediate produced by the spec repository's",
"scripts/run.py; it is the sole input needed to regenerate every loader source file",
"that scripts/templates/*.mako owns. Refresh both files together whenever the spec",
"is updated -- see scripts/spec_metadata.py refresh.",
],
"api_version": api_version,
"generated_by": "scripts/spec_metadata.py refresh --spec-repo <clone> --ref %s --ver %s"
% (exact_tag or commit, api_version),
"input_json": "input.json",
"input_json_sha256": sha256_of(destination),
"spec_commit": commit,
"spec_repository": args.spec_url,
"spec_revision": revision,
"spec_tag": exact_tag,
}
with open(os.path.join(archive_dir, MANIFEST_NAME), "w") as fout:
fout.write(json.dumps(manifest, indent=4, sort_keys=True))
fout.write("\n")
print("Archived spec metadata from %s" % (exact_tag or commit))
print(" %s" % destination)
print(" %s" % os.path.join(archive_dir, MANIFEST_NAME))
print("")
print("Regenerate and rebuild before committing:")
print(" python3 scripts/spec_metadata.py regen")
return 0
def main():
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--repo-root", default=DEFAULT_REPO_ROOT,
help="root of the loader repository (default: the repository "
"containing this script)")
parser.add_argument("--verbose", action="store_true",
help="show the full source generator output")
subparsers = parser.add_subparsers(dest="command")
regen = subparsers.add_parser(
"regen", help="regenerate the loader sources in place from the archived metadata")
regen.set_defaults(func=cmd_regen)
check = subparsers.add_parser(
"check", help="report which files a regeneration would change (never fails)")
check.add_argument("--github", action="store_true",
help="emit GitHub Actions warning annotations")
check.add_argument("--diff", action="store_true",
help="print a unified diff for each changed file")
check.set_defaults(func=cmd_check)
refresh = subparsers.add_parser(
"refresh", help="re-archive the metadata from a specification repository clone")
refresh.add_argument("--spec-repo", required=True,
help="path to a level-zero-spec clone, already checked out at the "
"release to archive")
refresh.add_argument("--ref",
help="verify the clone is checked out at this ref before archiving")
refresh.add_argument("--ver",
help="specification API version to generate for, e.g. 1.17. "
"Detected from the spec clone's most recent reachable tag "
"when omitted.")
refresh.add_argument("--input-json",
help="use this already-generated input.json instead of building one")
refresh.add_argument("--spec-url", default="https://github.com/oneapi-src/level-zero-spec",
help="specification repository URL to record in the manifest")
refresh.set_defaults(func=cmd_refresh)
args = parser.parse_args()
if not getattr(args, "func", None):
parser.print_help()
return 1
args.repo_root = os.path.abspath(args.repo_root)
return args.func(args)
if __name__ == "__main__":
sys.exit(main())