sourceledger 0.5.0__tar.gz → 0.5.1__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.5.1
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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sourceledger"
3
- version = "0.5.0"
3
+ version = "0.5.1"
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"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sourceledger"
3
- version = "0.5.0"
3
+ version = "0.5.1"
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"
@@ -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
@@ -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
File without changes