codemeta-drift 0.7.0__tar.gz → 0.7.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/PKG-INFO +2 -2
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/README.md +1 -1
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/pyproject.toml +1 -1
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/pyproject.toml.orig +1 -1
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/checks.py +10 -0
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/cli.py +79 -30
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/coverage.py +9 -5
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/curated-3.1.json +7 -0
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/curated-4.0.json +7 -0
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/export.py +13 -9
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/mapping-vectors.json +20 -0
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/poll.py +53 -26
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/watcher.py +11 -1
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/LICENSE +0 -0
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/__init__.py +0 -0
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/conformance.py +0 -0
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/hub.py +0 -0
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/mapping.schema.json +0 -0
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/paths.py +0 -0
- {codemeta_drift-0.7.0 → codemeta_drift-0.7.2}/src/codemeta_drift/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: codemeta-drift
|
|
3
|
-
Version: 0.7.
|
|
3
|
+
Version: 0.7.2
|
|
4
4
|
Summary: Show where CodeMeta's crosswalks are wrong or missing, check CodeMeta consistency, export JSON crosswalk mappings and SSSOM, and preview schema drift for review
|
|
5
5
|
Keywords: CodeMeta,software metadata,crosswalk,crosswalk coverage,JSON-LD,SSSOM,schema drift
|
|
6
6
|
Author: Simon van Lierde
|
|
@@ -124,7 +124,7 @@ also checks citesync's mapping pin. Publishing requires a configured token.
|
|
|
124
124
|
|
|
125
125
|
## Development
|
|
126
126
|
|
|
127
|
-
From a codemeta-drift checkout, with uv
|
|
127
|
+
From a codemeta-drift checkout, with uv, [just](https://just.systems) and Node (its built-in test runner, no packages) installed:
|
|
128
128
|
|
|
129
129
|
```sh
|
|
130
130
|
uv sync
|
|
@@ -101,7 +101,7 @@ also checks citesync's mapping pin. Publishing requires a configured token.
|
|
|
101
101
|
|
|
102
102
|
## Development
|
|
103
103
|
|
|
104
|
-
From a codemeta-drift checkout, with uv
|
|
104
|
+
From a codemeta-drift checkout, with uv, [just](https://just.systems) and Node (its built-in test runner, no packages) installed:
|
|
105
105
|
|
|
106
106
|
```sh
|
|
107
107
|
uv sync
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "codemeta-drift"
|
|
3
|
-
version = "0.7.
|
|
3
|
+
version = "0.7.2"
|
|
4
4
|
description = "Show where CodeMeta's crosswalks are wrong or missing, check CodeMeta consistency, export JSON crosswalk mappings and SSSOM, and preview schema drift for review"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.13"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "codemeta-drift"
|
|
3
|
-
version = "0.7.
|
|
3
|
+
version = "0.7.2"
|
|
4
4
|
description = "Show where CodeMeta's crosswalks are wrong or missing, check CodeMeta consistency, export JSON crosswalk mappings and SSSOM, and preview schema drift for review"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.13"
|
|
@@ -12,6 +12,7 @@ import csv
|
|
|
12
12
|
import difflib
|
|
13
13
|
import io
|
|
14
14
|
import json
|
|
15
|
+
import re
|
|
15
16
|
from collections import Counter
|
|
16
17
|
from collections.abc import Iterator, Mapping
|
|
17
18
|
from dataclasses import dataclass
|
|
@@ -29,6 +30,15 @@ NOT_PROPERTIES = frozenset({"type", "id", "schema", "codemeta"})
|
|
|
29
30
|
"""Context keys that are keyword aliases or prefixes, not properties."""
|
|
30
31
|
|
|
31
32
|
|
|
33
|
+
def code_span(text: str) -> str:
|
|
34
|
+
"""``text`` as one Markdown code span that no backtick in it can close early."""
|
|
35
|
+
text = re.sub(r"\r\n?|\n", " ", text) # every CommonMark line ending: a blank line would end the span's block
|
|
36
|
+
fence = "`" * (max(map(len, re.findall("`+", text)), default=0) + 1)
|
|
37
|
+
# CommonMark strips one space each side: the pad keeps an edge backtick apart from the fence, and edge spaces.
|
|
38
|
+
pad = " " if text[:1] == "`" or text[-1:] == "`" or (text[:1] == text[-1:] == " ") else ""
|
|
39
|
+
return f"{fence}{pad}{text}{pad}{fence}"
|
|
40
|
+
|
|
41
|
+
|
|
32
42
|
@dataclass(frozen=True)
|
|
33
43
|
class Finding:
|
|
34
44
|
"""One disagreement between two CodeMeta files.
|
|
@@ -12,6 +12,7 @@ error so standard output is never a partial file. A TAG with no curated rows is
|
|
|
12
12
|
"""
|
|
13
13
|
|
|
14
14
|
import argparse
|
|
15
|
+
import contextlib
|
|
15
16
|
import fnmatch
|
|
16
17
|
import json
|
|
17
18
|
import os
|
|
@@ -20,20 +21,19 @@ import subprocess
|
|
|
20
21
|
import sys
|
|
21
22
|
from collections.abc import Mapping, Sequence
|
|
22
23
|
from dataclasses import asdict
|
|
23
|
-
from importlib import metadata
|
|
24
24
|
from pathlib import Path
|
|
25
|
-
from typing import NoReturn
|
|
25
|
+
from typing import Any, NoReturn
|
|
26
26
|
|
|
27
27
|
from codemeta_drift.checks import CONTEXT, TABLE, check
|
|
28
28
|
from codemeta_drift.conformance import SCHEMA_FILES, conform
|
|
29
|
-
from codemeta_drift.export import curated_tags, export
|
|
29
|
+
from codemeta_drift.export import curated_tags, export, generator
|
|
30
30
|
|
|
31
31
|
JSON_VERSION = 1
|
|
32
32
|
"""Every ``--json`` report's ``schema_version``: a release may add keys; removing or retyping one bumps it."""
|
|
33
33
|
|
|
34
34
|
EXIT_FINDINGS, EXIT_USAGE, EXIT_CANNOT_RUN, EXIT_INTERRUPTED = 1, 2, 3, 130
|
|
35
35
|
|
|
36
|
-
READ_ERRORS = (OSError, ValueError, KeyError, IndexError, TypeError, AttributeError)
|
|
36
|
+
READ_ERRORS = (OSError, ValueError, KeyError, IndexError, TypeError, AttributeError, RecursionError)
|
|
37
37
|
"""What a missing, unreadable or malformed input raises: the command could not run (exit 3), never exit 1."""
|
|
38
38
|
|
|
39
39
|
INPUTS = (
|
|
@@ -63,11 +63,16 @@ def is_input(path: str) -> bool:
|
|
|
63
63
|
|
|
64
64
|
def read_dir(root: Path) -> dict[str, str]:
|
|
65
65
|
"""The input files of a working tree, as path -> text."""
|
|
66
|
+
|
|
67
|
+
def linked(path: Path) -> bool: # the file or a folder on its way: read_ref reads no link, so neither does this
|
|
68
|
+
relative = path.relative_to(root)
|
|
69
|
+
return any((root / part).is_symlink() for part in [relative, *relative.parents[:-1]])
|
|
70
|
+
|
|
66
71
|
return {
|
|
67
72
|
p.relative_to(root).as_posix(): p.read_text(encoding="utf-8")
|
|
68
73
|
for g in INPUTS
|
|
69
74
|
for p in root.glob(g)
|
|
70
|
-
if p.is_file()
|
|
75
|
+
if p.is_file() and not linked(p)
|
|
71
76
|
}
|
|
72
77
|
|
|
73
78
|
|
|
@@ -85,8 +90,8 @@ def read_ref(root: Path, ref: str) -> dict[str, str]:
|
|
|
85
90
|
for entry in git("ls-tree", "-r", "-z", commit).decode("utf-8").split("\0"):
|
|
86
91
|
if entry:
|
|
87
92
|
meta, path = entry.split("\t", 1)
|
|
88
|
-
|
|
89
|
-
if kind == "blob" and is_input(path):
|
|
93
|
+
mode, kind, oid = meta.split()
|
|
94
|
+
if kind == "blob" and mode != "120000" and is_input(path): # 120000: a symlink's target text
|
|
90
95
|
blobs[path] = oid
|
|
91
96
|
|
|
92
97
|
# One cat-file process reads every file; one git process per file doubles the run time.
|
|
@@ -135,14 +140,15 @@ def export_main(argv: list[str]) -> int:
|
|
|
135
140
|
if args.out:
|
|
136
141
|
target = args.out
|
|
137
142
|
args.out.write_text(text, encoding="utf-8")
|
|
138
|
-
else:
|
|
139
|
-
print(text, end="")
|
|
140
143
|
except subprocess.CalledProcessError as err:
|
|
141
144
|
print(f"codemeta-drift: cannot read {target}: {err.stderr.decode().strip()}", file=sys.stderr)
|
|
142
145
|
return EXIT_CANNOT_RUN
|
|
143
146
|
except READ_ERRORS as err:
|
|
144
147
|
print(f"codemeta-drift: cannot read or write {target}: {type(err).__name__}: {err}", file=sys.stderr)
|
|
145
148
|
return EXIT_CANNOT_RUN
|
|
149
|
+
# Outside the try, as in every subcommand: a stdout that fails is entry()'s to report, quietly for a closed pipe.
|
|
150
|
+
if not args.out:
|
|
151
|
+
print(text, end="")
|
|
146
152
|
return 0
|
|
147
153
|
|
|
148
154
|
|
|
@@ -202,23 +208,29 @@ def hub_main(argv: list[str]) -> int:
|
|
|
202
208
|
text = table(pair_rows(mapping, args.source, args.target), ["term", "source", "target"])
|
|
203
209
|
if args.out:
|
|
204
210
|
args.out.write_text(text, encoding="utf-8")
|
|
205
|
-
|
|
206
|
-
print(text, end="")
|
|
211
|
+
return 0
|
|
207
212
|
except UsageError as err:
|
|
208
213
|
print(f"codemeta-drift: {err}", file=sys.stderr)
|
|
209
214
|
return EXIT_USAGE
|
|
210
|
-
except (OSError, ValueError) as err:
|
|
215
|
+
except (OSError, ValueError, RecursionError) as err:
|
|
211
216
|
if getattr(args, "json", False):
|
|
212
|
-
|
|
217
|
+
report = json_report({}, [{"message": str(err), "help": None}])
|
|
218
|
+
written = False
|
|
219
|
+
if args.out:
|
|
220
|
+
with contextlib.suppress(OSError): # an unwritable --out falls back to stdout
|
|
221
|
+
written = args.out.write_text(report, encoding="utf-8") > 0
|
|
222
|
+
if not written:
|
|
223
|
+
print(report, end="")
|
|
213
224
|
else:
|
|
214
225
|
print(f"codemeta-drift: {err}", file=sys.stderr)
|
|
215
226
|
return EXIT_CANNOT_RUN
|
|
227
|
+
print(text, end="") # outside the try, as in export_main
|
|
216
228
|
return 0
|
|
217
229
|
|
|
218
230
|
|
|
219
231
|
def watch_main(argv: list[str]) -> int:
|
|
220
232
|
"""Compare downloaded schemas and print issue drafts, without opening issues."""
|
|
221
|
-
from codemeta_drift.watcher import issue_plans, schema_changes # noqa: PLC0415 - only watch needs this
|
|
233
|
+
from codemeta_drift.watcher import issue_plans, pin_tag, schema_changes # noqa: PLC0415 - only watch needs this
|
|
222
234
|
|
|
223
235
|
parser = argparse.ArgumentParser(prog="codemeta-drift watch", description="Preview schema and pin issues offline.")
|
|
224
236
|
parser.add_argument("checkout", type=Path)
|
|
@@ -243,24 +255,19 @@ def watch_main(argv: list[str]) -> int:
|
|
|
243
255
|
{fmt: json.loads((directory / name).read_text("utf-8")) for fmt, name in SCHEMA_FILES.items()}
|
|
244
256
|
for directory in (args.before, args.after)
|
|
245
257
|
]
|
|
246
|
-
|
|
247
|
-
line.split()[1] for line in args.citesync_source.read_text("utf-8").splitlines() if line.startswith("tag ")
|
|
248
|
-
]
|
|
249
|
-
if len(pins) != 1:
|
|
250
|
-
msg = "MAPPING_SOURCE must contain exactly one tag line"
|
|
251
|
-
raise ValueError(msg)
|
|
258
|
+
pin = pin_tag(args.citesync_source.read_text("utf-8"))
|
|
252
259
|
existing = json.loads(args.existing.read_text("utf-8"))
|
|
253
260
|
if not isinstance(existing, list) or any(not isinstance(title, str) for title in existing):
|
|
254
261
|
msg = "existing issues must be a JSON list of titles"
|
|
255
262
|
raise ValueError(msg)
|
|
256
|
-
|
|
257
|
-
print(json.dumps(issue_plans(changes, pins[0], args.latest, set(existing)), indent=2))
|
|
263
|
+
plans = issue_plans(schema_changes(mapping["rows"], *snapshots), pin, args.latest, set(existing))
|
|
258
264
|
except subprocess.CalledProcessError as err:
|
|
259
265
|
print(f"codemeta-drift: {err.stderr.decode().strip()}", file=sys.stderr)
|
|
260
266
|
return EXIT_CANNOT_RUN
|
|
261
267
|
except READ_ERRORS as err:
|
|
262
268
|
print(f"codemeta-drift: {type(err).__name__}: {err}", file=sys.stderr)
|
|
263
269
|
return EXIT_CANNOT_RUN
|
|
270
|
+
print(json.dumps(plans, indent=2)) # outside the try, as in export_main
|
|
264
271
|
return 0
|
|
265
272
|
|
|
266
273
|
|
|
@@ -273,10 +280,29 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
273
280
|
return commands[argv[0]](argv[1:])
|
|
274
281
|
return check_main(argv)
|
|
275
282
|
except KeyboardInterrupt:
|
|
276
|
-
|
|
283
|
+
with contextlib.suppress(OSError): # an unwritable stderr must not turn Ctrl-C into exit 3
|
|
284
|
+
print("codemeta-drift: interrupted", file=sys.stderr)
|
|
277
285
|
return EXIT_INTERRUPTED
|
|
278
286
|
|
|
279
287
|
|
|
288
|
+
class VersionAction(argparse.Action):
|
|
289
|
+
"""``--version``, reading the installed version only when asked: importlib.metadata costs about 10 ms."""
|
|
290
|
+
|
|
291
|
+
def __init__(self, option_strings: Sequence[str], dest: str, **kwargs: Any) -> None: # noqa: ANN401 - argparse's own
|
|
292
|
+
super().__init__(option_strings, dest, nargs=0, help="show the version and exit", **kwargs)
|
|
293
|
+
|
|
294
|
+
def __call__(
|
|
295
|
+
self,
|
|
296
|
+
parser: argparse.ArgumentParser,
|
|
297
|
+
namespace: argparse.Namespace, # noqa: ARG002 - argparse's signature
|
|
298
|
+
values: str | Sequence[Any] | None, # noqa: ARG002
|
|
299
|
+
option_string: str | None = None, # noqa: ARG002
|
|
300
|
+
) -> None:
|
|
301
|
+
"""Print ``codemeta-drift <version>`` and exit 0."""
|
|
302
|
+
print(f"{parser.prog} {generator()['version']}")
|
|
303
|
+
parser.exit()
|
|
304
|
+
|
|
305
|
+
|
|
280
306
|
def check_main(argv: list[str]) -> int:
|
|
281
307
|
"""Run every check on one snapshot and print the findings."""
|
|
282
308
|
parser = argparse.ArgumentParser(
|
|
@@ -288,17 +314,16 @@ def check_main(argv: list[str]) -> int:
|
|
|
288
314
|
"codemeta-drift watch --help for schema comparison."
|
|
289
315
|
),
|
|
290
316
|
)
|
|
291
|
-
parser.add_argument("--version", action=
|
|
317
|
+
parser.add_argument("--version", action=VersionAction)
|
|
292
318
|
parser.add_argument("checkout", type=Path, help="root of a codemeta clone")
|
|
293
319
|
parser.add_argument("--ref", help="read this commit, tag or branch instead of the working tree")
|
|
294
320
|
parser.add_argument("--json", action="store_true", help="print the findings as one JSON document")
|
|
295
321
|
args = parser.parse_args(argv)
|
|
296
|
-
tool = {"name": "codemeta-drift", "version": metadata.version("codemeta-drift")}
|
|
297
322
|
|
|
298
323
|
def cannot_run(message: str, help_: str | None) -> int:
|
|
299
324
|
# A malformed file must not exit 1, which means drift.
|
|
300
325
|
if args.json:
|
|
301
|
-
print(json_report({"tool":
|
|
326
|
+
print(json_report({"tool": generator(), "findings": []}, [{"message": message, "help": help_}]), end="")
|
|
302
327
|
else:
|
|
303
328
|
print(f"codemeta-drift: {message}", file=sys.stderr)
|
|
304
329
|
return EXIT_CANNOT_RUN
|
|
@@ -313,7 +338,7 @@ def check_main(argv: list[str]) -> int:
|
|
|
313
338
|
except READ_ERRORS as err:
|
|
314
339
|
return cannot_run(f"cannot read {args.checkout}: {type(err).__name__}: {err}", None)
|
|
315
340
|
if args.json:
|
|
316
|
-
print(json_report({"tool":
|
|
341
|
+
print(json_report({"tool": generator(), "findings": [asdict(f) for f in findings]}), end="")
|
|
317
342
|
elif findings:
|
|
318
343
|
print("\n".join(map(str, findings)))
|
|
319
344
|
return EXIT_FINDINGS if any(f.code != "SKIPPED" for f in findings) else 0
|
|
@@ -325,10 +350,34 @@ def entry() -> NoReturn:
|
|
|
325
350
|
A shell loop stops on Ctrl-C only when the command was killed by the signal; exit code 130 alone
|
|
326
351
|
does not stop it. ``main`` itself returns 130, for callers that run it in-process.
|
|
327
352
|
"""
|
|
328
|
-
|
|
353
|
+
# A closed fd 2 makes sys.stderr None, and print(file=None) writes to stdout: messages would land in the output.
|
|
354
|
+
if sys.stderr is None:
|
|
355
|
+
sys.stderr = Path(os.devnull).open("w", encoding="utf-8") # noqa: SIM115 - lives until exit
|
|
356
|
+
code = EXIT_CANNOT_RUN
|
|
357
|
+
try:
|
|
358
|
+
try:
|
|
359
|
+
code = main()
|
|
360
|
+
except SystemExit as done: # argparse's --help, --version and usage errors still have output to flush
|
|
361
|
+
if not isinstance(done.code, int | None):
|
|
362
|
+
raise
|
|
363
|
+
code = done.code or 0
|
|
364
|
+
if sys.stdout is not None: # None when the caller closed fd 1
|
|
365
|
+
sys.stdout.flush()
|
|
366
|
+
sys.stderr.flush() # a usage error's message is output too
|
|
367
|
+
except OSError as err: # a full disk or a closed pipe; Python itself would exit 120 or 1
|
|
368
|
+
if not isinstance(err, BrokenPipeError): # a reader that stops early, as head does, is no news
|
|
369
|
+
with contextlib.suppress(OSError):
|
|
370
|
+
print(f"codemeta-drift: cannot write the output: {err}", file=sys.stderr)
|
|
371
|
+
# Point the streams at devnull, or the interpreter's exit flush fails again and exits 120.
|
|
372
|
+
devnull = os.open(os.devnull, os.O_WRONLY)
|
|
373
|
+
for stream in (sys.stdout, sys.stderr):
|
|
374
|
+
with contextlib.suppress(OSError, ValueError, AttributeError):
|
|
375
|
+
os.dup2(devnull, stream.fileno())
|
|
376
|
+
if code != EXIT_INTERRUPTED:
|
|
377
|
+
sys.exit(EXIT_CANNOT_RUN)
|
|
329
378
|
if code == EXIT_INTERRUPTED and sys.platform != "win32":
|
|
330
|
-
|
|
331
|
-
|
|
379
|
+
with contextlib.suppress(OSError):
|
|
380
|
+
sys.stderr.flush()
|
|
332
381
|
signal.signal(signal.SIGINT, signal.SIG_DFL)
|
|
333
382
|
os.kill(os.getpid(), signal.SIGINT)
|
|
334
383
|
sys.exit(code)
|
|
@@ -4,7 +4,7 @@ import re
|
|
|
4
4
|
from collections.abc import Mapping
|
|
5
5
|
from typing import Any
|
|
6
6
|
|
|
7
|
-
from codemeta_drift.checks import TABLE, crosswalk_paths, format_name
|
|
7
|
+
from codemeta_drift.checks import TABLE, code_span, crosswalk_paths, format_name
|
|
8
8
|
from codemeta_drift.export import FORMATS, NO_PROPERTY, PEOPLE, TERMS, classify, crosswalk_cells, derive
|
|
9
9
|
from codemeta_drift.hub import validate_mapping
|
|
10
10
|
|
|
@@ -151,7 +151,7 @@ def markdown(mapping: dict[str, Any], files: Mapping[str, str] | None = None) ->
|
|
|
151
151
|
+ (owns if own else "")
|
|
152
152
|
+ "This page shows the pinned tag; the "
|
|
153
153
|
"[web page](https://simonvanlierde.com/codemeta-drift/) also checks CodeMeta's main branch "
|
|
154
|
-
"each week."
|
|
154
|
+
"against the newest tag each week."
|
|
155
155
|
),
|
|
156
156
|
"",
|
|
157
157
|
"| Mark | Status | Meaning |",
|
|
@@ -178,7 +178,7 @@ def markdown(mapping: dict[str, Any], files: Mapping[str, str] | None = None) ->
|
|
|
178
178
|
continue
|
|
179
179
|
mark = STATUSES[cell["status"]][0]
|
|
180
180
|
# GitHub ends a table cell at a bare |, even inside a code span.
|
|
181
|
-
path = f"
|
|
181
|
+
path = f" {code_span(cell['path']).replace('|', '\\|')}" if cell["path"] else ""
|
|
182
182
|
link = f"[{mark}](#{anchor(fmt)})" if cell["reason"] else mark
|
|
183
183
|
marks.append(link + path)
|
|
184
184
|
lines.append(f"| `{term}` | " + " | ".join(marks) + " |")
|
|
@@ -189,8 +189,12 @@ def markdown(mapping: dict[str, Any], files: Mapping[str, str] | None = None) ->
|
|
|
189
189
|
if cell["format"] != fmt or not cell["reason"]:
|
|
190
190
|
continue
|
|
191
191
|
# Stripped: DataCite's name cell is "title ", and a code span can't end in a space.
|
|
192
|
-
was =
|
|
193
|
-
|
|
192
|
+
was = (
|
|
193
|
+
f"crosswalk cell {code_span(cell['cell'].strip())}"
|
|
194
|
+
if (cell["cell"] or "").strip()
|
|
195
|
+
else "no crosswalk cell"
|
|
196
|
+
)
|
|
197
|
+
now = code_span(cell["path"]) if cell["path"] else "no path"
|
|
194
198
|
reason = cell["reason"][0].upper() + cell["reason"][1:].rstrip(".")
|
|
195
199
|
# A bare URL in a reason (SPDX's git+https://host/path.git) is shown as code, not a link.
|
|
196
200
|
# It starts after a space or "(" and never ends in a full stop; <autolinks> and `code` are left alone.
|
|
@@ -36,6 +36,13 @@
|
|
|
36
36
|
"path": "identifier",
|
|
37
37
|
"reason": "CodeMeta has no SWHID term; a SWHID sits in identifier, beside the DOI, as a swh:1: string or a PropertyValue (propertyID SWHID) whose value is one"
|
|
38
38
|
},
|
|
39
|
+
{
|
|
40
|
+
"format": "codemeta",
|
|
41
|
+
"term": "version",
|
|
42
|
+
"path": "version | softwareVersion",
|
|
43
|
+
"reason": "CodeMeta's own term is version, but schema:softwareVersion is a CodeMeta term too; a file that holds only softwareVersion still has a version",
|
|
44
|
+
"comment": "Write version."
|
|
45
|
+
},
|
|
39
46
|
{
|
|
40
47
|
"format": "zenodo",
|
|
41
48
|
"term": "author.givenName",
|
|
@@ -36,6 +36,13 @@
|
|
|
36
36
|
"path": "identifier",
|
|
37
37
|
"reason": "CodeMeta has no SWHID term; a SWHID sits in identifier, beside the DOI, as a swh:1: string or a PropertyValue (propertyID SWHID) whose value is one"
|
|
38
38
|
},
|
|
39
|
+
{
|
|
40
|
+
"format": "codemeta",
|
|
41
|
+
"term": "version",
|
|
42
|
+
"path": "version | softwareVersion",
|
|
43
|
+
"reason": "CodeMeta's own term is version, but schema:softwareVersion is a CodeMeta term too; a file that holds only softwareVersion still has a version",
|
|
44
|
+
"comment": "Write version."
|
|
45
|
+
},
|
|
39
46
|
{
|
|
40
47
|
"format": "zenodo",
|
|
41
48
|
"term": "author.givenName",
|
|
@@ -11,11 +11,15 @@ import re
|
|
|
11
11
|
from collections import Counter
|
|
12
12
|
from collections.abc import Mapping
|
|
13
13
|
from dataclasses import dataclass
|
|
14
|
-
from
|
|
14
|
+
from pathlib import Path
|
|
15
15
|
from typing import Any
|
|
16
16
|
|
|
17
17
|
from codemeta_drift.checks import Finding, context_terms, csv_rows, table_rows
|
|
18
18
|
|
|
19
|
+
PACKAGE = Path(__file__).parent
|
|
20
|
+
"""The installed package directory, which holds the schema and curated files: a plain path, cheaper than
|
|
21
|
+
importlib.resources, which this wheel-only package does not need."""
|
|
22
|
+
|
|
19
23
|
SCHEMA_VERSION = "1.7"
|
|
20
24
|
|
|
21
25
|
TERMS = {
|
|
@@ -108,9 +112,7 @@ FORMATS = {
|
|
|
108
112
|
}
|
|
109
113
|
|
|
110
114
|
PATH = re.compile(
|
|
111
|
-
json.loads(
|
|
112
|
-
"properties"
|
|
113
|
-
]["path"]["pattern"]
|
|
115
|
+
json.loads((PACKAGE / "mapping.schema.json").read_text("utf-8"))["$defs"]["row"]["properties"]["path"]["pattern"]
|
|
114
116
|
)
|
|
115
117
|
|
|
116
118
|
# Splits a path into its single-chain pieces, at both `` | `` and `` + ``.
|
|
@@ -153,9 +155,9 @@ def identity(term: str) -> str:
|
|
|
153
155
|
|
|
154
156
|
|
|
155
157
|
def curated_tags() -> list[str]:
|
|
156
|
-
"""CodeMeta tags with a curated-<tag>.json in this package."""
|
|
157
|
-
|
|
158
|
-
return sorted(
|
|
158
|
+
"""CodeMeta tags with a curated-<tag>.json in this package, oldest first by version number."""
|
|
159
|
+
found = (re.fullmatch(r"curated-(\d+(?:\.\d+)*)\.json", p.name) for p in PACKAGE.iterdir())
|
|
160
|
+
return sorted((m[1] for m in found if m), key=tag_key)
|
|
159
161
|
|
|
160
162
|
|
|
161
163
|
def tag_key(tag: str) -> tuple[int, ...]:
|
|
@@ -170,14 +172,14 @@ def formats(tag: str) -> dict[str, Spoke]:
|
|
|
170
172
|
|
|
171
173
|
def latest_tag() -> str:
|
|
172
174
|
"""The newest CodeMeta tag with a curated file, by version number."""
|
|
173
|
-
return
|
|
175
|
+
return curated_tags()[-1]
|
|
174
176
|
|
|
175
177
|
|
|
176
178
|
def read_curated(tag: str) -> list[dict[str, Any]]:
|
|
177
179
|
"""The curated rows for a CodeMeta tag. Raises KeyError for a tag with no file."""
|
|
178
180
|
if tag not in curated_tags():
|
|
179
181
|
raise KeyError(tag)
|
|
180
|
-
return json.loads(
|
|
182
|
+
return json.loads((PACKAGE / f"curated-{tag}.json").read_text("utf-8"))["rows"]
|
|
181
183
|
|
|
182
184
|
|
|
183
185
|
def build_rows(
|
|
@@ -400,6 +402,8 @@ def derive(spoke: Spoke, term: str, cell: str, made: Mapping[str, str | None]) -
|
|
|
400
402
|
|
|
401
403
|
def generator() -> dict[str, str]:
|
|
402
404
|
"""This tool's name and installed version, for the export header."""
|
|
405
|
+
from importlib import metadata # noqa: PLC0415 - about 10 ms; only reports that name the version need it
|
|
406
|
+
|
|
403
407
|
return {"name": "codemeta-drift", "version": metadata.version("codemeta-drift")}
|
|
404
408
|
|
|
405
409
|
|
|
@@ -490,6 +490,26 @@
|
|
|
490
490
|
"https://example.org"
|
|
491
491
|
]
|
|
492
492
|
},
|
|
493
|
+
{
|
|
494
|
+
"name": "alternatives: the codemeta version row reads version",
|
|
495
|
+
"path": "version | softwareVersion",
|
|
496
|
+
"document": {
|
|
497
|
+
"version": "1.2.0"
|
|
498
|
+
},
|
|
499
|
+
"expected": [
|
|
500
|
+
"1.2.0"
|
|
501
|
+
]
|
|
502
|
+
},
|
|
503
|
+
{
|
|
504
|
+
"name": "alternatives: the codemeta version row falls back to softwareVersion",
|
|
505
|
+
"path": "version | softwareVersion",
|
|
506
|
+
"document": {
|
|
507
|
+
"softwareVersion": "1.2.0"
|
|
508
|
+
},
|
|
509
|
+
"expected": [
|
|
510
|
+
"1.2.0"
|
|
511
|
+
]
|
|
512
|
+
},
|
|
493
513
|
{
|
|
494
514
|
"name": "alternatives with @ keys",
|
|
495
515
|
"path": "Authors@R | Maintainer",
|
|
@@ -8,14 +8,17 @@ import re
|
|
|
8
8
|
import subprocess
|
|
9
9
|
import time
|
|
10
10
|
from collections.abc import Callable
|
|
11
|
+
from http.client import HTTPMessage
|
|
11
12
|
from pathlib import Path
|
|
12
|
-
from typing import Any
|
|
13
|
+
from typing import IO, Any
|
|
13
14
|
from urllib.error import HTTPError
|
|
14
15
|
from urllib.parse import quote
|
|
15
|
-
from urllib.request import
|
|
16
|
+
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|
16
17
|
|
|
18
|
+
from codemeta_drift.checks import code_span
|
|
19
|
+
from codemeta_drift.conformance import SCHEMA_FILES
|
|
17
20
|
from codemeta_drift.export import curated_tags, latest_tag
|
|
18
|
-
from codemeta_drift.watcher import issue_plans, schema_changes
|
|
21
|
+
from codemeta_drift.watcher import issue_plans, pin_tag, schema_changes
|
|
19
22
|
|
|
20
23
|
API = "https://api.github.com/repos/"
|
|
21
24
|
SCHEMA_URLS = {
|
|
@@ -25,27 +28,53 @@ SCHEMA_URLS = {
|
|
|
25
28
|
}
|
|
26
29
|
|
|
27
30
|
|
|
31
|
+
class HTTPSOnlyRedirects(HTTPRedirectHandler):
|
|
32
|
+
"""Follow a redirect only to HTTPS, refusing before the plain request goes out."""
|
|
33
|
+
|
|
34
|
+
def redirect_request(
|
|
35
|
+
self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage, newurl: str
|
|
36
|
+
) -> Request | None:
|
|
37
|
+
"""Refuse a non-HTTPS target, else redirect as urllib does."""
|
|
38
|
+
if not newurl.startswith("https://"):
|
|
39
|
+
error = "schema and API sources must use HTTPS, also after a redirect"
|
|
40
|
+
raise ValueError(error)
|
|
41
|
+
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
urlopen = build_opener(HTTPSOnlyRedirects()).open
|
|
45
|
+
|
|
46
|
+
|
|
28
47
|
def fetch_json(url: str) -> Any: # noqa: ANN401
|
|
29
48
|
"""Read a public HTTPS document with a timeout; never attach credentials."""
|
|
30
49
|
if not url.startswith("https://"):
|
|
31
50
|
msg = "schema and API sources must use HTTPS"
|
|
32
51
|
raise ValueError(msg)
|
|
33
|
-
with urlopen(url, timeout=30) as response:
|
|
52
|
+
with urlopen(url, timeout=30) as response:
|
|
34
53
|
return json.load(response)
|
|
35
54
|
|
|
36
55
|
|
|
37
56
|
def stale_pin_hashes(source: str, tag: str, fetch: Callable[[str], Any]) -> list[dict[str, str]]:
|
|
38
|
-
"""Draft one citesync issue per `sha256 <hex> <local> <path>` line that
|
|
57
|
+
"""Draft one citesync issue per `sha256 <hex> <local> <path>` line that is malformed, stale or missing at tag."""
|
|
39
58
|
plans = []
|
|
40
59
|
for line in source.splitlines():
|
|
41
60
|
if not line.startswith("sha256 "):
|
|
42
61
|
continue
|
|
43
62
|
if len(fields := line.split()) != 4:
|
|
44
|
-
|
|
45
|
-
|
|
63
|
+
# A draft, not an exception: one bad line must not stop the rest of the weekly poll.
|
|
64
|
+
plans.append(
|
|
65
|
+
{
|
|
66
|
+
"repo": "simonvanlierde/citesync",
|
|
67
|
+
"title": f"Malformed MAPPING_SOURCE line in citesync: {' '.join(fields)}",
|
|
68
|
+
"body": f"{code_span(line)} is not `sha256 <hex> <local> <path>`, so its pin was not checked. "
|
|
69
|
+
"Fix the line.",
|
|
70
|
+
}
|
|
71
|
+
)
|
|
72
|
+
continue
|
|
46
73
|
_, digest, local, path = fields
|
|
47
74
|
try:
|
|
48
|
-
published = fetch(
|
|
75
|
+
published = fetch(
|
|
76
|
+
API + f"simonvanlierde/codemeta-drift/contents/{quote(path, safe='/')}?ref={quote(tag, safe='')}"
|
|
77
|
+
)
|
|
49
78
|
except HTTPError as err:
|
|
50
79
|
if err.code != 404:
|
|
51
80
|
raise
|
|
@@ -54,8 +83,8 @@ def stale_pin_hashes(source: str, tag: str, fetch: Callable[[str], Any]) -> list
|
|
|
54
83
|
{
|
|
55
84
|
"repo": "simonvanlierde/citesync",
|
|
56
85
|
"title": f"Pinned {local} is not in codemeta-drift {tag}",
|
|
57
|
-
"body": f"MAPPING_SOURCE pins
|
|
58
|
-
"file. Pin a release that ships it.",
|
|
86
|
+
"body": f"MAPPING_SOURCE pins {code_span(local)} from {code_span(path)}, but codemeta-drift {tag} "
|
|
87
|
+
"has no such file. Pin a release that ships it.",
|
|
59
88
|
}
|
|
60
89
|
)
|
|
61
90
|
continue
|
|
@@ -65,8 +94,8 @@ def stale_pin_hashes(source: str, tag: str, fetch: Callable[[str], Any]) -> list
|
|
|
65
94
|
{
|
|
66
95
|
"repo": "simonvanlierde/citesync",
|
|
67
96
|
"title": f"Update mapping pin hash for {local} at {tag}",
|
|
68
|
-
"body": f"The sha256 of
|
|
69
|
-
f"{tag} hashes to
|
|
97
|
+
"body": f"The sha256 of {code_span(local)} in MAPPING_SOURCE is {code_span(digest)}, but "
|
|
98
|
+
f"{code_span(path)} at {tag} hashes to {code_span(current)}. Re-vendor the file and fix that line.",
|
|
70
99
|
}
|
|
71
100
|
)
|
|
72
101
|
return plans
|
|
@@ -86,18 +115,15 @@ def poll(
|
|
|
86
115
|
latest = fetch(API + "simonvanlierde/codemeta-drift/releases/latest")["tag_name"]
|
|
87
116
|
pin = fetch(API + "simonvanlierde/citesync/contents/src/citesync/MAPPING_SOURCE")
|
|
88
117
|
# The contents endpoint returns base64 so every source still uses the same JSON fetch contract.
|
|
89
|
-
source = base64.b64decode(pin["content"]
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
raise ValueError(msg)
|
|
94
|
-
plans = issue_plans(schema_changes(mapping["rows"], before, after), pin_tags[0], latest, set())
|
|
95
|
-
plans += stale_pin_hashes(source, pin_tags[0], fetch)
|
|
118
|
+
source = base64.b64decode(pin["content"]).decode("utf-8")
|
|
119
|
+
pinned = pin_tag(source)
|
|
120
|
+
plans = issue_plans(schema_changes(mapping["rows"], before, after), pinned, latest, set())
|
|
121
|
+
plans += stale_pin_hashes(source, pinned, fetch)
|
|
96
122
|
# Zenodo has no current public JSON Schema: source changes need a fresh manual path review.
|
|
97
|
-
|
|
98
|
-
for path, digest in sorted(
|
|
123
|
+
zenodo_source = before["zenodo"]["x-source"]
|
|
124
|
+
for path, digest in sorted(zenodo_source["files"].items()):
|
|
99
125
|
try:
|
|
100
|
-
current_sha = fetch(API +
|
|
126
|
+
current_sha = fetch(API + zenodo_source["repo"] + "/contents/" + path)["sha"]
|
|
101
127
|
except HTTPError as err:
|
|
102
128
|
if err.code != 404:
|
|
103
129
|
raise
|
|
@@ -107,7 +133,7 @@ def poll(
|
|
|
107
133
|
{
|
|
108
134
|
"repo": "simonvanlierde/codemeta-drift",
|
|
109
135
|
"title": f"Review Zenodo importer {path} {current_sha}",
|
|
110
|
-
"body": f"
|
|
136
|
+
"body": f"{code_span(path)} changed from blob {code_span(digest)} to {code_span(current_sha)}. "
|
|
111
137
|
"Review the Zenodo structural subset before refreshing its source hashes. "
|
|
112
138
|
"A source change does not automatically change the mapping.",
|
|
113
139
|
}
|
|
@@ -145,7 +171,6 @@ def main() -> None:
|
|
|
145
171
|
parser.add_argument("--out", type=Path, required=True, help="JSON draft artifact")
|
|
146
172
|
parser.add_argument("--publish", action="store_true", help="open missing issues using gh's credentials")
|
|
147
173
|
args = parser.parse_args()
|
|
148
|
-
from codemeta_drift.conformance import SCHEMA_FILES # noqa: PLC0415 - CLI snapshot loading
|
|
149
174
|
|
|
150
175
|
mapping = json.loads((args.root / f"examples/mapping-{latest_tag()}.json").read_text("utf-8"))
|
|
151
176
|
before = {
|
|
@@ -155,13 +180,15 @@ def main() -> None:
|
|
|
155
180
|
plans = poll(mapping, before)
|
|
156
181
|
args.out.write_text(json.dumps(plans, indent=2) + "\n", encoding="utf-8")
|
|
157
182
|
if args.publish:
|
|
158
|
-
|
|
183
|
+
# Only stdout is captured: gh's reason for a refusal must reach the job log, which
|
|
184
|
+
# CalledProcessError does not print.
|
|
185
|
+
subprocess.run(["gh", "api", "rate_limit"], check=True, stdout=subprocess.DEVNULL, timeout=30) # noqa: S607
|
|
159
186
|
|
|
160
187
|
def titles(repo: str) -> set[str]:
|
|
161
188
|
output = subprocess.run( # noqa: S603 - fixed gh operation, no shell
|
|
162
189
|
["gh", "api", "--paginate", "--slurp", f"repos/{repo}/issues?state=all&per_page=100"], # noqa: S607
|
|
163
190
|
check=True,
|
|
164
|
-
|
|
191
|
+
stdout=subprocess.PIPE,
|
|
165
192
|
text=True,
|
|
166
193
|
timeout=30,
|
|
167
194
|
).stdout
|
|
@@ -5,6 +5,7 @@ import json
|
|
|
5
5
|
import re
|
|
6
6
|
from typing import Any
|
|
7
7
|
|
|
8
|
+
from codemeta_drift.checks import code_span
|
|
8
9
|
from codemeta_drift.conformance import array_items, branches, resolve
|
|
9
10
|
from codemeta_drift.paths import PIECES, parse
|
|
10
11
|
|
|
@@ -81,6 +82,15 @@ def schema_changes(rows: list[dict[str, Any]], before: dict[str, Any], after: di
|
|
|
81
82
|
return changes
|
|
82
83
|
|
|
83
84
|
|
|
85
|
+
def pin_tag(source: str) -> str:
|
|
86
|
+
"""The release tag on citesync's one `tag <x>` MAPPING_SOURCE line."""
|
|
87
|
+
tags = [parts[1] for line in source.splitlines() if len(parts := line.split()) > 1 and parts[0] == "tag"]
|
|
88
|
+
if len(tags) != 1:
|
|
89
|
+
msg = "MAPPING_SOURCE must contain exactly one tag line"
|
|
90
|
+
raise ValueError(msg)
|
|
91
|
+
return tags[0]
|
|
92
|
+
|
|
93
|
+
|
|
84
94
|
def release_version(tag: str) -> tuple[int, int, int]:
|
|
85
95
|
"""Numeric stable release version; reject arbitrary refs rather than guessing their order."""
|
|
86
96
|
if not re.fullmatch(r"v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)", tag):
|
|
@@ -106,7 +116,7 @@ def issue_plans(
|
|
|
106
116
|
"repo": "simonvanlierde/codemeta-drift",
|
|
107
117
|
"title": f"Review schema changes {digest}",
|
|
108
118
|
"body": "These schema fields need review:\n\n"
|
|
109
|
-
+ "\n".join(f"- {c['format']}: {c['kind']}
|
|
119
|
+
+ "\n".join(f"- {c['format']}: {c['kind']} {code_span(c['path'])} ({c['detail']})" for c in changes),
|
|
110
120
|
}
|
|
111
121
|
)
|
|
112
122
|
if release_version(pin_tag) < release_version(latest_tag):
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|