Skip to content

Python API

sourceledger

Fetch or record a dataset's public files with provenance, and release it without files whose terms forbid it.

Every file keeps a provenance record, and every output row names the bytes it came from.

The names below are the public API. Until 1.0, a breaking change to them, to the keys of sources.toml, or to the fetch-record format comes only in a minor version, listed in the changelog. The submodules, such as sourceledger.ledger, may change in any release.

FetchBusyError

Bases: OSError

Another process holds the fetch lock on this raw folder.

Source code in src/sourceledger/ledger.py
111
112
class FetchBusyError(OSError):
    """Another process holds the fetch lock on this raw folder."""

FetchError

Bases: OSError

One or more sources failed to fetch. The others were fetched and recorded as usual.

Source code in src/sourceledger/ledger.py
102
103
104
105
106
107
108
class FetchError(OSError):
    """One or more sources failed to fetch. The others were fetched and recorded as usual."""

    def __init__(self, records: list[FetchRecord], failures: list[str]) -> None:
        super().__init__("\n".join(failures))
        self.records = records  # the sources that succeeded
        self.failures = failures  # one line per source that did not

FetchRecord dataclass

What one download was, so every output row traces back to the bytes it came from.

Source code in src/sourceledger/ledger.py
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
@dataclasses.dataclass(frozen=True, slots=True)
class FetchRecord:
    """What one download was, so every output row traces back to the bytes it came from."""

    source_id: str
    url: str
    retrieved_at: str
    sha256: str
    bytes: int
    vintage: str
    # Empty when the server sends none. Defaults keep records written before these fields readable.
    last_modified: str = ""
    etag: str = ""
    # Where the bytes came from after redirects. Empty when there were none.
    final_url: str = ""
    # The request headers taken from environment variables (names only, never values).
    env_headers: list[str] = dataclasses.field(default_factory=list)
    # The Internet Archive's snapshot of the URL, for a source with `archive = true`. Set by
    # the fetch that first brought these bytes; a later download of the same bytes takes it
    # from their line in the log. Empty when the source does not ask for one, or the archive
    # did not answer with one.
    archive_url: str = ""
    # When `record()` took these bytes from a file another tool downloaded; empty for a
    # fetch. `retrieved_at` is then the download time that tool reported, or empty when it
    # reported none. With `parameters`, left out of the log and sidecar while empty, so a
    # fetched record is written as 0.4.0 wrote it.
    recorded_at: str = ""
    # The request's own metadata, as the caller passed it to `record()`.
    parameters: dict[str, str] = dataclasses.field(default_factory=dict)

ReleaseError

Bases: ValueError

The release was refused: its input or its output has the problems listed.

Source code in src/sourceledger/releaser.py
123
124
125
126
127
128
class ReleaseError(ValueError):
    """The release was refused: its input or its output has the `problems` listed."""

    def __init__(self, problems: list[str]) -> None:
        super().__init__("; ".join(problems))
        self.problems = problems

RestrictedSourceError

Bases: ReleaseError

A file in the release folder holds the bytes of a source whose terms forbid redistribution.

Source code in src/sourceledger/releaser.py
131
132
class RestrictedSourceError(ReleaseError):
    """A file in the release folder holds the bytes of a source whose terms forbid redistribution."""

ValidatorCouldNotRun

Bases: OSError

A check stopped without reporting findings, such as offline or past its time limit, so it did not check.

Source code in src/sourceledger/releaser.py
147
148
class ValidatorCouldNotRun(OSError):  # noqa: N818
    """A check stopped without reporting findings, such as offline or past its time limit, so it did not check."""

ValidatorFailed

Bases: ReleaseError

A check of the release folder reported findings, one per problem; ran names each check that ran.

Source code in src/sourceledger/releaser.py
135
136
137
138
139
140
class ValidatorFailed(ReleaseError):  # noqa: N818  # the names decision 0006 gives
    """A check of the release folder reported findings, one per problem; `ran` names each check that ran."""

    def __init__(self, problems: list[str], ran: list[dict[str, str]]) -> None:
        super().__init__(problems)
        self.ran = ran

ValidatorMissing

Bases: OSError

A check the release needs is not installed: the release extra is missing.

Source code in src/sourceledger/releaser.py
143
144
class ValidatorMissing(OSError):  # noqa: N818
    """A check the release needs is not installed: the `release` extra is missing."""

build(sources: list[Source], *, raw: Path = RAW, processed: Path = PROCESSED, parse: Parser = parse_source, only: Collection[str] | None = None, output_format: str = 'csv', name: str | None = None, build_revision: str | None = None) -> list[Path]

Write implemented sources to processed: unchanged files, or tables stamped with their fetch records.

format = "file" copies the original bytes to processed/<raw_name>, without parsing. For tables, parse reads each raw file; the default reads CSV, JSON and Excel by format. output_format selects CSV (the default) or Parquet with zstd compression and an explicit string schema. Parquet needs the parquet extra and writes batches of at most 10,000 rows. Then writes processed/datapackage.json, a Frictionless Data Package (v2) describing every output: its columns, size and SHA-256, its source URL and licence, and its fetch record. The package is called name; without one, the [project] name in ./pyproject.toml, or else the current folder's name, either made lower case. build_revision, if supplied, records the code revision in each rebuilt resource. Identical inputs and revision give the same files.

only restricts the build to those source ids. The package keeps each other source's entry as the last build wrote it. Raises ValueError for an unknown source id, a build revision that is empty or cannot be encoded as UTF-8, or a file output named datapackage.json, which is reserved for the descriptor.

Source code in src/sourceledger/builder.py
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
def build(
    sources: list[Source],
    *,
    raw: Path = RAW,
    processed: Path = PROCESSED,
    parse: Parser = parse_source,
    only: Collection[str] | None = None,
    output_format: str = "csv",
    name: str | None = None,
    build_revision: str | None = None,
) -> list[Path]:
    """Write implemented sources to `processed`: unchanged files, or tables stamped with their fetch records.

    `format = "file"` copies the original bytes to `processed/<raw_name>`, without parsing.
    For tables, `parse` reads each raw file; the default reads CSV, JSON and Excel by format.
    `output_format` selects CSV (the default) or Parquet with zstd compression and an explicit
    string schema. Parquet needs the parquet extra and writes batches of at most 10,000 rows.
    Then writes `processed/datapackage.json`, a Frictionless Data Package (v2) describing every
    output: its columns, size and SHA-256, its source URL and licence, and its fetch record.
    The package is called `name`; without one, the `[project]` name in ./pyproject.toml, or else
    the current folder's name, either made lower case. `build_revision`, if supplied, records
    the code revision in each rebuilt resource. Identical inputs and revision give the same files.

    `only` restricts the build to those source ids. The package keeps each other source's
    entry as the last build wrote it. Raises ValueError for an unknown source id, a build revision
    that is empty or cannot be encoded as UTF-8, or a file output named `datapackage.json`, which
    is reserved for the descriptor.
    """
    return [
        out
        for out, _count in build_sources(
            sources,
            raw=raw,
            processed=processed,
            parse=parse,
            only=only,
            output_format=output_format,
            name=name,
            build_revision=build_revision,
        )
    ]

parse_csv(source: Source, payload: bytes) -> tuple[list[str], list[dict[str, str]]]

One raw CSV file as its columns and rows. A gzipped file is decompressed first.

Raises ValueError for a file that is not UTF-8, a repeated column name, a row with more or fewer fields than the header, or a gzipped file that is damaged or decompresses past the source's max_bytes.

Source code in src/sourceledger/builder.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
def parse_csv(source: Source, payload: bytes) -> tuple[list[str], list[dict[str, str]]]:
    """One raw CSV file as its columns and rows. A gzipped file is decompressed first.

    Raises ValueError for a file that is not UTF-8, a repeated column name, a row with more or
    fewer fields than the header, or a gzipped file that is damaged or decompresses past the
    source's `max_bytes`.
    """
    text = _text(source, _maybe_gunzip(source, payload))
    columns, rows = _csv_rows(source, io.StringIO(text, newline=""))
    return columns, [dict(zip(columns, row, strict=True)) for row in rows]

parse_json(source: Source, payload: bytes) -> tuple[list[str], list[dict[str, str]]]

A JSON array of objects as columns and rows: one column per key, in the order keys first appear.

A key an object lacks is an empty cell. Numbers are kept as written, and nested values as JSON text. Raises ValueError for a file that is not UTF-8, anything but an array of objects, or one nested too deeply to read.

Source code in src/sourceledger/builder.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def parse_json(source: Source, payload: bytes) -> tuple[list[str], list[dict[str, str]]]:
    """A JSON array of objects as columns and rows: one column per key, in the order keys first appear.

    A key an object lacks is an empty cell. Numbers are kept as written, and nested values
    as JSON text. Raises ValueError for a file that is not UTF-8, anything but an array of
    objects, or one nested too deeply to read.
    """
    payload = _maybe_gunzip(source, payload)
    # From 3.14 the reader's depth limit follows the stack size, so a deep value can load and
    # then overflow while its cell is written: both steps are covered.
    try:
        data = json.loads(_text(source, payload), parse_float=_Number, parse_int=_Number)
        if not (isinstance(data, list) and all(isinstance(item, dict) for item in data)):
            msg = f"{source['id']}: expected a JSON array of objects"
            raise ValueError(msg)
        columns = list(dict.fromkeys(key for item in data for key in item))
        for index, item in enumerate(data):
            data[index] = {column: _cell(item.get(column)) for column in columns}
    except RecursionError as error:
        msg = f"{source['id']}: JSON nested too deeply to read"
        raise ValueError(msg) from error
    return columns, data

parse_source(source: Source, payload: bytes) -> tuple[list[str], list[dict[str, str]]]

One raw file as its columns and rows, read by its format: the default Parser.

The format is the source's format key, or else the URL's extension: .json is JSON, .xlsx is Excel, anything else is CSV (gzipped or not). Raises ValueError for format = "file", which has no table; build copies these files without a parser.

Source code in src/sourceledger/builder.py
75
76
77
78
79
80
81
82
83
84
85
def parse_source(source: Source, payload: bytes) -> tuple[list[str], list[dict[str, str]]]:
    """One raw file as its columns and rows, read by its format: the default `Parser`.

    The format is the source's `format` key, or else the URL's extension: `.json` is JSON,
    `.xlsx` is Excel, anything else is CSV (gzipped or not). Raises ValueError for
    `format = "file"`, which has no table; `build` copies these files without a parser.
    """
    if _format(source) == FILE_FORMAT:
        msg = f"{source['id']}: format file has no table to parse"
        raise ValueError(msg)
    return _PARSERS[_format(source)](source, payload)

parse_xlsx(source: Source, payload: bytes) -> tuple[list[str], list[dict[str, str]]]

One sheet of an Excel workbook as columns and rows, the first row as the header.

The sheet is the source's sheet key, or else the first. Fully empty rows are skipped, and so are empty header cells at the end of the row. An empty cell reads as "", like an empty CSV field. Needs the xlsx extra: uv add 'sourceledger[xlsx]'.

Raises ValueError for a file that is not a workbook, one that expands past the source's max_bytes, a missing sheet, a repeated column name, or a cell right of the header.

Source code in src/sourceledger/builder.py
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
def parse_xlsx(source: Source, payload: bytes) -> tuple[list[str], list[dict[str, str]]]:
    """One sheet of an Excel workbook as columns and rows, the first row as the header.

    The sheet is the source's `sheet` key, or else the first. Fully empty rows are skipped,
    and so are empty header cells at the end of the row. An empty cell reads as "", like an
    empty CSV field. Needs the `xlsx` extra: `uv add 'sourceledger[xlsx]'`.

    Raises ValueError for a file that is not a workbook, one that expands past the source's
    `max_bytes`, a missing sheet, a repeated column name, or a cell right of the header.
    """
    try:
        import openpyxl  # noqa: PLC0415  # an optional extra, imported only when a source needs it
        from openpyxl.utils.exceptions import InvalidFileException  # noqa: PLC0415
    except ImportError as error:
        msg = f"{source['id']}: reading .xlsx needs the xlsx extra: uv add 'sourceledger[xlsx]'"
        raise ValueError(msg) from error
    cap = source.get("max_bytes", _MAX_BYTES)
    try:
        # The sizes the zip declares bound what it can expand to: reading past one fails its check.
        with zipfile.ZipFile(io.BytesIO(payload)) as archive:
            expanded = sum(info.file_size for info in archive.infolist())
    except zipfile.BadZipFile as error:
        msg = f"{source['id']}: not a readable Excel workbook ({error})"
        raise ValueError(msg) from error
    if expanded > cap:
        msg = f"{source['id']}: decompresses past {cap} bytes; raise max_bytes in sources.toml if expected"
        raise ValueError(msg)
    try:
        rows = _sheet_rows(source, openpyxl.load_workbook(io.BytesIO(payload), read_only=True, data_only=True))
    except (zipfile.BadZipFile, KeyError, InvalidFileException) as error:  # a missing part reads as KeyError
        msg = f"{source['id']}: not a readable Excel workbook ({error})"
        raise ValueError(msg) from error
    if not rows:
        return [], []
    header = rows[0][1]
    width = len(header)
    while width and header[width - 1] is None:
        width -= 1
    columns = [_cell(cell) for cell in header[:width]]
    _check_columns(source, columns)
    table = []
    for number, row in rows[1:]:
        if any(cell is not None for cell in row[width:]):
            msg = f"{source['id']}: row {number} has more cells than the header"
            raise ValueError(msg)
        table.append({column: _cell(cell) for column, cell in itertools.zip_longest(columns, row[:width])})
    return columns, table

read_output(path: Path) -> Iterator[dict[str, str]]

The rows of a published CSV or Parquet table, as written, one at a time.

CSV is read row by row, Parquet in batches of at most 10,000 rows; Parquet needs the parquet extra. Wrap the call in list() to hold the whole table. This is a generator, so nothing runs until the first next(): every error, a missing file included (OSError), and ValueError for a Parquet file that cannot be read, is raised there. An iterator left unfinished keeps the file open; on Windows that blocks replacing the output, so exhaust it or call close().

Source code in src/sourceledger/builder.py
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
def read_output(path: Path) -> Iterator[dict[str, str]]:
    """The rows of a published CSV or Parquet table, as written, one at a time.

    CSV is read row by row, Parquet in batches of at most 10,000 rows; Parquet needs the
    parquet extra. Wrap the call in `list()` to hold the whole table. This is a generator, so
    nothing runs until the first `next()`: every error, a missing file included (OSError), and
    ValueError for a Parquet file that cannot be read, is raised there. An iterator left
    unfinished keeps the file open; on Windows that blocks replacing the output, so exhaust it
    or call `close()`.
    """
    if path.suffix == _PARQUET_SUFFIX:
        for batch in _parquet_batches(path):
            yield from batch.to_pylist()
        return
    with path.open(newline="", encoding="utf-8") as fh:
        yield from csv.DictReader(fh)

entry(argv: list[str] | None = None, *, parse: Parser = parse_source, prog: str = 'sourceledger', user_agent: str = USER_AGENT, manifest: Path = MANIFEST, build_revision: str | None = None) -> NoReturn

The sourceledger command: run main with these arguments, and exit as the shell expects.

A project's own command points its console script at a function that calls this with its parse, prog, user_agent, manifest and optional build_revision, as for main. argv is the arguments, sys.argv[1:] when None, so a test can run the command and catch its SystemExit. A shell loop stops on Ctrl-C only when the command was killed by the signal; an exit code of 130 alone does not stop it, so after Ctrl-C this dies of SIGINT. main itself returns 130. A reader that closes the pipe early, such as head, ends the command quietly by SIGPIPE. Output is UTF-8, stdout with LF line ends, on every system; main leaves the streams as they are.

Source code in src/sourceledger/cli.py
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
def entry(
    argv: list[str] | None = None,
    *,
    parse: Parser = parse_source,
    prog: str = "sourceledger",
    user_agent: str = USER_AGENT,
    manifest: Path = MANIFEST,
    build_revision: str | None = None,
) -> NoReturn:
    """The `sourceledger` command: run `main` with these arguments, and exit as the shell expects.

    A project's own command points its console script at a function that calls this with its
    `parse`, `prog`, `user_agent`, `manifest` and optional `build_revision`, as for `main`.
    `argv` is the arguments, `sys.argv[1:]` when None, so a test can run the command and catch its SystemExit.
    A shell loop stops on Ctrl-C only when the command was killed by the signal; an exit code of
    130 alone does not stop it, so after Ctrl-C this dies of SIGINT. `main` itself returns 130.
    A reader that closes the pipe early, such as `head`, ends the command quietly by SIGPIPE.
    Output is UTF-8, stdout with LF line ends, on every system; `main` leaves the streams as they are.
    """
    if hasattr(signal, "SIGPIPE"):  # not on Windows
        signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    # Windows writes redirected output in the locale's code page with CRLF; the HTML report says UTF-8.
    for stream, newline in ((sys.stdout, {"newline": "\n"}), (sys.stderr, {})):
        if reconfigure := getattr(stream, "reconfigure", None):
            reconfigure(encoding="utf-8", **newline)
    code = main(
        argv=argv, parse=parse, prog=prog, user_agent=user_agent, manifest=manifest, build_revision=build_revision
    )
    if code == EXIT_INTERRUPTED and sys.platform != "win32":  # noqa: PLR2004
        sys.stdout.flush()
        sys.stderr.flush()
        signal.signal(signal.SIGINT, signal.SIG_DFL)
        os.kill(os.getpid(), signal.SIGINT)
    sys.exit(code)

main(argv: list[str] | None = None, *, parse: Parser = parse_source, prog: str = 'sourceledger', user_agent: str = USER_AGENT, manifest: Path = MANIFEST, build_revision: str | None = None) -> int

Run one stage: init, fetch, record, build, validate, status, attribution, revisions, verify, report or release.

sourceledger STAGE --help lists each stage's options. A project's own entry point calls this with its parse, its name as prog, and that name as user_agent. manifest is the sources.toml to read, ./sources.toml by default; a project that ships it inside its package passes that path, and --manifest PATH overrides both. build_revision records the project's code revision on the resources that build writes.

Returns the exit code the module docstring lists. A usage error exits through SystemExit with code 2, as argparse does.

Source code in src/sourceledger/cli.py
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
def main(  # the entry point: parse, run one stage, report it
    argv: list[str] | None = None,
    *,
    parse: Parser = parse_source,
    prog: str = "sourceledger",
    user_agent: str = USER_AGENT,
    manifest: Path = MANIFEST,
    build_revision: str | None = None,
) -> int:
    """Run one stage: init, fetch, record, build, validate, status, attribution, revisions, verify, report or release.

    `sourceledger STAGE --help` lists each stage's options. A project's own entry point calls
    this with its `parse`, its name as `prog`, and that name as `user_agent`. `manifest` is the
    sources.toml to read, `./sources.toml` by default; a project that ships it inside its
    package passes that path, and `--manifest PATH` overrides both.
    `build_revision` records the project's code revision on the resources that `build` writes.

    Returns the exit code the module docstring lists. A usage error exits through SystemExit
    with code 2, as argparse does.
    """
    argv = sys.argv[1:] if argv is None else argv
    args = None
    try:
        args, extra = _parser(prog, manifest).parse_known_args(argv)
        if extra:  # reported by the stage's parser, so the usage and help name the stage
            args.parser.error(f"unrecognized arguments: {' '.join(extra)}")
        if check_args := getattr(args, "check_args", None):
            check_args(args)
    except _ParseError as error:
        _usage_error(error, argv, args)
    # Retries and recovered fetch logs are reported as warnings, on stderr.
    logging.basicConfig(format=f"{prog}: %(message)s", level=logging.WARNING)
    return _main(_Run(args, argv, parse, prog, user_agent, build_revision))

align_rows(before: Iterable[Mapping[str, BeforeValue]], after: Iterable[Mapping[str, AfterValue]], *, keys: Sequence[str]) -> dict[tuple[str | int, ...], tuple[dict[str, BeforeValue], dict[str, AfterValue]]]

Return shallow row snapshots for keys present in both inputs, in before-row order.

Every row in both inputs is checked before matching, including rows with no match. Key cells must be nonblank strings or integers, excluding booleans. Their text and types are preserved: 2020 and "2020" are different keys. Other cells are unchanged, including missing values, nonfinite numbers and provenance fields. Nested objects remain shared because the snapshots are shallow.

Empty inputs or no common keys return an empty dictionary. Both inputs are held in memory. For other join types or dataframe operations, use pandas or Polars.

Parameters:

Name Type Description Default
before Iterable[Mapping[str, BeforeValue]]

The earlier rows, such as read_output(before_path).

required
after Iterable[Mapping[str, AfterValue]]

The later rows, such as read_output(after_path).

required
keys Sequence[str]

A nonempty sequence of distinct, nonblank column names.

required

Raises:

Type Description
ValueError

Invalid key names, a nonmapping row, a missing or invalid key cell, or a duplicate key in either input. Row errors identify the input and row.

OSError

An input iterator could not read its table. Other iterator errors also propagate unchanged.

Source code in src/sourceledger/comparison.py
 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
def align_rows[BeforeValue, AfterValue](
    before: Iterable[Mapping[str, BeforeValue]],
    after: Iterable[Mapping[str, AfterValue]],
    *,
    keys: Sequence[str],
) -> dict[tuple[str | int, ...], tuple[dict[str, BeforeValue], dict[str, AfterValue]]]:
    """Return shallow row snapshots for keys present in both inputs, in before-row order.

    Every row in both inputs is checked before matching, including rows with no match.
    Key cells must be nonblank strings or integers, excluding booleans. Their text and
    types are preserved: ``2020`` and ``"2020"`` are different keys. Other cells are
    unchanged, including missing values, nonfinite numbers and provenance fields.
    Nested objects remain shared because the snapshots are shallow.

    Empty inputs or no common keys return an empty dictionary. Both inputs are held in
    memory. For other join types or dataframe operations, use pandas or Polars.

    Args:
        before: The earlier rows, such as ``read_output(before_path)``.
        after: The later rows, such as ``read_output(after_path)``.
        keys: A nonempty sequence of distinct, nonblank column names.

    Raises:
        ValueError: Invalid key names, a nonmapping row, a missing or invalid key cell,
            or a duplicate key in either input. Row errors identify the input and row.
        OSError: An input iterator could not read its table. Other iterator errors
            also propagate unchanged.
    """
    if isinstance(keys, (str, bytes)) or not isinstance(keys, Sequence):
        msg = "keys must be a nonempty sequence of distinct nonblank column names"
        raise ValueError(msg)  # noqa: TRY004  # input errors share the public ValueError contract
    names = tuple(keys)
    if (
        not names
        or any(not isinstance(name, str) or not name.strip() for name in names)
        or len(set(names)) != len(names)
    ):
        msg = "keys must be a nonempty sequence of distinct nonblank column names"
        raise ValueError(msg)
    old, new = _index(before, names, "before"), _index(after, names, "after")
    return {key: (row, new[key]) for key, row in old.items() if key in new}

fetch(sources: list[Source], *, raw: Path = RAW, log: Path = FETCH_LOG, user_agent: str = USER_AGENT, only: Collection[str] | None = None) -> list[FetchRecord]

Download each implemented source into raw, with a fetch record beside it.

A source the server reports unchanged since its last intact fetch keeps that raw file and record, and its old record is returned. A record whose bytes differ from the last ones logged for its source is appended to log. Bytes the log already has keep its retrieved_at and final_url in the record on disk, while the returned record says when and where this run downloaded them.

Every source is tried. Raises FetchError after the loop when any failed, listing each with its reason; nothing is written for those. A source fails for a download over its max_bytes (default 200 MiB), bytes that miss the sha256 the manifest pins, or an error that outlasts its retries. Raises FetchBusyError (an OSError) at once when another fetch holds the lock on raw.

only restricts the fetch to those source ids, and leaves the others as they are. Raises ValueError for an id the manifest does not have.

Source code in src/sourceledger/fetcher.py
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
def fetch(
    sources: list[Source],
    *,
    raw: Path = RAW,
    log: Path = FETCH_LOG,
    user_agent: str = USER_AGENT,
    only: Collection[str] | None = None,
) -> list[FetchRecord]:
    """Download each implemented source into `raw`, with a fetch record beside it.

    A source the server reports unchanged since its last intact fetch keeps that raw file
    and record, and its old record is returned. A record whose bytes differ from the last
    ones logged for its source is appended to `log`. Bytes the log already has keep its
    `retrieved_at` and `final_url` in the record on disk, while the returned record says when
    and where this run downloaded them.

    Every source is tried. Raises FetchError after the loop when any failed, listing each
    with its reason; nothing is written for those. A source fails for a download over its
    `max_bytes` (default 200 MiB), bytes that miss the `sha256` the manifest pins, or an
    error that outlasts its retries. Raises FetchBusyError (an OSError) at once when
    another fetch holds the lock on `raw`.

    `only` restricts the fetch to those source ids, and leaves the others as they are.
    Raises ValueError for an id the manifest does not have.
    """
    return fetch_sources(sources, raw=raw, log=log, user_agent=user_agent, only=only)

record(source: Source, path: Path, *, retrieved_at: datetime | str | None = None, url: str | None = None, etag: str = '', last_modified: str = '', parameters: dict[str, str | int] | None = None, raw: Path = RAW, log: Path = FETCH_LOG, copy: bool = True) -> FetchRecord

Take a file another tool downloaded for source into raw, and log and record it as fetch would.

The file is copied, never moved, so the other tool keeps its cache. The same pin, lock, log and sidecar rules apply as for a fetch, and nothing goes over the network. The record's recorded_at is the time of this call. With copy=False, a source with format="file" and redistribute=False keeps its bytes in the caller's cache and stores a log entry and a separate sidecar in raw. Pass the cache path to release.

retrieved_at is when the other tool downloaded the file: a timezone-aware datetime or an ISO 8601 string with a time zone, stored in UTC. Leave it out when that tool does not say; the record then states no download time rather than pass the record time off as one. url is where the file came from, the source's URL by default; another URL is kept as the record's final_url, without its query or fragment, which can hold a signature or key. etag and last_modified are kept only when url is the source's URL, so a later fetch never sends one URL's validators to another. parameters describes the request: flat, with str or int values, stored as text in name order. It is written to the log and to every copy of the dataset's metadata, so a name that looks like a credential is refused; a value is published as given.

The same bytes recorded again for the same request, URL, download time and validators add no log line; anything else adds one, so the log's last line names how the sidecar's bytes came in. A record replaces the previous record's ETag and Last-Modified with its own. For a source with archive = true it asks for no snapshot: it keeps the one the log holds for the same bytes, and otherwise leaves archive_url empty.

Raises ValueError for a source that is not implemented, a URL with a user name or password, a time without a time zone or in the future, other parameters, a path that is not a regular file, a file over the source's max_bytes, or bytes that miss the manifest's sha256 pin. Raises FetchBusyError (an OSError) when another fetch holds the lock on raw.

Source code in src/sourceledger/ledger.py
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
def record(
    source: Source,
    path: Path,
    *,
    retrieved_at: datetime | str | None = None,
    url: str | None = None,
    etag: str = "",
    last_modified: str = "",
    parameters: dict[str, str | int] | None = None,
    raw: Path = RAW,
    log: Path = FETCH_LOG,
    copy: bool = True,
) -> FetchRecord:
    """Take a file another tool downloaded for `source` into `raw`, and log and record it as `fetch` would.

    The file is copied, never moved, so the other tool keeps its cache. The same pin, lock,
    log and sidecar rules apply as for a fetch, and nothing goes over the network. The
    record's `recorded_at` is the time of this call. With `copy=False`, a source with
    `format="file"` and `redistribute=False` keeps its bytes in the caller's cache and
    stores a log entry and a separate sidecar in `raw`. Pass the cache path to `release`.

    `retrieved_at` is when the other tool downloaded the file: a timezone-aware datetime or
    an ISO 8601 string with a time zone, stored in UTC. Leave it out when that tool does not
    say; the record then states no download time rather than pass the record time off as one.
    `url` is where the file came from, the source's URL by default; another URL is kept as
    the record's `final_url`, without its query or fragment, which can hold a signature or
    key. `etag` and `last_modified` are kept only when `url` is the source's URL, so a later
    `fetch` never sends one URL's validators to another. `parameters` describes the
    request: flat, with str or int values, stored as text in name order. It is written to
    the log and to every copy of the dataset's metadata, so a name that looks like a
    credential is refused; a value is published as given.

    The same bytes recorded again for the same request, URL, download time and validators add no log
    line; anything else adds one, so the log's last line names how the sidecar's bytes came
    in. A record replaces the previous record's ETag and Last-Modified with its own. For a
    source with `archive = true` it asks for no snapshot: it keeps the one the log holds for
    the same bytes, and otherwise leaves `archive_url` empty.

    Raises ValueError for a source that is not implemented, a URL with a user name or
    password, a time without a time zone or in the future, other `parameters`, a path that
    is not a regular file, a file over the source's `max_bytes`, or bytes that miss the
    manifest's `sha256` pin. Raises FetchBusyError (an OSError) when another fetch holds
    the lock on `raw`.
    """
    if not copy and (source.get("format") != FILE_FORMAT or source.get("redistribute") is not False):
        msg = f"{source['id']}: copy=False requires format='file' and redistribute=false"
        raise ValueError(msg)
    return record_file(
        source,
        path,
        retrieved_at=retrieved_at,
        url=url,
        etag=etag,
        last_modified=last_modified,
        parameters=parameters,
        raw=raw,
        log=log,
        copy=copy,
    )

revisions(before: Path, *, log: Path = FETCH_LOG) -> list[str]

One Markdown line per source whose bytes changed between before, an earlier copy of the log, and log.

A source that before never logged is new, not revised, and is left out. Raises FileNotFoundError when before or log does not exist: an empty report must mean no revisions, not a missing copy or a run from the wrong directory.

Source code in src/sourceledger/ledger.py
323
324
325
326
327
328
329
330
331
332
333
334
def revisions(before: Path, *, log: Path = FETCH_LOG) -> list[str]:
    """One Markdown line per source whose bytes changed between `before`, an earlier copy of the log, and `log`.

    A source that `before` never logged is new, not revised, and is left out. Raises
    FileNotFoundError when `before` or `log` does not exist: an empty report must mean no
    revisions, not a missing copy or a run from the wrong directory.
    """
    return [
        f"- `{r['source_id']}`: {r['before_sha256'][:12]} -> {r['after']['sha256'][:12]}, "
        f"{r['after']['bytes']:,} bytes, {_when(r['after'])} from <{r['after']['url']}>"
        for r in revision_records(before, log=log)
    ]

verified(source: Source, *, raw: Path = RAW) -> tuple[FetchRecord, bytes]

The fetch record and raw bytes for source, after checking that both are current.

Raises ValueError when the record was made for a different request than the manifest now makes (another URL, vintage or sha256 pin), or when the raw file no longer hashes to the record.

Source code in src/sourceledger/ledger.py
697
698
699
700
701
702
703
704
705
706
707
def verified(source: Source, *, raw: Path = RAW) -> tuple[FetchRecord, bytes]:
    """The fetch record and raw bytes for `source`, after checking that both are current.

    Raises ValueError when the record was made for a different request than the manifest
    now makes (another URL, vintage or `sha256` pin), or when the raw file no longer hashes
    to the record.
    """
    record = _record(source, raw)
    payload = (raw / raw_name(source)).read_bytes()
    _check_hash(source, record, hashlib.sha256(payload).hexdigest())
    return record, payload

load_manifest(path: Path = MANIFEST) -> list[Source]

The [[source]] tables of sources.toml, after checking ids, URLs, caps, timeouts and pins.

Source code in src/sourceledger/manifest.py
 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
def load_manifest(path: Path = MANIFEST) -> list[Source]:
    """The `[[source]]` tables of sources.toml, after checking ids, URLs, caps, timeouts and pins."""
    with path.open("rb") as fh:
        manifest = tomllib.load(fh)
    # A typo such as [[sources]] must not read as an empty manifest: build would then write
    # an empty datapackage.json over a good one.
    for key in sorted(manifest.keys() - _MANIFEST_KEYS):
        close = difflib.get_close_matches(key.lower().replace("-", "_"), _MANIFEST_KEYS, n=1, cutoff=0.6)
        hint = f"; did you mean {close[0]}?" if close else ""
        msg = f"sources.toml: {key!r} is not a sources.toml key{hint}"
        raise ValueError(msg)
    _check_output_format(manifest.get("output_format", "csv"))
    _check_release_formats(manifest.get("release_formats", []))
    _check_name(manifest.get("name"))
    sources = manifest.get("source", [])
    if not isinstance(sources, list) or not all(isinstance(s, dict) and isinstance(s.get("id"), str) for s in sources):
        msg = "sources.toml: every [[source]] needs a string id"
        raise ValueError(msg)
    _check_ids([s["id"] for s in sources])
    if no_url := [s["id"] for s in implemented(sources) if not isinstance(s.get("url"), str)]:
        msg = f"implemented sources {no_url} in sources.toml have no url"
        raise ValueError(msg)
    # Not isinstance: bool is an int subclass, so `max_bytes = true` would pass as a 1-byte cap.
    caps = {s["id"]: s.get("max_bytes", _MAX_BYTES) for s in sources}
    if bad_cap := [i for i, cap in caps.items() if type(cap) is not int or cap < 1]:
        msg = f"sources {bad_cap} in sources.toml need max_bytes to be a positive whole number"
        raise ValueError(msg)
    if bad_archive := [s["id"] for s in sources if not isinstance(s.get("archive", False), bool)]:
        msg = f"sources {bad_archive} in sources.toml need archive to be true or false"
        raise ValueError(msg)
    if bad_timeout := [
        s["id"]
        for s in sources
        if type(timeout := s.get("timeout_s", _BUDGET_S)) not in (int, float) or not 0 < timeout <= sys.float_info.max
    ]:
        msg = f"sources {bad_timeout} in sources.toml need timeout_s to be a positive finite number"
        raise ValueError(msg)
    for source in sources:
        _check_placement(source)
        _check_text(source)
        _check_url(source)
        _check_pin(source)
        _check_vintage(source)
        _check_format(source)
        _check_headers(source)
    return sources

load_output_format(path: Path = MANIFEST) -> str

The project's output_format from sources.toml, "csv" when unset: pass it to build and validate.

Source code in src/sourceledger/manifest.py
232
233
234
235
236
237
def load_output_format(path: Path = MANIFEST) -> str:
    """The project's `output_format` from sources.toml, "csv" when unset: pass it to `build` and `validate`."""
    with path.open("rb") as fh:
        output_format = tomllib.load(fh).get("output_format", "csv")
    _check_output_format(output_format)
    return output_format

load_package_name(path: Path = MANIFEST) -> str | None

The project's name from sources.toml, None when unset: pass it to build, which then picks one.

Source code in src/sourceledger/manifest.py
247
248
249
250
251
252
def load_package_name(path: Path = MANIFEST) -> str | None:
    """The project's `name` from sources.toml, None when unset: pass it to `build`, which then picks one."""
    with path.open("rb") as fh:
        name = tomllib.load(fh).get("name")
    _check_name(name)
    return name

load_release_formats(path: Path = MANIFEST) -> list[str]

The project's release_formats from sources.toml, empty when unset: pass it to release.

Source code in src/sourceledger/manifest.py
264
265
266
267
268
269
def load_release_formats(path: Path = MANIFEST) -> list[str]:
    """The project's `release_formats` from sources.toml, empty when unset: pass it to `release`."""
    with path.open("rb") as fh:
        formats = tomllib.load(fh).get("release_formats", [])
    _check_release_formats(formats)
    return formats

check_release(folder: Path) -> tuple[list[str], list[dict[str, str]]]

Check a release folder: SHA256SUMS against the files, then each metadata file with its validator.

Returns one string per problem, with names from the folder as they are (pass each through printable before a terminal), and the file, name and version of each check that ran. Raises FileNotFoundError when folder is not a folder, ValidatorMissing when a metadata file is there but its validator is not installed, and ValidatorCouldNotRun when a validator stopped without reporting findings or ran past its time limit.

Source code in src/sourceledger/releaser.py
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
def check_release(folder: Path) -> tuple[list[str], list[dict[str, str]]]:
    """Check a release folder: SHA256SUMS against the files, then each metadata file with its validator.

    Returns one string per problem, with names from the folder as they are (pass each through
    `printable` before a terminal), and the `file`, `name` and `version` of each check that ran.
    Raises FileNotFoundError when `folder` is not a folder, ValidatorMissing when a metadata
    file is there but its validator is not installed, and ValidatorCouldNotRun when a validator
    stopped without reporting findings or ran past its time limit.
    """
    if not folder.is_dir():
        raise FileNotFoundError(errno.ENOENT, "no such folder", str(folder))
    present = [name for name in _VALIDATORS if (folder / name).is_file()]
    versions = {name: _validator_version(name) for name in present}
    problems = _sums_problems(folder)
    ran = [{"file": SUMS, "name": "sourceledger", "version": _VERSION}]
    for name in present:
        dist, args = _VALIDATORS[name]
        # -I: the folder is someone else's, and a module planted in it must not shadow the validator.
        # -X utf8: -I ignores PYTHONIOENCODING, and Windows would read the JSON and pipe the output as cp1252.
        command = [sys.executable, "-I", "-X", "utf8", *args]
        try:
            subprocess.run(command, cwd=folder, capture_output=True, check=True, timeout=_TIMEOUT_S)  # noqa: S603  # a fixed command line, with this interpreter
        except subprocess.CalledProcessError as failed:
            problems += [f"{name}: {finding}" for finding in _findings(name, dist, failed)]
        except subprocess.TimeoutExpired:
            msg = f"{name}: {dist} did not finish in {_TIMEOUT_S} s"
            raise ValidatorCouldNotRun(msg) from None
        ran.append({"file": name, "name": dist, "version": versions[name]})
    return problems, ran

release(sources: list[Source], out_dir: Path, *, formats: Iterable[str] = (), raw: Path = RAW, processed: Path = PROCESSED, codemeta: Path = CODEMETA, output_format: str = 'csv', name: str | None = None, dry_run: bool = False, external_inputs: Mapping[str, Path] | None = None, log: Path = FETCH_LOG) -> dict[str, Any]

Write a release folder at out_dir from a validated build, check it, and return what it holds.

The folder gets data/ with the output of every implemented source whose redistribute is true, datapackage.json without the others, ro-crate-metadata.json and croissant.json when formats (any iterable of their names) asks for them, and SHA256SUMS, written last. The descriptive fields come from codemeta. The folder is written beside out_dir and moved into place only once every check passed, so a refused release leaves nothing at out_dir. external_inputs maps restricted file source ids to cache files already recorded with record(copy=False). Their checksums and sizes are checked against those records. They need no build output and the package contains their fingerprints, without local paths. Pass the same log as record so the release can also exclude earlier revisions. dry_run checks the input and returns what would be written, without writing. name is passed to validate.

The result has files (paths in the folder), excluded (source ids), formats (each optional format "written" or "skipped") and validators (file, name, version of each check that ran). Raises ReleaseError when validate finds problems or codemeta.json is missing or lacks a field a format needs, RestrictedSourceError when a restricted source's bytes reached the folder, ValidatorFailed when a check reports findings, ValidatorMissing when a check a format needs is not installed, ValidatorCouldNotRun when a check stopped without reporting, and FileExistsError when out_dir exists and is not empty.

Source code in src/sourceledger/releaser.py
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
def release(  # noqa: PLR0913  # the same project paths and options as the preceding stages
    sources: list[Source],
    out_dir: Path,
    *,
    formats: Iterable[str] = (),
    raw: Path = RAW,
    processed: Path = PROCESSED,
    codemeta: Path = CODEMETA,
    output_format: str = "csv",
    name: str | None = None,
    dry_run: bool = False,
    external_inputs: Mapping[str, Path] | None = None,
    log: Path = FETCH_LOG,
) -> dict[str, Any]:
    """Write a release folder at `out_dir` from a validated build, check it, and return what it holds.

    The folder gets `data/` with the output of every implemented source whose `redistribute` is
    true, `datapackage.json` without the others, `ro-crate-metadata.json` and `croissant.json`
    when `formats` (any iterable of their names) asks for them, and `SHA256SUMS`, written last.
    The descriptive fields come from `codemeta`. The folder is written beside `out_dir` and moved
    into place only once every check passed, so a refused release leaves nothing at `out_dir`.
    `external_inputs` maps restricted file source ids to cache files already recorded with
    `record(copy=False)`. Their checksums and sizes are checked against those records. They
    need no build output and the package contains their fingerprints, without local paths.
    Pass the same `log` as `record` so the release can also exclude earlier revisions.
    `dry_run` checks the input and returns what would be written, without writing. `name` is
    passed to `validate`.

    The result has `files` (paths in the folder), `excluded` (source ids), `formats` (each
    optional format "written" or "skipped") and `validators` (`file`, `name`, `version` of each
    check that ran). Raises ReleaseError when `validate` finds problems or codemeta.json is missing or lacks a
    field a format needs, RestrictedSourceError when a restricted source's bytes reached the
    folder, ValidatorFailed when a check reports findings, ValidatorMissing when a check a format
    needs is not installed, ValidatorCouldNotRun when a check stopped without reporting, and
    FileExistsError when `out_dir` exists and is not empty.
    """
    # A str is an iterable of str too, and would be read one letter at a time.
    wanted = set(formats)
    if isinstance(formats, str) or not wanted <= set(RELEASE_FORMATS):
        msg = f"formats must be drawn from {list(RELEASE_FORMATS)}, not {formats!r}"
        raise ValueError(msg)
    formats = [fmt for fmt in RELEASE_FORMATS if fmt in wanted]
    external = dict(external_inputs or {})
    built = _buildable_sources(sources, external, processed)
    if problems := validate(built, raw=raw, processed=processed, output_format=output_format, name=name):
        raise ReleaseError(problems)
    if out_dir.exists() and (not out_dir.is_dir() or any(out_dir.iterdir())):
        msg = f"{out_dir.as_posix()} already exists; a release goes into a new folder"
        raise FileExistsError(msg)
    # codemeta.json first: a missing field is cheaper to learn before installing the validators.
    described = _described(codemeta, formats)
    for fmt in formats:
        _validator_version(_FILES[fmt])
    records = _external_records(sources, raw, external, checked=dry_run)
    history = _external_history(log, records)
    shipped, excluded = _split(sources)
    files = [f"{_DATA}/{output_name(s, output_format)}" for s in shipped]
    files += [DATAPACKAGE, *(_FILES[fmt] for fmt in formats), SUMS]
    result: dict[str, Any] = {
        "files": files,
        "excluded": [s["id"] for s in excluded],
        "formats": {fmt: "written" if fmt in formats else "skipped" for fmt in RELEASE_FORMATS},
        "validators": [],
    }
    if len(files) > _ZENODO_FILES:
        _logger.warning(
            "the release has %d files; Zenodo takes at most %d, so zip them first", len(files), _ZENODO_FILES
        )
    if dry_run:
        return result
    folder = _part_folder(out_dir)
    try:
        _write(folder, sources, described, formats, records, raw=raw, processed=processed, output_format=output_format)
        _refuse_restricted(folder, out_dir, sources, raw, processed, output_format, external_history=history)
        problems, result["validators"] = check_release(folder)
        if problems:
            raise ValidatorFailed(problems, result["validators"])
        _promote(folder, out_dir, sources, raw, log, external, records, history)
    finally:
        if folder.exists():
            shutil.rmtree(folder)
    return result

attribution(sources: list[Source]) -> list[str]

The implemented sources as the lines of a Markdown table, in manifest order.

One row per source: its name (or id), the terms in the publisher's words, the licence, where the terms are stated, and whether the raw file may be republished. For a dataset's README or release notes.

Source code in src/sourceledger/report.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
def attribution(sources: list[Source]) -> list[str]:
    """The implemented sources as the lines of a Markdown table, in manifest order.

    One row per source: its name (or id), the terms in the publisher's words, the licence,
    where the terms are stated, and whether the raw file may be republished. For a
    dataset's README or release notes.
    """
    lines = ["| Source | Terms | Licence | Terms URL | Redistribute |", "| --- | --- | --- | --- | --- |"]
    for source in implemented(sources):
        values = [
            source.get("name", source["id"]),
            source.get("terms", ""),
            source.get("license", ""),
            source.get("terms_url", ""),
            _yes_no(source.get("redistribute")),
        ]
        lines.append("| " + " | ".join(map(_md_cell, values)) + " |")
    return lines

status(sources: list[Source], *, log: Path = FETCH_LOG) -> list[str]

One line per source, from the manifest and the fetch log only: no network, no raw files.

Each line gives the id, the status, the vintage, when the version last logged was fetched (or never; recorded <time> for a file record() took in with no download time), the start of its SHA-256, the licence, and whether the raw file may be republished.

Source code in src/sourceledger/report.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def status(sources: list[Source], *, log: Path = FETCH_LOG) -> list[str]:
    """One line per source, from the manifest and the fetch log only: no network, no raw files.

    Each line gives the id, the status, the vintage, when the version last logged was fetched
    (or `never`; `recorded <time>` for a file `record()` took in with no download time), the
    start of its SHA-256, the licence, and whether the raw file may be republished.
    """
    width = max((len(s["id"]) for s in sources), default=0)
    return [
        "  ".join(
            [
                f"{r['source_id']:<{width}}",
                f"{r['status']!s:<13}",
                r["vintage"],
                "never" if r["retrieved_at"] is None else r["retrieved_at"] or f"recorded {r['recorded_at']}",
                (r["sha256"] or "-")[:12],
                str(r["license"] or "-"),
                f"redistribute={_yes_no(r['redistribute'])}",
            ]
        )
        for r in status_records(sources, log=log)
    ]

validate(sources: list[Source], *, raw: Path = RAW, processed: Path = PROCESSED, only: Collection[str] | None = None, output_format: str = 'csv', name: str | None = None) -> list[str]

Check the published output against the manifest and the fetch records, and return one string per problem.

only restricts the checks to those source ids, and skips the two that concern the whole output: files no source owns, and the package's list of sources. Raises ValueError for an id the manifest does not have. output_format must match the build: CSV by default, or Parquet (needs the parquet extra). name, the package name sources.toml sets, must be the one datapackage.json has; None skips that check, since the fallback names differ between checkouts.

Source code in src/sourceledger/report.py
 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
def validate(
    sources: list[Source],
    *,
    raw: Path = RAW,
    processed: Path = PROCESSED,
    only: Collection[str] | None = None,
    output_format: str = "csv",
    name: str | None = None,
) -> list[str]:
    """Check the published output against the manifest and the fetch records, and return one string per problem.

    `only` restricts the checks to those source ids, and skips the two that concern the whole
    output: files no source owns, and the package's list of sources. Raises ValueError for an
    id the manifest does not have.
    `output_format` must match the build: CSV by default, or Parquet (needs the parquet extra).
    `name`, the package name sources.toml sets, must be the one datapackage.json has; None skips
    that check, since the fallback names differ between checkouts.
    """
    _check_output_format(output_format)
    selected = select(sources, only)
    problems = []
    listed = _listed(processed / DATAPACKAGE)
    outputs = {output_name(source, output_format) for source in sources}
    # Output of a source since removed or renamed would otherwise pass as published data.
    # A `.NAME.<random>.part` is the temp file of a build that was killed or is still running.
    if only is None:
        ids = {source["id"] for source in sources}
        problems += [
            f"{out.as_posix()}: output_format is {output_format!r}; "
            "build again, or validate with the format it was built in"
            if out.stem in ids and out.suffix in (".csv", ".parquet")
            else f"{out.as_posix()}: no source {out.stem!r} in sources.toml, and {processed.as_posix()}/ holds "
            "only build outputs; delete it, or keep the file elsewhere, as data/extra/"
            for out in sorted(processed.glob("*"))
            if out.is_file() and out.name != DATAPACKAGE and out.name not in outputs and not out.match(".*.part")
        ]
    for source in selected:
        sid, status = source["id"], source.get("status")
        out = processed / output_name(source, output_format)
        if status == UNIMPLEMENTED:
            if out.name.lower() != DATAPACKAGE and out.exists():
                problems.append(f"{sid}: status is unimplemented, but {out.as_posix()} exists")
            continue
        if status != IMPLEMENTED:
            problems.append(f"{sid}: status must be {IMPLEMENTED!r} or {UNIMPLEMENTED!r}, not {status!r}")
            continue
        problems += _terms_problems(source)
        problems += _output_problems(source, raw, out, listed.get(sid))
    return problems + _package_problems(sources, processed, only, output_format, name)

verify(folder: Path, *, external_inputs: Mapping[str, Path] | None = None) -> list[str]

Check a published dataset against its datapackage.json, offline, and return one string per problem.

Each resource's file must be inside folder and match the bytes (when given) and the hash (sha256:<hex>) the package lists. Raises OSError when the package is missing, and ValueError when it is not JSON. The problems hold names from the folder as they are: pass each through printable before it goes to a terminal.

With external_inputs, map each excluded source id to a local file to check against its published fingerprint. Without it, verify only the files shipped in the folder.

Source code in src/sourceledger/report.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def verify(folder: Path, *, external_inputs: Mapping[str, Path] | None = None) -> list[str]:
    """Check a published dataset against its datapackage.json, offline, and return one string per problem.

    Each resource's file must be inside `folder` and match the `bytes` (when given) and the
    `hash` (`sha256:<hex>`) the package lists. Raises OSError when the package is missing,
    and ValueError when it is not JSON. The problems hold names from the folder as they are:
    pass each through `printable` before it goes to a terminal.

    With `external_inputs`, map each excluded source id to a local file to check against
    its published fingerprint. Without it, verify only the files shipped in the folder.
    """
    path = folder / DATAPACKAGE
    try:
        data = read_received(path)
    except ValueError as refused:
        return [str(refused)]
    package = json.loads(data.decode("utf-8"))
    resources = package.get("resources") if isinstance(package, dict) else None
    if not isinstance(resources, list):
        return [f"{path.as_posix()} has no list of resources"]
    problems = [problem for r in resources for problem in _file_problems(folder, r if isinstance(r, dict) else {})]
    if external_inputs is not None:
        problems.extend(_excluded_input_problems(package.get("excluded_inputs", {}), external_inputs))
    return problems