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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
required |
after
|
Iterable[Mapping[str, AfterValue]]
|
The later rows, such as |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |