sourceledger 0.5.1__tar.gz → 0.6.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sourceledger
3
- Version: 0.5.1
3
+ Version: 0.6.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
@@ -52,6 +52,8 @@ CSV, JSON, Excel or binary files. List the sources and reuse terms in `sources.t
52
52
 
53
53
  Each table row identifies its download. A `datapackage.json` describes the outputs.
54
54
  The [documentation website](https://simonvanlierde.com/sourceledger/) follows a source through a publisher's revision.
55
+ In Python, [`align_rows()`](docs/recipes.md#compare-two-versions-by-row-key) matches two versions by the keys you name,
56
+ keeping the full rows and their provenance. Your code decides which values count as changed.
55
57
 
56
58
  ## Install
57
59
 
@@ -147,9 +149,6 @@ cheap. Older fetch logs stay readable. A record written by `record()`, or with
147
149
 
148
150
  - An error class per kind of failure in the other stages, under `ValueError` and `OSError`,
149
151
  once a caller needs to tell them apart. This will not break code that catches the base classes.
150
- - Comparing two versions of a table row by row, with the row keys the caller names, so a
151
- revision shows which values changed and not only that the bytes did. It starts as a pilot on
152
- real data, the archived World Development Indicators releases, before it becomes an API.
153
152
  - A review by [pyOpenSci](https://www.pyopensci.org) once the project has users besides
154
153
  its own template.
155
154
 
@@ -161,18 +160,32 @@ Not planned:
161
160
 
162
161
  Ideas and requests are welcome as [issues](https://github.com/simonvanlierde/sourceledger/issues).
163
162
 
163
+ ## Social card
164
+
165
+ [`docs/assets/og.png`](docs/assets/og.png) is the 1200x630 card shown when the link is shared. It is rendered from
166
+ [`docs/og-card.html`](docs/og-card.html), which draws the chain of custody of the revision example: the 2023 value
167
+ and the SHA-256 of the download, each before and after the publisher's change. Edit the HTML, then run:
168
+
169
+ ```sh
170
+ just og-card
171
+ ```
172
+
173
+ Zensical serves `docs/assets/`, and `docs-overrides/main.html` holds the tags.
174
+ Rendering a new card needs Node and pnpm for the Playwright screenshot command.
175
+
164
176
  ## Development
165
177
 
166
- You need [uv](https://docs.astral.sh/uv/), [just](https://just.systems), and Node 26 with
167
- [pnpm](https://pnpm.io) for the documentation site, which `just check` also builds.
178
+ You need [uv](https://docs.astral.sh/uv/) and [just](https://just.systems).
179
+ `just check` also builds the documentation site.
168
180
 
169
181
  ```sh
170
182
  uv sync
171
183
  just check
172
184
  ```
173
185
 
174
- The site is built with Astro from the Markdown in `docs/`. `just site` builds it into
175
- `site/dist/`, and every push to `main` deploys it to GitHub Pages at
186
+ Zensical builds the Markdown in `docs/`, including search and the Python API reference.
187
+ `just docs` builds it into `_docs/` in strict mode. `just docs-serve` previews it locally.
188
+ Every push to `main` deploys it to GitHub Pages at
176
189
  <https://simonvanlierde.com/sourceledger/>.
177
190
 
178
191
  [Contributing](.github/CONTRIBUTING.md) covers hooks, coding standards and tests.
@@ -20,6 +20,8 @@ CSV, JSON, Excel or binary files. List the sources and reuse terms in `sources.t
20
20
 
21
21
  Each table row identifies its download. A `datapackage.json` describes the outputs.
22
22
  The [documentation website](https://simonvanlierde.com/sourceledger/) follows a source through a publisher's revision.
23
+ In Python, [`align_rows()`](docs/recipes.md#compare-two-versions-by-row-key) matches two versions by the keys you name,
24
+ keeping the full rows and their provenance. Your code decides which values count as changed.
23
25
 
24
26
  ## Install
25
27
 
@@ -115,9 +117,6 @@ cheap. Older fetch logs stay readable. A record written by `record()`, or with
115
117
 
116
118
  - An error class per kind of failure in the other stages, under `ValueError` and `OSError`,
117
119
  once a caller needs to tell them apart. This will not break code that catches the base classes.
118
- - Comparing two versions of a table row by row, with the row keys the caller names, so a
119
- revision shows which values changed and not only that the bytes did. It starts as a pilot on
120
- real data, the archived World Development Indicators releases, before it becomes an API.
121
120
  - A review by [pyOpenSci](https://www.pyopensci.org) once the project has users besides
122
121
  its own template.
123
122
 
@@ -129,18 +128,32 @@ Not planned:
129
128
 
130
129
  Ideas and requests are welcome as [issues](https://github.com/simonvanlierde/sourceledger/issues).
131
130
 
131
+ ## Social card
132
+
133
+ [`docs/assets/og.png`](docs/assets/og.png) is the 1200x630 card shown when the link is shared. It is rendered from
134
+ [`docs/og-card.html`](docs/og-card.html), which draws the chain of custody of the revision example: the 2023 value
135
+ and the SHA-256 of the download, each before and after the publisher's change. Edit the HTML, then run:
136
+
137
+ ```sh
138
+ just og-card
139
+ ```
140
+
141
+ Zensical serves `docs/assets/`, and `docs-overrides/main.html` holds the tags.
142
+ Rendering a new card needs Node and pnpm for the Playwright screenshot command.
143
+
132
144
  ## Development
133
145
 
134
- You need [uv](https://docs.astral.sh/uv/), [just](https://just.systems), and Node 26 with
135
- [pnpm](https://pnpm.io) for the documentation site, which `just check` also builds.
146
+ You need [uv](https://docs.astral.sh/uv/) and [just](https://just.systems).
147
+ `just check` also builds the documentation site.
136
148
 
137
149
  ```sh
138
150
  uv sync
139
151
  just check
140
152
  ```
141
153
 
142
- The site is built with Astro from the Markdown in `docs/`. `just site` builds it into
143
- `site/dist/`, and every push to `main` deploys it to GitHub Pages at
154
+ Zensical builds the Markdown in `docs/`, including search and the Python API reference.
155
+ `just docs` builds it into `_docs/` in strict mode. `just docs-serve` previews it locally.
156
+ Every push to `main` deploys it to GitHub Pages at
144
157
  <https://simonvanlierde.com/sourceledger/>.
145
158
 
146
159
  [Contributing](.github/CONTRIBUTING.md) covers hooks, coding standards and tests.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sourceledger"
3
- version = "0.5.1"
3
+ version = "0.6.0"
4
4
  description = "Fetch or record a dataset's public files with provenance, and release it without files whose terms forbid it"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -131,18 +131,24 @@ exclude = ["docs/examples"]
131
131
  [tool.ty.terminal]
132
132
  error-on-warning = false
133
133
 
134
- [tool.pytest.ini_options]
134
+ [tool.pytest]
135
+ minversion = "9.0"
135
136
  addopts = [
136
137
  "-ra",
137
- "--strict-config",
138
- "--strict-markers",
139
138
  "--import-mode=importlib",
140
139
  "-m",
141
140
  "not live",
142
141
  ]
143
142
  markers = ["live: calls a real external service; deselected unless run with -m live"]
144
- testpaths = ["tests"]
145
143
  pythonpath = ["tests"]
144
+ testpaths = ["tests"]
145
+ strict = true
146
+ filterwarnings = [
147
+ "error",
148
+ 'ignore:os.path.commonprefix\(\) is deprecated:DeprecationWarning',
149
+ "ignore:ConjunctiveGraph is deprecated:DeprecationWarning:rdflib.plugins.parsers.jsonld",
150
+ ]
151
+ log_level = "INFO"
146
152
 
147
153
  [tool.coverage.run]
148
154
  source = ["src"]
@@ -166,3 +172,14 @@ also_copy = [
166
172
  "src/sourceledger/sources.schema.json",
167
173
  ]
168
174
  do_not_mutate_patterns = ['^\s*_logger\.\w+\(']
175
+
176
+ [tool.repo-review.ignore]
177
+ PY007 = "just is the task runner: `just check` runs what CI runs"
178
+ PC110 = "ruff format runs as a local hook from the venv, the same ruff CI runs"
179
+ PC140 = "ty runs as a local hook from the venv"
180
+ PC170 = "no reStructuredText: rumdl checks the Markdown docs"
181
+ PC190 = "ruff check runs as a local hook from the venv"
182
+ PC901 = "the hooks run in CI's checks workflow, not on pre-commit.ci"
183
+ PC902 = "the hooks run in CI's checks workflow, not on pre-commit.ci"
184
+ PC903 = "the hooks run in CI's checks workflow, not on pre-commit.ci"
185
+ GH200 = "Renovate updates the actions and hook revs (renovate.json5)"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sourceledger"
3
- version = "0.5.1"
3
+ version = "0.6.0"
4
4
  description = "Fetch or record a dataset's public files with provenance, and release it without files whose terms forbid it"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -124,13 +124,25 @@ exclude = ["docs/examples"]
124
124
  [tool.ty.terminal]
125
125
  error-on-warning = false
126
126
 
127
- [tool.pytest.ini_options]
128
- # `live` tests reach real services; `pytest -m live` runs only them (the last -m wins).
129
- addopts = ["-ra", "--strict-config", "--strict-markers", "--import-mode=importlib", "-m", "not live"]
127
+ # pytest 9's native table. strict turns unknown config keys, unknown markers and
128
+ # an xfail test that passes into errors, and filterwarnings turns warnings into
129
+ # failures, so a deprecation shows up in CI, not after the upgrade that removes it.
130
+ [tool.pytest]
131
+ minversion = "9.0"
132
+ addopts = ["-ra", "--import-mode=importlib", "-m", "not live"]
130
133
  markers = ["live: calls a real external service; deselected unless run with -m live"]
131
- testpaths = ["tests"]
132
134
  # The test modules import their shared helpers from tests/support.py.
133
135
  pythonpath = ["tests"]
136
+ testpaths = ["tests"]
137
+ strict = true
138
+ filterwarnings = [
139
+ "error",
140
+ # frictionless and its validators still call the deprecated helper on Python 3.15.
141
+ "ignore:os.path.commonprefix\\(\\) is deprecated:DeprecationWarning",
142
+ # rdflib's JSON-LD parser constructs its own deprecated graph class.
143
+ "ignore:ConjunctiveGraph is deprecated:DeprecationWarning:rdflib.plugins.parsers.jsonld",
144
+ ]
145
+ log_level = "INFO"
134
146
 
135
147
  # Coverage is opt-in via `pytest --cov` (`just py-cov`), not addopts, because it
136
148
  # slows every plain test run. CI's run fails under the fail_under below.
@@ -153,3 +165,16 @@ source_paths = ["src"]
153
165
  also_copy = ["README.md", "docs", ".github/scripts", "src/sourceledger/sources.schema.json"]
154
166
  # Log calls only change diagnostics; their mutants would all survive.
155
167
  do_not_mutate_patterns = ['^\s*_logger\.\w+\(']
168
+
169
+ # Checks from Scientific Python's repo-review (the sp-repo-review git hook) that this
170
+ # project skips on purpose. `prek run sp-repo-review --all-files` runs the rest.
171
+ [tool.repo-review.ignore]
172
+ PY007 = "just is the task runner: `just check` runs what CI runs"
173
+ PC110 = "ruff format runs as a local hook from the venv, the same ruff CI runs"
174
+ PC140 = "ty runs as a local hook from the venv"
175
+ PC170 = "no reStructuredText: rumdl checks the Markdown docs"
176
+ PC190 = "ruff check runs as a local hook from the venv"
177
+ PC901 = "the hooks run in CI's checks workflow, not on pre-commit.ci"
178
+ PC902 = "the hooks run in CI's checks workflow, not on pre-commit.ci"
179
+ PC903 = "the hooks run in CI's checks workflow, not on pre-commit.ci"
180
+ GH200 = "Renovate updates the actions and hook revs (renovate.json5)"
@@ -9,8 +9,9 @@ changelog. The submodules, such as `sourceledger.ledger`, may change in any rele
9
9
 
10
10
  from sourceledger.builder import Parser, build, parse_csv, parse_json, parse_source, parse_xlsx, read_output
11
11
  from sourceledger.cli import entry, main
12
+ from sourceledger.comparison import align_rows
12
13
  from sourceledger.fetcher import USER_AGENT, fetch
13
- from sourceledger.ledger import FetchError, FetchRecord, record, revisions, verified
14
+ from sourceledger.ledger import FetchBusyError, FetchError, FetchRecord, record, revisions, verified
14
15
  from sourceledger.manifest import Source, load_manifest, load_output_format, load_package_name, load_release_formats
15
16
  from sourceledger.releaser import (
16
17
  ReleaseError,
@@ -25,6 +26,7 @@ from sourceledger.report import attribution, report, status, validate, verify
25
26
 
26
27
  __all__ = [
27
28
  "USER_AGENT",
29
+ "FetchBusyError",
28
30
  "FetchError",
29
31
  "FetchRecord",
30
32
  "Parser",
@@ -34,6 +36,7 @@ __all__ = [
34
36
  "ValidatorCouldNotRun",
35
37
  "ValidatorFailed",
36
38
  "ValidatorMissing",
39
+ "align_rows",
37
40
  "attribution",
38
41
  "build",
39
42
  "check_release",
@@ -0,0 +1,77 @@
1
+ """Align published rows by their declared keys, keeping their values and provenance."""
2
+
3
+ from collections.abc import Iterable, Mapping, Sequence
4
+
5
+
6
+ def align_rows[BeforeValue, AfterValue](
7
+ before: Iterable[Mapping[str, BeforeValue]],
8
+ after: Iterable[Mapping[str, AfterValue]],
9
+ *,
10
+ keys: Sequence[str],
11
+ ) -> dict[tuple[str | int, ...], tuple[dict[str, BeforeValue], dict[str, AfterValue]]]:
12
+ """Return shallow row snapshots for keys present in both inputs, in before-row order.
13
+
14
+ Every row in both inputs is checked before matching, including rows with no match.
15
+ Key cells must be nonblank strings or integers, excluding booleans. Their text and
16
+ types are preserved: ``2020`` and ``"2020"`` are different keys. Other cells are
17
+ unchanged, including missing values, nonfinite numbers and provenance fields.
18
+ Nested objects remain shared because the snapshots are shallow.
19
+
20
+ Empty inputs or no common keys return an empty dictionary. Both inputs are held in
21
+ memory. For other join types or dataframe operations, use pandas or Polars.
22
+
23
+ Args:
24
+ before: The earlier rows, such as ``read_output(before_path)``.
25
+ after: The later rows, such as ``read_output(after_path)``.
26
+ keys: A nonempty sequence of distinct, nonblank column names.
27
+
28
+ Raises:
29
+ ValueError: Invalid key names, a nonmapping row, a missing or invalid key cell,
30
+ or a duplicate key in either input. Row errors identify the input and row.
31
+ OSError: An input iterator could not read its table. Other iterator errors
32
+ also propagate unchanged.
33
+ """
34
+ if isinstance(keys, (str, bytes)) or not isinstance(keys, Sequence):
35
+ msg = "keys must be a nonempty sequence of distinct nonblank column names"
36
+ raise ValueError(msg) # noqa: TRY004 # input errors share the public ValueError contract
37
+ names = tuple(keys)
38
+ if (
39
+ not names
40
+ or any(not isinstance(name, str) or not name.strip() for name in names)
41
+ or len(set(names)) != len(names)
42
+ ):
43
+ msg = "keys must be a nonempty sequence of distinct nonblank column names"
44
+ raise ValueError(msg)
45
+ old, new = _index(before, names, "before"), _index(after, names, "after")
46
+ return {key: (row, new[key]) for key, row in old.items() if key in new}
47
+
48
+
49
+ def _index[Value](
50
+ rows: Iterable[Mapping[str, Value]], keys: tuple[str, ...], side: str
51
+ ) -> dict[tuple[str | int, ...], dict[str, Value]]:
52
+ indexed = {}
53
+ for number, row in enumerate(rows, 1):
54
+ if not isinstance(row, Mapping):
55
+ msg = f"{side} row {number}: expected a mapping"
56
+ raise ValueError(msg) # noqa: TRY004 # input errors share the public ValueError contract
57
+ snapshot = dict(row)
58
+ cells: list[str | int] = []
59
+ for column in keys:
60
+ if column not in snapshot:
61
+ msg = f"{side} row {number}: missing key column {column!r}"
62
+ raise ValueError(msg)
63
+ cell = snapshot[column]
64
+ if (
65
+ isinstance(cell, bool)
66
+ or not isinstance(cell, (str, int))
67
+ or (isinstance(cell, str) and not cell.strip())
68
+ ):
69
+ msg = f"{side} row {number}: key column {column!r} must be a nonblank string or integer"
70
+ raise ValueError(msg)
71
+ cells.append(cell)
72
+ key = tuple(cells)
73
+ if key in indexed:
74
+ msg = f"{side} row {number}: duplicate key {key!r}"
75
+ raise ValueError(msg)
76
+ indexed[key] = snapshot
77
+ return indexed
@@ -285,6 +285,7 @@ def _get(source: Source, previous: FetchRecord | None, user_agent: str, folder:
285
285
  msg = f"{source['id']}: {error}"
286
286
  raise ValueError(msg) from error
287
287
  except urllib.error.HTTPError as error:
288
+ error.close()
288
289
  # urllib raises a 304 like an error. Only a conditional request can get one.
289
290
  if error.code == HTTPStatus.NOT_MODIFIED and previous and conditional:
290
291
  return previous
@@ -321,6 +322,8 @@ def _archive(source: Source, user_agent: str) -> str:
321
322
  # The archive redirects to the snapshot, or names it in Content-Location.
322
323
  snapshot = urljoin(response.url, response.headers.get("Content-Location", ""))
323
324
  except (*_TRANSIENT, ValueError) as error:
325
+ if isinstance(error, urllib.error.HTTPError):
326
+ error.close()
324
327
  _logger.warning("%s: the Internet Archive did not snapshot %s (%s)", source["id"], url, error)
325
328
  return ""
326
329
  if not snapshot.startswith(_SNAPSHOT):
@@ -376,8 +379,8 @@ def fetch(
376
379
  Every source is tried. Raises FetchError after the loop when any failed, listing each
377
380
  with its reason; nothing is written for those. A source fails for a download over its
378
381
  `max_bytes` (default 200 MiB), bytes that miss the `sha256` the manifest pins, or an
379
- error that outlasts its retries. Raises OSError at once when another fetch holds the
380
- lock on `raw`.
382
+ error that outlasts its retries. Raises FetchBusyError (an OSError) at once when
383
+ another fetch holds the lock on `raw`.
381
384
 
382
385
  `only` restricts the fetch to those source ids, and leaves the others as they are.
383
386
  Raises ValueError for an id the manifest does not have.
@@ -107,6 +107,10 @@ class FetchError(OSError):
107
107
  self.failures = failures # one line per source that did not
108
108
 
109
109
 
110
+ class FetchBusyError(OSError):
111
+ """Another process holds the fetch lock on this raw folder."""
112
+
113
+
110
114
  def _write_atomic(path: Path, data: bytes) -> None:
111
115
  """Write `data` to `path` as `_replacing` does."""
112
116
  with _replacing(path) as fh:
@@ -294,7 +298,7 @@ def _lock(raw: Path) -> Generator[None]:
294
298
  fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
295
299
  except (BlockingIOError, PermissionError) as error: # held elsewhere; other OSErrors propagate
296
300
  msg = f"another fetch is already running in {raw.as_posix()}"
297
- raise OSError(msg) from error
301
+ raise FetchBusyError(msg) from error
298
302
  try:
299
303
  for stale in raw.glob(".*.part"):
300
304
  with contextlib.suppress(OSError): # a scanner holding it, or a directory of that name
@@ -408,7 +412,8 @@ def record(
408
412
  Raises ValueError for a source that is not implemented, a URL with a user name or
409
413
  password, a time without a time zone or in the future, other `parameters`, a path that
410
414
  is not a regular file, a file over the source's `max_bytes`, or bytes that miss the
411
- manifest's `sha256` pin. Raises OSError when another fetch holds the lock on `raw`.
415
+ manifest's `sha256` pin. Raises FetchBusyError (an OSError) when another fetch holds
416
+ the lock on `raw`.
412
417
  """
413
418
  return record_file(
414
419
  source,
File without changes