sourceledger 0.5.0__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.0
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.0"
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.0"
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",
@@ -373,6 +373,8 @@ def build_sources(
373
373
  """Build outputs with row counts for tables, or None for unchanged file copies."""
374
374
  _check_output_format(output_format)
375
375
  _check_name(name)
376
+ # Before any output is written: a broken pyproject.toml must not cost a whole build.
377
+ name = name or _package_name()
376
378
  selected = {s["id"] for s in select(sources, only)}
377
379
  earlier = {} if only is None else _listed(processed / DATAPACKAGE)
378
380
  processed.mkdir(parents=True, exist_ok=True)
@@ -390,7 +392,7 @@ def build_sources(
390
392
  record, fields, count = _build_one(source, raw, out, parse)
391
393
  written.append((out, count))
392
394
  resources.append(_resource(source, record, fields, out))
393
- package = {"$schema": _DATAPACKAGE_PROFILE, "name": name or _package_name(), "resources": resources}
395
+ package = {"$schema": _DATAPACKAGE_PROFILE, "name": name, "resources": resources}
394
396
  _write_atomic(processed / DATAPACKAGE, json_bytes(package))
395
397
  return written
396
398
 
@@ -435,8 +437,8 @@ def _build_one(source: Source, raw: Path, out: Path, parse: Parser) -> tuple[Fet
435
437
  if compressed:
436
438
  stream.close()
437
439
  else:
438
- # NOTE: other formats and custom parsers hold the whole file and its rows
439
- # in memory, as a Parser returns lists; stream them too once such sources outgrow memory.
440
+ # NOTE: other formats and custom parsers hold the whole file in memory, and the
441
+ # built-in ones their rows too; stream them once such sources outgrow memory.
440
442
  fh.seek(0)
441
443
  columns, rows = parse(source, fh.read())
442
444
  count = _write_rows(source, out, stamp, columns, rows)
@@ -531,7 +533,7 @@ def _package_name() -> str:
531
533
  project = tomllib.load(fh).get("project")
532
534
  except FileNotFoundError:
533
535
  project = None
534
- except tomllib.TOMLDecodeError as error:
536
+ except (OSError, tomllib.TOMLDecodeError, UnicodeDecodeError) as error:
535
537
  msg = f"pyproject.toml: {error}; fix it, or set name in sources.toml"
536
538
  raise ValueError(msg) from None
537
539
  named = project.get("name") if isinstance(project, dict) else None
@@ -205,7 +205,6 @@ def _parser(prog: str, manifest: Path) -> argparse.ArgumentParser:
205
205
  sub["release"].add_argument(
206
206
  "--codemeta",
207
207
  type=Path,
208
- default=CODEMETA,
209
208
  metavar="PATH",
210
209
  help="read the dataset's name, licence and authors from this CodeMeta file (default: ./codemeta.json)",
211
210
  )
@@ -236,7 +235,7 @@ def _check_release_args(args: argparse.Namespace) -> None:
236
235
  args.parser.error("--check writes nothing; drop --dry-run")
237
236
  if args.check is not None and args.manifest != args.parser.get_default("manifest"):
238
237
  args.parser.error("--check reads no manifest; drop --manifest")
239
- if args.check is not None and args.codemeta != CODEMETA:
238
+ if args.check is not None and args.codemeta is not None:
240
239
  args.parser.error("--check reads no codemeta.json; drop --codemeta")
241
240
 
242
241
 
@@ -544,7 +543,8 @@ def _build_stage(run: _Run) -> list[str]:
544
543
  def _validate_stage(run: _Run) -> list[str]:
545
544
  sources = _sources(run)
546
545
  output_format = load_output_format(run.args.manifest)
547
- return _report_problems(run, validate(sources, only=run.args.only, output_format=output_format))
546
+ name = load_package_name(run.args.manifest)
547
+ return _report_problems(run, validate(sources, only=run.args.only, output_format=output_format, name=name))
548
548
 
549
549
 
550
550
  def _status_stage(run: _Run) -> list[str]:
@@ -592,7 +592,8 @@ def _release_stage(run: _Run) -> list[str]:
592
592
  run.args.path,
593
593
  formats=load_release_formats(run.args.manifest),
594
594
  output_format=load_output_format(run.args.manifest),
595
- codemeta=run.args.codemeta,
595
+ codemeta=run.args.codemeta or CODEMETA,
596
+ name=load_package_name(run.args.manifest),
596
597
  dry_run=run.args.dry_run,
597
598
  )
598
599
  except ReleaseError as error: # refused input or findings: the stage's result, as for --check
@@ -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,
@@ -55,7 +55,9 @@ _ZENODO_FILES = 100
55
55
 
56
56
  # The codemeta.json terms each format copies, and those it cannot do without. All are
57
57
  # schema.org terms, so they keep their names. Croissant names the authors `creator`.
58
- _TERMS = ("name", "description", "license", "version", "identifier", "datePublished", "url")
58
+ _TERMS = ("name", "description", "license", "version", "identifier", "datePublished", "url", "keywords", "publisher")
59
+ # People, each given an @id: authors, and contributors who are not authors.
60
+ _ROLES = ("author", "contributor")
59
61
  _REQUIRED = {
60
62
  _FORMAT_ROCRATE: ("name", "description", "license", "datePublished"),
61
63
  _FORMAT_CROISSANT: ("name", "description", "license", "url"),
@@ -142,6 +144,7 @@ def release(
142
144
  processed: Path = PROCESSED,
143
145
  codemeta: Path = CODEMETA,
144
146
  output_format: str = "csv",
147
+ name: str | None = None,
145
148
  dry_run: bool = False,
146
149
  ) -> dict[str, Any]:
147
150
  """Write a release folder at `out_dir` from a validated build, check it, and return what it holds.
@@ -151,7 +154,8 @@ def release(
151
154
  when `formats` (any iterable of their names) asks for them, and `SHA256SUMS`, written last.
152
155
  The descriptive fields come from `codemeta`. The folder is written beside `out_dir` and moved
153
156
  into place only once every check passed, so a refused release leaves nothing at `out_dir`.
154
- `dry_run` checks the input and returns what would be written, without writing.
157
+ `dry_run` checks the input and returns what would be written, without writing. `name` is
158
+ passed to `validate`.
155
159
 
156
160
  The result has `files` (paths in the folder), `excluded` (source ids), `formats` (each
157
161
  optional format "written" or "skipped") and `validators` (`file`, `name`, `version` of each
@@ -167,7 +171,7 @@ def release(
167
171
  msg = f"formats must be drawn from {list(RELEASE_FORMATS)}, not {formats!r}"
168
172
  raise ValueError(msg)
169
173
  formats = [fmt for fmt in RELEASE_FORMATS if fmt in wanted]
170
- if problems := validate(sources, raw=raw, processed=processed, output_format=output_format):
174
+ if problems := validate(sources, raw=raw, processed=processed, output_format=output_format, name=name):
171
175
  raise ReleaseError(problems)
172
176
  if out_dir.exists() and (not out_dir.is_dir() or any(out_dir.iterdir())):
173
177
  msg = f"{out_dir.as_posix()} already exists; a release goes into a new folder"
@@ -381,11 +385,28 @@ def _described(codemeta: Path, formats: Collection[str]) -> dict[str, Any]:
381
385
  ]:
382
386
  raise ReleaseError(missing)
383
387
  described = {term: _keywords(meta[term]) for term in _TERMS if meta.get(term)}
384
- if authors := _keywords(meta.get("author")):
385
- described["author"] = authors if isinstance(authors, list) else [authors]
388
+ if publishers := described.get("publisher"):
389
+ named = [_organization(p) for p in _as_list(publishers)]
390
+ described["publisher"] = named if isinstance(publishers, list) else named[0]
391
+ for role in _ROLES:
392
+ if people := _keywords(meta.get(role)):
393
+ described[role] = _as_list(people)
386
394
  return described
387
395
 
388
396
 
397
+ def _organization(publisher: object) -> object:
398
+ """A publisher as both validators want it: text, or an object without a type, becomes an Organization."""
399
+ if isinstance(publisher, str):
400
+ return {"@type": "Organization", "name": publisher}
401
+ if isinstance(publisher, dict):
402
+ return {"@type": "Organization", **publisher} # a @type it has wins
403
+ return publisher
404
+
405
+
406
+ def _as_list(value: object) -> list[Any]:
407
+ return value if isinstance(value, list) else [value]
408
+
409
+
389
410
  # CodeMeta 3's context makes these aliases of the JSON-LD keywords; RO-Crate's and Croissant's do not.
390
411
  _ALIASES = {"id": "@id", "type": "@type"}
391
412
 
@@ -493,13 +514,13 @@ def _media_type(resource: dict[str, Any]) -> str:
493
514
  return resource.get("mediatype", "application/octet-stream")
494
515
 
495
516
 
496
- def _people(authors: list[Any]) -> tuple[list[dict[str, str]], list[dict[str, Any]]]:
497
- """References to the authors, and the authors as entities, each with an @id (`#author-<n>` without one)."""
517
+ def _people(people: list[Any], role: str = "author") -> tuple[list[dict[str, str]], list[dict[str, Any]]]:
518
+ """References to the people, and the people as entities, each with an @id (`#<role>-<n>` without one)."""
498
519
  entities = [
499
- {**author, "@id": author.get("@id") or f"#author-{n}"}
500
- if isinstance(author, dict)
501
- else {"@id": f"#author-{n}", "name": str(author)}
502
- for n, author in enumerate(authors, 1)
520
+ {**person, "@id": person.get("@id") or f"#{role}-{n}"}
521
+ if isinstance(person, dict)
522
+ else {"@id": f"#{role}-{n}", "name": str(person)}
523
+ for n, person in enumerate(people, 1)
503
524
  ]
504
525
  for entity in entities:
505
526
  entity.setdefault("@type", "Person")
@@ -518,9 +539,17 @@ def _ro_crate(
518
539
  """An RO-Crate 1.3 description: the root dataset, a File per shipped output, and every source with its fetch."""
519
540
  root: dict[str, Any] = {"@id": "./", "@type": "Dataset"}
520
541
  root.update(described)
521
- authors, people = _people(described.get("author", []))
522
- if authors:
523
- root["author"] = authors
542
+ people: list[dict[str, Any]] = []
543
+ seen: set[str] = set()
544
+ for role in _ROLES:
545
+ refs, entities = _people(described.get(role, []), role)
546
+ if refs:
547
+ root[role] = refs
548
+ # One entity per @id: a person listed twice, or as author and contributor, is one person.
549
+ for entity in entities:
550
+ if entity["@id"] not in seen:
551
+ seen.add(entity["@id"])
552
+ people.append(entity)
524
553
  resources = _by_name(package)
525
554
  files = []
526
555
  for source in shipped:
@@ -653,6 +682,8 @@ def _croissant(described: dict[str, Any], package: dict[str, Any]) -> dict[str,
653
682
  document.update(described)
654
683
  if authors := document.pop("author", None):
655
684
  document["creator"] = _people(authors)[1]
685
+ if contributors := document.get("contributor"):
686
+ document["contributor"] = _people(contributors, "contributor")[1]
656
687
  resources = package["resources"]
657
688
  document["distribution"] = [
658
689
  {
@@ -61,6 +61,7 @@ def validate(
61
61
  processed: Path = PROCESSED,
62
62
  only: Collection[str] | None = None,
63
63
  output_format: str = "csv",
64
+ name: str | None = None,
64
65
  ) -> list[str]:
65
66
  """Check the published output against the manifest and the fetch records, and return one string per problem.
66
67
 
@@ -68,6 +69,8 @@ def validate(
68
69
  output: files no source owns, and the package's list of sources. Raises ValueError for an
69
70
  id the manifest does not have.
70
71
  `output_format` must match the build: CSV by default, or Parquet (needs the parquet extra).
72
+ `name`, the package name sources.toml sets, must be the one datapackage.json has; None skips
73
+ that check, since the fallback names differ between checkouts.
71
74
  """
72
75
  _check_output_format(output_format)
73
76
  selected = select(sources, only)
@@ -99,7 +102,7 @@ def validate(
99
102
  continue
100
103
  problems += _terms_problems(source)
101
104
  problems += _output_problems(source, raw, out, listed.get(sid))
102
- return problems + _package_problems(sources, processed, only, output_format)
105
+ return problems + _package_problems(sources, processed, only, output_format, name)
103
106
 
104
107
 
105
108
  def _built_from(stamp: dict[str, Any], fields: dict[str, Any]) -> bool:
@@ -171,7 +174,7 @@ def _scan(out: Path, stamp: dict[str, str]) -> tuple[bool, bool]:
171
174
 
172
175
 
173
176
  def _package_problems(
174
- sources: list[Source], processed: Path, only: Collection[str] | None, output_format: str
177
+ sources: list[Source], processed: Path, only: Collection[str] | None, output_format: str, name: str | None
175
178
  ) -> list[str]:
176
179
  """Whether datapackage.json lists exactly the implemented sources, each with its output's current hash.
177
180
 
@@ -187,10 +190,15 @@ def _package_problems(
187
190
  except ValueError as error:
188
191
  return [f"{path.as_posix()} is not JSON ({error}); re-run build"]
189
192
  listed = _by_name(package)
193
+ problems = []
194
+ if name is not None and isinstance(package, dict) and package.get("name") != name:
195
+ problems.append(f"{path.as_posix()} names the package {package.get('name')!r}, not {name!r}; re-run build")
190
196
  if only is None and listed.keys() != expected.keys():
191
197
  names = sorted(map(str, listed))
192
- return [f"{path.as_posix()} lists {names}, not the implemented sources {sorted(expected)}; re-run build"]
193
- problems = []
198
+ return [
199
+ *problems,
200
+ f"{path.as_posix()} lists {names}, not the implemented sources {sorted(expected)}; re-run build",
201
+ ]
194
202
  for sid in sorted(checked):
195
203
  out = processed / output_name(expected[sid], output_format)
196
204
  if sid not in listed:
File without changes