sourceledger 0.6.0__tar.gz → 0.7.0__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.
- {sourceledger-0.6.0 → sourceledger-0.7.0}/PKG-INFO +1 -1
- {sourceledger-0.6.0 → sourceledger-0.7.0}/pyproject.toml +1 -1
- {sourceledger-0.6.0 → sourceledger-0.7.0}/pyproject.toml.orig +1 -1
- {sourceledger-0.6.0 → sourceledger-0.7.0}/src/sourceledger/builder.py +40 -11
- {sourceledger-0.6.0 → sourceledger-0.7.0}/src/sourceledger/cli.py +157 -41
- {sourceledger-0.6.0 → sourceledger-0.7.0}/src/sourceledger/fetcher.py +18 -5
- {sourceledger-0.6.0 → sourceledger-0.7.0}/src/sourceledger/ledger.py +127 -27
- {sourceledger-0.6.0 → sourceledger-0.7.0}/src/sourceledger/releaser.py +151 -17
- {sourceledger-0.6.0 → sourceledger-0.7.0}/src/sourceledger/report.py +64 -19
- {sourceledger-0.6.0 → sourceledger-0.7.0}/LICENSE +0 -0
- {sourceledger-0.6.0 → sourceledger-0.7.0}/README.md +0 -0
- {sourceledger-0.6.0 → sourceledger-0.7.0}/src/sourceledger/__init__.py +0 -0
- {sourceledger-0.6.0 → sourceledger-0.7.0}/src/sourceledger/comparison.py +0 -0
- {sourceledger-0.6.0 → sourceledger-0.7.0}/src/sourceledger/manifest.py +0 -0
- {sourceledger-0.6.0 → sourceledger-0.7.0}/src/sourceledger/py.typed +0 -0
- {sourceledger-0.6.0 → sourceledger-0.7.0}/src/sourceledger/sources.schema.json +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sourceledger
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.0
|
|
4
4
|
Summary: Fetch or record a dataset's public files with provenance, and release it without files whose terms forbid it
|
|
5
5
|
Keywords: provenance,data pipeline,reproducibility,open data,research software,FAIR
|
|
6
6
|
Author: Simon van Lierde
|
|
@@ -335,6 +335,7 @@ def build(
|
|
|
335
335
|
only: Collection[str] | None = None,
|
|
336
336
|
output_format: str = "csv",
|
|
337
337
|
name: str | None = None,
|
|
338
|
+
build_revision: str | None = None,
|
|
338
339
|
) -> list[Path]:
|
|
339
340
|
"""Write implemented sources to `processed`: unchanged files, or tables stamped with their fetch records.
|
|
340
341
|
|
|
@@ -345,21 +346,43 @@ def build(
|
|
|
345
346
|
Then writes `processed/datapackage.json`, a Frictionless Data Package (v2) describing every
|
|
346
347
|
output: its columns, size and SHA-256, its source URL and licence, and its fetch record.
|
|
347
348
|
The package is called `name`; without one, the `[project]` name in ./pyproject.toml, or else
|
|
348
|
-
the current folder's name, either made lower case.
|
|
349
|
-
|
|
349
|
+
the current folder's name, either made lower case. `build_revision`, if supplied, records
|
|
350
|
+
the code revision in each rebuilt resource. Identical inputs and revision give the same files.
|
|
350
351
|
|
|
351
352
|
`only` restricts the build to those source ids. The package keeps each other source's
|
|
352
|
-
entry as the last build wrote it. Raises ValueError for an
|
|
353
|
-
or a file output named `datapackage.json`, which
|
|
353
|
+
entry as the last build wrote it. Raises ValueError for an unknown source id, a build revision
|
|
354
|
+
that is empty or cannot be encoded as UTF-8, or a file output named `datapackage.json`, which
|
|
355
|
+
is reserved for the descriptor.
|
|
354
356
|
"""
|
|
355
357
|
return [
|
|
356
358
|
out
|
|
357
359
|
for out, _count in build_sources(
|
|
358
|
-
sources,
|
|
360
|
+
sources,
|
|
361
|
+
raw=raw,
|
|
362
|
+
processed=processed,
|
|
363
|
+
parse=parse,
|
|
364
|
+
only=only,
|
|
365
|
+
output_format=output_format,
|
|
366
|
+
name=name,
|
|
367
|
+
build_revision=build_revision,
|
|
359
368
|
)
|
|
360
369
|
]
|
|
361
370
|
|
|
362
371
|
|
|
372
|
+
def check_build_revision(build_revision: str | None) -> None:
|
|
373
|
+
"""Refuse revision text that the UTF-8 descriptor cannot store."""
|
|
374
|
+
if build_revision is None:
|
|
375
|
+
return
|
|
376
|
+
if not isinstance(build_revision, str) or not build_revision.strip():
|
|
377
|
+
msg = "build_revision must be nonempty text"
|
|
378
|
+
raise ValueError(msg)
|
|
379
|
+
try:
|
|
380
|
+
build_revision.encode()
|
|
381
|
+
except UnicodeEncodeError as error:
|
|
382
|
+
msg = "build_revision must be valid UTF-8 text"
|
|
383
|
+
raise ValueError(msg) from error
|
|
384
|
+
|
|
385
|
+
|
|
363
386
|
def build_sources(
|
|
364
387
|
sources: list[Source],
|
|
365
388
|
*,
|
|
@@ -369,10 +392,12 @@ def build_sources(
|
|
|
369
392
|
only: Collection[str] | None = None,
|
|
370
393
|
output_format: str = "csv",
|
|
371
394
|
name: str | None = None,
|
|
395
|
+
build_revision: str | None = None,
|
|
372
396
|
) -> list[tuple[Path, int | None]]:
|
|
373
397
|
"""Build outputs with row counts for tables, or None for unchanged file copies."""
|
|
374
398
|
_check_output_format(output_format)
|
|
375
399
|
_check_name(name)
|
|
400
|
+
check_build_revision(build_revision)
|
|
376
401
|
# Before any output is written: a broken pyproject.toml must not cost a whole build.
|
|
377
402
|
name = name or _package_name()
|
|
378
403
|
selected = {s["id"] for s in select(sources, only)}
|
|
@@ -391,7 +416,7 @@ def build_sources(
|
|
|
391
416
|
raise ValueError(msg)
|
|
392
417
|
record, fields, count = _build_one(source, raw, out, parse)
|
|
393
418
|
written.append((out, count))
|
|
394
|
-
resources.append(_resource(source, record, fields, out))
|
|
419
|
+
resources.append(_resource(source, record, fields, out, build_revision=build_revision))
|
|
395
420
|
package = {"$schema": _DATAPACKAGE_PROFILE, "name": name, "resources": resources}
|
|
396
421
|
_write_atomic(processed / DATAPACKAGE, json_bytes(package))
|
|
397
422
|
return written
|
|
@@ -542,7 +567,9 @@ def _package_name() -> str:
|
|
|
542
567
|
return re.sub(r"[^a-z0-9._-]+", "-", letters.lower()).strip("-") or "dataset"
|
|
543
568
|
|
|
544
569
|
|
|
545
|
-
def _resource(
|
|
570
|
+
def _resource(
|
|
571
|
+
source: Source, record: FetchRecord, fields: list[str], out: Path, *, build_revision: str | None = None
|
|
572
|
+
) -> dict[str, Any]:
|
|
546
573
|
"""One output as a Data Package resource: a file, or a table whose columns hold text."""
|
|
547
574
|
resource: dict[str, Any] = {
|
|
548
575
|
"name": source["id"],
|
|
@@ -565,13 +592,13 @@ def _resource(source: Source, record: FetchRecord, fields: list[str], out: Path)
|
|
|
565
592
|
if source.get("license"):
|
|
566
593
|
licence = {"name": source["license"], "path": source.get("terms_url"), "title": source.get("terms")}
|
|
567
594
|
resource["licenses"] = [{k: v for k, v in licence.items() if v}]
|
|
568
|
-
#
|
|
569
|
-
resource["sourceledger"] = _provenance(source, record)
|
|
595
|
+
# Data Package v2 allows custom properties for the fetch and build provenance.
|
|
596
|
+
resource["sourceledger"] = _provenance(source, record, build_revision=build_revision)
|
|
570
597
|
return resource
|
|
571
598
|
|
|
572
599
|
|
|
573
|
-
def _provenance(source: Source, record: FetchRecord) -> dict[str, Any]:
|
|
574
|
-
"""A resource's
|
|
600
|
+
def _provenance(source: Source, record: FetchRecord, *, build_revision: str | None = None) -> dict[str, Any]:
|
|
601
|
+
"""A resource's fetch provenance and optional build revision."""
|
|
575
602
|
stamp = {
|
|
576
603
|
"retrieved_at": record.retrieved_at,
|
|
577
604
|
"vintage": record.vintage,
|
|
@@ -583,6 +610,8 @@ def _provenance(source: Source, record: FetchRecord) -> dict[str, Any]:
|
|
|
583
610
|
stamp["recorded_at"] = record.recorded_at
|
|
584
611
|
if record.parameters:
|
|
585
612
|
stamp["parameters"] = record.parameters
|
|
613
|
+
if build_revision is not None:
|
|
614
|
+
stamp["build_revision"] = build_revision
|
|
586
615
|
return stamp
|
|
587
616
|
|
|
588
617
|
|
|
@@ -23,7 +23,7 @@ from importlib.metadata import version
|
|
|
23
23
|
from pathlib import Path
|
|
24
24
|
from typing import TYPE_CHECKING, Any, NoReturn
|
|
25
25
|
|
|
26
|
-
from sourceledger.builder import DATAPACKAGE, PROCESSED, Parser, build_sources, parse_source
|
|
26
|
+
from sourceledger.builder import DATAPACKAGE, PROCESSED, Parser, build_sources, check_build_revision, parse_source
|
|
27
27
|
from sourceledger.fetcher import USER_AGENT, fetch_sources
|
|
28
28
|
from sourceledger.ledger import (
|
|
29
29
|
FETCH_LOG,
|
|
@@ -64,6 +64,8 @@ EXIT_FAILED = 3
|
|
|
64
64
|
EXIT_INTERRUPTED = 130
|
|
65
65
|
# Bumped when a field of the --json reports changes meaning or goes away.
|
|
66
66
|
JSON_SCHEMA_VERSION = 1
|
|
67
|
+
_JSON_FLAG = "--json"
|
|
68
|
+
_STDIN = "-" # compared as typed: `./-` is a file named -
|
|
67
69
|
|
|
68
70
|
_STAGES = {
|
|
69
71
|
"init": "write a starter sources.toml",
|
|
@@ -79,6 +81,23 @@ _STAGES = {
|
|
|
79
81
|
"release": "write and check a release folder: data, metadata, SHA256SUMS",
|
|
80
82
|
}
|
|
81
83
|
|
|
84
|
+
_EXAMPLES = {
|
|
85
|
+
"init": "{prog} init",
|
|
86
|
+
"fetch": "{prog} fetch --only co2 --json",
|
|
87
|
+
"record": (
|
|
88
|
+
"{prog} record co2 ~/Downloads/co2.csv --retrieved-at 2026-11-05T09:30:00Z\n"
|
|
89
|
+
" {prog} record co2 - < ~/Downloads/co2.csv"
|
|
90
|
+
),
|
|
91
|
+
"build": "{prog} build --dry-run",
|
|
92
|
+
"validate": "{prog} validate --json",
|
|
93
|
+
"status": "{prog} status --json",
|
|
94
|
+
"attribution": "{prog} attribution > ATTRIBUTION.md",
|
|
95
|
+
"revisions": "{prog} revisions before.jsonl --json",
|
|
96
|
+
"verify": "{prog} verify published/",
|
|
97
|
+
"report": "{prog} report > provenance.html",
|
|
98
|
+
"release": "{prog} release out/ --dry-run",
|
|
99
|
+
}
|
|
100
|
+
|
|
82
101
|
_EPILOG = """\
|
|
83
102
|
a first run:
|
|
84
103
|
{prog} init write a starter sources.toml
|
|
@@ -97,12 +116,18 @@ class _UsageError(Exception):
|
|
|
97
116
|
"""An argument the parser could not check, such as an id sources.toml does not have."""
|
|
98
117
|
|
|
99
118
|
|
|
119
|
+
class _ParseError(Exception):
|
|
120
|
+
"""A usage error the parser found; `main` prints it as text, or as the failure envelope under --json."""
|
|
121
|
+
|
|
122
|
+
def __init__(self, message: str, parser: argparse.ArgumentParser) -> None:
|
|
123
|
+
super().__init__(message)
|
|
124
|
+
self.parser = parser
|
|
125
|
+
|
|
126
|
+
|
|
100
127
|
class _ArgumentParser(argparse.ArgumentParser):
|
|
101
128
|
def error(self, message: str) -> NoReturn:
|
|
102
|
-
"""
|
|
103
|
-
self
|
|
104
|
-
_error(message, f"run `{self.prog} --help` for its options")
|
|
105
|
-
sys.exit(EXIT_USAGE)
|
|
129
|
+
"""Hand the usage error to `main`, which exits with code 2."""
|
|
130
|
+
raise _ParseError(message, self)
|
|
106
131
|
|
|
107
132
|
|
|
108
133
|
def _error(message: str, help_: str | None) -> None:
|
|
@@ -121,6 +146,7 @@ class _Run:
|
|
|
121
146
|
parse: Parser
|
|
122
147
|
prog: str
|
|
123
148
|
user_agent: str
|
|
149
|
+
build_revision: str | None
|
|
124
150
|
result: dict[str, object] = dataclasses.field(default_factory=dict)
|
|
125
151
|
|
|
126
152
|
def say(self, line: str) -> None:
|
|
@@ -154,7 +180,8 @@ def _parser(prog: str, manifest: Path) -> argparse.ArgumentParser:
|
|
|
154
180
|
"--manifest", type=Path, default=manifest, metavar="PATH", help="the manifest to read (default: %(default)s)"
|
|
155
181
|
)
|
|
156
182
|
json_option = _ArgumentParser(add_help=False)
|
|
157
|
-
json_option.add_argument(
|
|
183
|
+
json_option.add_argument(_JSON_FLAG, action="store_true", help="print one JSON object instead of text")
|
|
184
|
+
json_option.set_defaults(takes_json=True) # copied into each parser that has the option
|
|
158
185
|
only_option = _ArgumentParser(add_help=False)
|
|
159
186
|
only_option.add_argument("--only", action="append", metavar="ID", help="only this source (repeatable)")
|
|
160
187
|
dry_run_option = _ArgumentParser(add_help=False)
|
|
@@ -163,7 +190,7 @@ def _parser(prog: str, manifest: Path) -> argparse.ArgumentParser:
|
|
|
163
190
|
"init": [manifest_option],
|
|
164
191
|
"fetch": [manifest_option, only_option, dry_run_option, json_option],
|
|
165
192
|
"record": [manifest_option, dry_run_option, json_option],
|
|
166
|
-
"build": [manifest_option, only_option, dry_run_option],
|
|
193
|
+
"build": [manifest_option, only_option, dry_run_option, json_option],
|
|
167
194
|
"validate": [manifest_option, only_option, json_option],
|
|
168
195
|
"status": [manifest_option, json_option],
|
|
169
196
|
"attribution": [manifest_option],
|
|
@@ -174,12 +201,20 @@ def _parser(prog: str, manifest: Path) -> argparse.ArgumentParser:
|
|
|
174
201
|
}
|
|
175
202
|
sub = {
|
|
176
203
|
name: stages.add_parser(
|
|
177
|
-
name,
|
|
204
|
+
name,
|
|
205
|
+
help=text,
|
|
206
|
+
description=text[0].upper() + text[1:] + ".",
|
|
207
|
+
epilog=f"example:\n {_EXAMPLES[name].format(prog=prog)}",
|
|
208
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
209
|
+
parents=parents[name],
|
|
210
|
+
allow_abbrev=False,
|
|
178
211
|
)
|
|
179
212
|
for name, text in _STAGES.items()
|
|
180
213
|
}
|
|
181
214
|
sub["record"].add_argument("id", metavar="ID", help="the source in sources.toml")
|
|
182
|
-
sub["record"].add_argument(
|
|
215
|
+
sub["record"].add_argument(
|
|
216
|
+
"path", metavar="PATH", help="the file another tool downloaded, or - to read it from stdin"
|
|
217
|
+
)
|
|
183
218
|
sub["record"].add_argument("--url", help="where the file came from (default: the source's url)")
|
|
184
219
|
sub["record"].add_argument(
|
|
185
220
|
"--retrieved-at",
|
|
@@ -195,7 +230,7 @@ def _parser(prog: str, manifest: Path) -> argparse.ArgumentParser:
|
|
|
195
230
|
sub["record"].add_argument(
|
|
196
231
|
"--parameter", action="append", default=[], metavar="NAME=VALUE", help="request metadata (repeatable)"
|
|
197
232
|
)
|
|
198
|
-
sub["record"].set_defaults(check_args=
|
|
233
|
+
sub["record"].set_defaults(check_args=_check_record_args)
|
|
199
234
|
sub["revisions"].add_argument("path", type=Path, metavar="OLD_LOG", help="an earlier copy of data/fetches.jsonl")
|
|
200
235
|
sub["verify"].add_argument("path", type=Path, metavar="DIR", help="the folder of a published dataset")
|
|
201
236
|
sub["release"].add_argument("path", type=Path, nargs="?", metavar="OUT_DIR", help="the new folder to write")
|
|
@@ -210,7 +245,7 @@ def _parser(prog: str, manifest: Path) -> argparse.ArgumentParser:
|
|
|
210
245
|
)
|
|
211
246
|
sub["release"].set_defaults(check_args=_check_release_args)
|
|
212
247
|
for name, stage_parser in sub.items():
|
|
213
|
-
stage_parser.set_defaults(parser=stage_parser, run=_HANDLERS[name])
|
|
248
|
+
stage_parser.set_defaults(parser=stage_parser, run=_HANDLERS[name], stage_name=name)
|
|
214
249
|
return parser
|
|
215
250
|
|
|
216
251
|
|
|
@@ -239,8 +274,12 @@ def _check_release_args(args: argparse.Namespace) -> None:
|
|
|
239
274
|
args.parser.error("--check reads no codemeta.json; drop --codemeta")
|
|
240
275
|
|
|
241
276
|
|
|
242
|
-
def
|
|
243
|
-
"""Exit with a usage error for a --parameter
|
|
277
|
+
def _check_record_args(args: argparse.Namespace) -> None:
|
|
278
|
+
"""Exit with a usage error for `-` with no piped stdin, or a --parameter not NAME=VALUE or given twice."""
|
|
279
|
+
if args.path == _STDIN and sys.stdin is None: # started with stdin closed, as by `<&-`
|
|
280
|
+
args.parser.error("PATH is -, but there is no stdin")
|
|
281
|
+
if args.path == _STDIN and sys.stdin.isatty():
|
|
282
|
+
args.parser.error("PATH is -, but stdin is a terminal; pipe the file in")
|
|
244
283
|
if bad := [p for p in args.parameter if not (p.partition("=")[0] and p.partition("=")[1])]:
|
|
245
284
|
args.parser.error(f"--parameter takes NAME=VALUE, not {bad[0]!r}")
|
|
246
285
|
names = [p.partition("=")[0] for p in args.parameter]
|
|
@@ -255,12 +294,13 @@ def entry(
|
|
|
255
294
|
prog: str = "sourceledger",
|
|
256
295
|
user_agent: str = USER_AGENT,
|
|
257
296
|
manifest: Path = MANIFEST,
|
|
297
|
+
build_revision: str | None = None,
|
|
258
298
|
) -> NoReturn:
|
|
259
299
|
"""The `sourceledger` command: run `main` with these arguments, and exit as the shell expects.
|
|
260
300
|
|
|
261
301
|
A project's own command points its console script at a function that calls this with its
|
|
262
|
-
`parse`, `prog`, `user_agent` and `
|
|
263
|
-
`sys.argv[1:]` when None, so a test can run the command and catch its SystemExit.
|
|
302
|
+
`parse`, `prog`, `user_agent`, `manifest` and optional `build_revision`, as for `main`.
|
|
303
|
+
`argv` is the arguments, `sys.argv[1:]` when None, so a test can run the command and catch its SystemExit.
|
|
264
304
|
A shell loop stops on Ctrl-C only when the command was killed by the signal; an exit code of
|
|
265
305
|
130 alone does not stop it, so after Ctrl-C this dies of SIGINT. `main` itself returns 130.
|
|
266
306
|
A reader that closes the pipe early, such as `head`, ends the command quietly by SIGPIPE.
|
|
@@ -272,7 +312,9 @@ def entry(
|
|
|
272
312
|
for stream, newline in ((sys.stdout, {"newline": "\n"}), (sys.stderr, {})):
|
|
273
313
|
if reconfigure := getattr(stream, "reconfigure", None):
|
|
274
314
|
reconfigure(encoding="utf-8", **newline)
|
|
275
|
-
code = main(
|
|
315
|
+
code = main(
|
|
316
|
+
argv=argv, parse=parse, prog=prog, user_agent=user_agent, manifest=manifest, build_revision=build_revision
|
|
317
|
+
)
|
|
276
318
|
if code == EXIT_INTERRUPTED and sys.platform != "win32": # noqa: PLR2004
|
|
277
319
|
sys.stdout.flush()
|
|
278
320
|
sys.stderr.flush()
|
|
@@ -288,6 +330,7 @@ def main( # the entry point: parse, run one stage, report it
|
|
|
288
330
|
prog: str = "sourceledger",
|
|
289
331
|
user_agent: str = USER_AGENT,
|
|
290
332
|
manifest: Path = MANIFEST,
|
|
333
|
+
build_revision: str | None = None,
|
|
291
334
|
) -> int:
|
|
292
335
|
"""Run one stage: init, fetch, record, build, validate, status, attribution, revisions, verify, report or release.
|
|
293
336
|
|
|
@@ -295,19 +338,46 @@ def main( # the entry point: parse, run one stage, report it
|
|
|
295
338
|
this with its `parse`, its name as `prog`, and that name as `user_agent`. `manifest` is the
|
|
296
339
|
sources.toml to read, `./sources.toml` by default; a project that ships it inside its
|
|
297
340
|
package passes that path, and `--manifest PATH` overrides both.
|
|
341
|
+
`build_revision` records the project's code revision on the resources that `build` writes.
|
|
298
342
|
|
|
299
343
|
Returns the exit code the module docstring lists. A usage error exits through SystemExit
|
|
300
344
|
with code 2, as argparse does.
|
|
301
345
|
"""
|
|
302
346
|
argv = sys.argv[1:] if argv is None else argv
|
|
303
|
-
args
|
|
304
|
-
|
|
305
|
-
args
|
|
306
|
-
|
|
307
|
-
|
|
347
|
+
args = None
|
|
348
|
+
try:
|
|
349
|
+
args, extra = _parser(prog, manifest).parse_known_args(argv)
|
|
350
|
+
if extra: # reported by the stage's parser, so the usage and help name the stage
|
|
351
|
+
args.parser.error(f"unrecognized arguments: {' '.join(extra)}")
|
|
352
|
+
if check_args := getattr(args, "check_args", None):
|
|
353
|
+
check_args(args)
|
|
354
|
+
except _ParseError as error:
|
|
355
|
+
_usage_error(error, argv, args)
|
|
308
356
|
# Retries and recovered fetch logs are reported as warnings, on stderr.
|
|
309
357
|
logging.basicConfig(format=f"{prog}: %(message)s", level=logging.WARNING)
|
|
310
|
-
return _main(_Run(args, argv, parse, prog, user_agent))
|
|
358
|
+
return _main(_Run(args, argv, parse, prog, user_agent, build_revision))
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _usage_error(error: _ParseError, argv: list[str], args: argparse.Namespace | None) -> NoReturn:
|
|
362
|
+
"""Exit with code 2: the failure envelope on stdout under --json, else usage and error on stderr."""
|
|
363
|
+
parser = error.parser
|
|
364
|
+
stage = parser.get_default("stage_name")
|
|
365
|
+
help_ = f"run `{parser.prog} --help` for its options"
|
|
366
|
+
if args is None:
|
|
367
|
+
options = argv[argv.index(stage) + 1 :] if stage in argv else []
|
|
368
|
+
end_of_options = "--"
|
|
369
|
+
if end_of_options in options:
|
|
370
|
+
options = options[: options.index(end_of_options)]
|
|
371
|
+
as_json = _JSON_FLAG in options
|
|
372
|
+
else:
|
|
373
|
+
as_json = args.json
|
|
374
|
+
if parser.get_default("takes_json") and as_json:
|
|
375
|
+
errors = [{"message": str(error), "help": help_}]
|
|
376
|
+
print(json.dumps({"schema_version": JSON_SCHEMA_VERSION, "stage": stage, "errors": errors}))
|
|
377
|
+
else:
|
|
378
|
+
print(parser.format_usage(), end="", file=sys.stderr)
|
|
379
|
+
_error(str(error), help_)
|
|
380
|
+
sys.exit(EXIT_USAGE)
|
|
311
381
|
|
|
312
382
|
|
|
313
383
|
def _main(run: _Run) -> int:
|
|
@@ -319,12 +389,10 @@ def _main(run: _Run) -> int:
|
|
|
319
389
|
errors = [(str(error), f"run `{run.prog} status` to list the source ids")]
|
|
320
390
|
code = EXIT_USAGE
|
|
321
391
|
except FetchError as error:
|
|
322
|
-
errors = [(failure,
|
|
392
|
+
errors = [_fetch_failure(failure, run.prog, kept=bool(error.records)) for failure in error.failures]
|
|
323
393
|
if error.records: # say what was kept, after the last failure
|
|
324
|
-
errors[-1]
|
|
325
|
-
|
|
326
|
-
f"the other sources were fetched and logged; run `{run.prog} fetch` again to retry",
|
|
327
|
-
)
|
|
394
|
+
message, help_ = errors[-1]
|
|
395
|
+
errors[-1] = (message, "the other sources were fetched and logged" + (f"; {help_}" if help_ else ""))
|
|
328
396
|
code = EXIT_FAILED
|
|
329
397
|
# OSError: a missing file, a failed download or a held lock. ValueError: a bad manifest,
|
|
330
398
|
# a download that fails its checks, or a stale fetch. csv.Error: a source that is not CSV.
|
|
@@ -337,7 +405,10 @@ def _main(run: _Run) -> int:
|
|
|
337
405
|
# record logs the URL without its query and fragment, which can hold a signature; so does the rerun.
|
|
338
406
|
argv = [a.replace(url, without_query(url)) for a in run.argv] if url else run.argv
|
|
339
407
|
rerun = shlex.join([run.prog, *argv])
|
|
340
|
-
|
|
408
|
+
help_ = f"what finished before is kept; run `{rerun}` to finish"
|
|
409
|
+
if getattr(run.args, "path", None) == _STDIN: # record read stdin, and its bytes are gone
|
|
410
|
+
help_ = "check the recorded file and fetch log, then pipe the file in again if needed"
|
|
411
|
+
errors = [(f"{run.args.stage} was interrupted", help_)]
|
|
341
412
|
code = EXIT_INTERRUPTED
|
|
342
413
|
except Exception as error: # noqa: BLE001 # such as a project's parser failing: one line, not a traceback
|
|
343
414
|
errors = [(f"{type(error).__name__}: {error}", None)]
|
|
@@ -347,11 +418,26 @@ def _main(run: _Run) -> int:
|
|
|
347
418
|
document["errors"] = [{"message": message, "help": help_} for message, help_ in errors]
|
|
348
419
|
print(json.dumps(document))
|
|
349
420
|
else:
|
|
421
|
+
sys.stdout.flush() # keep completed results ahead of errors when both streams share a file
|
|
350
422
|
for message, help_ in errors:
|
|
351
423
|
_error(message, help_)
|
|
352
424
|
return code
|
|
353
425
|
|
|
354
426
|
|
|
427
|
+
_DOWNLOAD_FAILURE = ": fetching "
|
|
428
|
+
_UNCHANGED = "unchanged"
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _fetch_failure(failure: str, prog: str, *, kept: bool) -> tuple[str, str | None]:
|
|
432
|
+
"""Explain a pin failure separately from a download that can be retried."""
|
|
433
|
+
if pin := re.fullmatch(r"(.*): downloaded bytes hash to ([0-9a-f]{64}), not the sha256 in sources.toml", failure):
|
|
434
|
+
return (
|
|
435
|
+
f"{pin[1]}: downloaded bytes changed: hash to {pin[2]}, not the sha256 in sources.toml",
|
|
436
|
+
f'review the changed bytes before updating sources.toml:\nsha256 = "{pin[2]}"',
|
|
437
|
+
)
|
|
438
|
+
return failure, f"run `{prog} fetch` again to retry" if kept and _DOWNLOAD_FAILURE in failure else None
|
|
439
|
+
|
|
440
|
+
|
|
355
441
|
# What to do about the file or folder a stage will not overwrite.
|
|
356
442
|
_EXISTS_HELP = {
|
|
357
443
|
"init": "edit it, or pass --manifest PATH to write one elsewhere",
|
|
@@ -383,7 +469,7 @@ def _help(error: Exception, run: _Run) -> str | None:
|
|
|
383
469
|
missing = Path(error.filename) if isinstance(error, FileNotFoundError) and error.filename else None
|
|
384
470
|
# The stage's own path first: one named like the manifest is still the path the user passed.
|
|
385
471
|
path = getattr(run.args, "check", None) or getattr(run.args, "path", None)
|
|
386
|
-
if missing and path and missing in (path, path
|
|
472
|
+
if missing and path and missing in (Path(path), Path(path, DATAPACKAGE)): # record keeps PATH as typed
|
|
387
473
|
return _MISSING_PATH_HELP[run.args.stage]
|
|
388
474
|
if missing == run.args.manifest:
|
|
389
475
|
return f"run `{run.prog} init` to write one, or pass --manifest PATH"
|
|
@@ -428,21 +514,26 @@ def _json_record(record: FetchRecord, before: dict[str, dict[str, Any]]) -> dict
|
|
|
428
514
|
|
|
429
515
|
def _marker(record: FetchRecord, before: dict[str, dict[str, Any]]) -> str:
|
|
430
516
|
"""`new` bytes, the same bytes `relogged` another way, or `unchanged`."""
|
|
431
|
-
return "new" if _new(record, before) else "relogged" if _relogged(record, before) else
|
|
517
|
+
return "new" if _new(record, before) else "relogged" if _relogged(record, before) else _UNCHANGED
|
|
432
518
|
|
|
433
519
|
|
|
434
|
-
def _fetch_line(record: FetchRecord, before: dict[str, dict[str, Any]]) -> str:
|
|
520
|
+
def _fetch_line(record: FetchRecord, before: dict[str, dict[str, Any]], restored: set[str]) -> str:
|
|
435
521
|
"""One line per source, with its `_marker`."""
|
|
436
522
|
marker = _marker(record, before)
|
|
523
|
+
if marker == _UNCHANGED and record.source_id in restored:
|
|
524
|
+
marker = "fetched"
|
|
437
525
|
return (
|
|
438
526
|
f"{record.source_id} {marker:<9} {record.bytes:>9,} B {record.sha256[:12]} {record.vintage} {record.url}"
|
|
439
527
|
)
|
|
440
528
|
|
|
441
529
|
|
|
442
|
-
def _report_records(
|
|
530
|
+
def _report_records(
|
|
531
|
+
run: _Run, records: list[FetchRecord], before: dict[str, dict[str, Any]], restored: set[str] | None = None
|
|
532
|
+
) -> None:
|
|
443
533
|
run.result["records"] = [_json_record(r, before) for r in records]
|
|
534
|
+
restored = restored or set()
|
|
444
535
|
for record in records:
|
|
445
|
-
run.say(_fetch_line(record, before))
|
|
536
|
+
run.say(_fetch_line(record, before, restored))
|
|
446
537
|
if relogged := [r.source_id for r in records if _relogged(r, before)]:
|
|
447
538
|
run.say(f"run build: the outputs of {', '.join(relogged)} name the earlier log line")
|
|
448
539
|
|
|
@@ -485,12 +576,19 @@ def _fetch_stage(run: _Run) -> list[str]:
|
|
|
485
576
|
return []
|
|
486
577
|
before: dict[str, dict[str, Any]] = {}
|
|
487
578
|
done: list[FetchRecord] = []
|
|
579
|
+
restored: set[str] = set()
|
|
488
580
|
try:
|
|
489
581
|
fetch_sources(
|
|
490
|
-
sources,
|
|
582
|
+
sources,
|
|
583
|
+
user_agent=run.user_agent,
|
|
584
|
+
only=run.args.only,
|
|
585
|
+
before=before,
|
|
586
|
+
progress=_progress(run),
|
|
587
|
+
done=done,
|
|
588
|
+
restored=restored,
|
|
491
589
|
)
|
|
492
590
|
finally: # on a failure or Ctrl-C too: the sources that did fetch
|
|
493
|
-
_report_records(run, done, before)
|
|
591
|
+
_report_records(run, done, before, restored)
|
|
494
592
|
return []
|
|
495
593
|
|
|
496
594
|
|
|
@@ -498,9 +596,11 @@ def _record_stage(run: _Run) -> list[str]:
|
|
|
498
596
|
args = run.args
|
|
499
597
|
(source,) = select(_sources(run, [args.id]), [args.id])
|
|
500
598
|
before: dict[str, dict[str, Any]] = {}
|
|
599
|
+
# Left open for the process (closefd=False); a BufferedReader has the read1 that copying uses.
|
|
600
|
+
src = os.fdopen(sys.stdin.fileno(), "rb", closefd=False) if args.path == _STDIN else Path(args.path)
|
|
501
601
|
result = record_file(
|
|
502
602
|
source,
|
|
503
|
-
|
|
603
|
+
src,
|
|
504
604
|
retrieved_at=args.retrieved_at,
|
|
505
605
|
url=args.url,
|
|
506
606
|
etag=args.etag,
|
|
@@ -515,7 +615,7 @@ def _record_stage(run: _Run) -> list[str]:
|
|
|
515
615
|
run.result["dry_run"] = True
|
|
516
616
|
run.result["records"] = [_json_record(result, before)]
|
|
517
617
|
what = f"{_marker(result, before)}, {result.bytes:,} B, sha256 {result.sha256}"
|
|
518
|
-
run.say(f"would record {source['id']} from {args.path.as_posix()}: {what}")
|
|
618
|
+
run.say(f"would record {source['id']} from {Path(args.path).as_posix()}: {what}")
|
|
519
619
|
else:
|
|
520
620
|
_report_records(run, [result], before)
|
|
521
621
|
return []
|
|
@@ -524,19 +624,35 @@ def _record_stage(run: _Run) -> list[str]:
|
|
|
524
624
|
def _build_stage(run: _Run) -> list[str]:
|
|
525
625
|
sources = _sources(run)
|
|
526
626
|
output_format = load_output_format(run.args.manifest)
|
|
627
|
+
package = (PROCESSED / DATAPACKAGE).as_posix()
|
|
527
628
|
if run.args.dry_run:
|
|
629
|
+
check_build_revision(run.build_revision)
|
|
630
|
+
would = []
|
|
528
631
|
for source in implemented(select(sources, run.args.only)):
|
|
529
632
|
current_record(source, RAW) # the same refusal build gives for a missing or changed raw file
|
|
530
|
-
|
|
531
|
-
|
|
633
|
+
would.append((PROCESSED / output_name(source, output_format)).as_posix())
|
|
634
|
+
would.append(package)
|
|
635
|
+
run.result["dry_run"] = True
|
|
636
|
+
run.result["would_write"] = would
|
|
637
|
+
for path in would:
|
|
638
|
+
run.say(f"would write {path}")
|
|
532
639
|
return []
|
|
533
640
|
name = load_package_name(run.args.manifest)
|
|
641
|
+
outputs = []
|
|
534
642
|
for out, count in build_sources(
|
|
535
|
-
sources,
|
|
643
|
+
sources,
|
|
644
|
+
parse=run.parse,
|
|
645
|
+
only=run.args.only,
|
|
646
|
+
output_format=output_format,
|
|
647
|
+
name=name,
|
|
648
|
+
build_revision=run.build_revision,
|
|
536
649
|
):
|
|
650
|
+
outputs.append({"path": out.as_posix(), "rows": count})
|
|
537
651
|
size = f"{out.stat().st_size} bytes" if count is None else f"{count} row{'' if count == 1 else 's'}"
|
|
538
652
|
run.say(f"{size} -> {out.as_posix()}")
|
|
539
|
-
run.
|
|
653
|
+
run.result["outputs"] = outputs
|
|
654
|
+
run.result["package"] = package
|
|
655
|
+
run.say(f"package -> {package}")
|
|
540
656
|
return []
|
|
541
657
|
|
|
542
658
|
|
|
@@ -138,7 +138,7 @@ class _NoRedirectInward(urllib.request.HTTPRedirectHandler):
|
|
|
138
138
|
fp.close()
|
|
139
139
|
msg = f"refused a redirect from a public host to {without_query(newurl)}, which is not HTTP or HTTPS"
|
|
140
140
|
raise _InwardRedirectError(msg)
|
|
141
|
-
new.public_only = True # ty: ignore[
|
|
141
|
+
new.public_only = True # ty: ignore[missing-attribute] # read back by _PeerCheck
|
|
142
142
|
# urllib copies every header to the new request. A token meant for one host must not
|
|
143
143
|
# reach another, nor go out in clear text after https -> http, so a redirect that
|
|
144
144
|
# changes the scheme, host or port keeps only the harmless ones.
|
|
@@ -398,11 +398,13 @@ def fetch_sources(
|
|
|
398
398
|
before: dict[str, dict[str, Any]] | None = None,
|
|
399
399
|
progress: Callable[[str], None] | None = None,
|
|
400
400
|
done: list[FetchRecord] | None = None,
|
|
401
|
+
restored: set[str] | None = None,
|
|
401
402
|
) -> list[FetchRecord]:
|
|
402
403
|
"""Fetch and optionally retain the pre-fetch hashes from the same locked history read.
|
|
403
404
|
|
|
404
405
|
`progress`, when given, is called before each source with its id and place, as `example (1 of 3)`.
|
|
405
406
|
`done`, when given, collects the records as they come, so a caller still has them after Ctrl-C.
|
|
407
|
+
`restored`, when given, collects sources downloaded without a usable local copy.
|
|
406
408
|
"""
|
|
407
409
|
sources = select(sources, only)
|
|
408
410
|
raw.mkdir(parents=True, exist_ok=True)
|
|
@@ -418,7 +420,7 @@ def fetch_sources(
|
|
|
418
420
|
if progress:
|
|
419
421
|
progress(f"{source['id']} ({number} of {len(todo)})")
|
|
420
422
|
try:
|
|
421
|
-
records.append(_fetch_one(source, raw, log, logged, user_agent))
|
|
423
|
+
records.append(_fetch_one(source, raw, log, logged, user_agent, restored))
|
|
422
424
|
except ValueError as error: # messages already name the source
|
|
423
425
|
failures.append(str(error))
|
|
424
426
|
except _TRANSIENT as error:
|
|
@@ -428,15 +430,26 @@ def fetch_sources(
|
|
|
428
430
|
return records
|
|
429
431
|
|
|
430
432
|
|
|
431
|
-
def _fetch_one(
|
|
433
|
+
def _fetch_one(
|
|
434
|
+
source: Source,
|
|
435
|
+
raw: Path,
|
|
436
|
+
log: Path,
|
|
437
|
+
logged: dict[str, dict[str, Any]],
|
|
438
|
+
user_agent: str,
|
|
439
|
+
restored: set[str] | None = None,
|
|
440
|
+
) -> FetchRecord:
|
|
432
441
|
"""Fetch one source, write its raw file, log and record, and return the record."""
|
|
433
|
-
|
|
442
|
+
previous = _previous(source, raw)
|
|
443
|
+
response = _get(source, previous, user_agent, raw)
|
|
434
444
|
if isinstance(response, FetchRecord):
|
|
435
445
|
# A version written to disk by a fetch that died before logging it gets logged now.
|
|
436
446
|
_log_new_version(log, logged, response)
|
|
437
447
|
return response
|
|
438
448
|
try:
|
|
439
|
-
|
|
449
|
+
record = _keep(source, response, raw, log, logged, user_agent)
|
|
450
|
+
if previous is None and restored is not None:
|
|
451
|
+
restored.add(source["id"])
|
|
452
|
+
return record
|
|
440
453
|
finally:
|
|
441
454
|
response.path.unlink(missing_ok=True) # gone already once moved into place
|
|
442
455
|
|