citesync 0.3.0__tar.gz → 0.4.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.
Files changed (29) hide show
  1. {citesync-0.3.0 → citesync-0.4.0}/PKG-INFO +7 -5
  2. {citesync-0.3.0 → citesync-0.4.0}/README.md +6 -4
  3. {citesync-0.3.0 → citesync-0.4.0}/pyproject.toml +1 -1
  4. {citesync-0.3.0 → citesync-0.4.0}/pyproject.toml.orig +1 -1
  5. citesync-0.4.0/src/citesync/MAPPING_SOURCE +5 -0
  6. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/check.py +6 -1
  7. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/cli.py +46 -1
  8. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/config.py +20 -0
  9. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/core_metadata.py +13 -8
  10. citesync-0.4.0/src/citesync/export.py +272 -0
  11. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/formats.py +16 -3
  12. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/mapping-local.json +493 -2
  13. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/mapping.schema.json +3 -3
  14. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/playground.py +4 -3
  15. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/playground_exports.py +1 -65
  16. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/research_metadata.py +19 -21
  17. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/rules.py +9 -0
  18. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/write.py +94 -32
  19. citesync-0.3.0/src/citesync/MAPPING_SOURCE +0 -5
  20. {citesync-0.3.0 → citesync-0.4.0}/LICENSE +0 -0
  21. {citesync-0.3.0 → citesync-0.4.0}/NOTICE +0 -0
  22. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/__init__.py +0 -0
  23. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/__main__.py +0 -0
  24. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/codecs.py +0 -0
  25. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/errors.py +0 -0
  26. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/jsonsplice.py +0 -0
  27. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/mapping.py +0 -0
  28. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/positions.py +0 -0
  29. {citesync-0.3.0 → citesync-0.4.0}/src/citesync/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: citesync
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Generate and synchronize software citation files from package metadata. CLI, pre-commit hook and browser playground.
5
5
  Keywords: citation,CITATION.cff,codemeta,zenodo,software-metadata,pre-commit
6
6
  Author: Simon van Lierde
@@ -41,7 +41,7 @@ Status: experimental. It may change in ways that break your code, without notice
41
41
 
42
42
  Questions and bugs: see [CONTRIBUTING.md](https://github.com/simonvanlierde/citesync/blob/main/.github/CONTRIBUTING.md).
43
43
 
44
- Generate software citation files from package metadata, then keep them in sync across CITATION.cff, codemeta.json, .zenodo.json and package manifests. Use the CLI, a pre-commit hook or the [browser playground](https://simonvanlierde.com/citesync/). Field mappings come from CodeMeta's crosswalks, as exported by [codemeta-drift](https://github.com/simonvanlierde/codemeta-drift).
44
+ Generate software citation files from package metadata, then keep them in sync across CITATION.cff, codemeta.json, .zenodo.json and package manifests, including [Typst and Quarto plugin manifests](docs/formats.md#plugin-manifests). Use the CLI, a pre-commit hook or the [browser playground](https://simonvanlierde.com/citesync/). Field mappings come from CodeMeta's crosswalks, as exported by [codemeta-drift](https://github.com/simonvanlierde/codemeta-drift).
45
45
 
46
46
  ## Usage
47
47
 
@@ -54,6 +54,7 @@ citesync check --source pyproject.toml
54
54
  citesync write --diff # print what write would change, and change nothing
55
55
  citesync write # rewrite the other files to agree with the source
56
56
  citesync init # write a CITATION.cff from codemeta.json, .zenodo.json and the manifests
57
+ citesync export --format apa # print a citation: apa, bibtex, csl-json, jsonld, cff, codemeta or zenodo
57
58
  citesync explain version-mismatch # what a rule checks and how to fix it
58
59
  citesync config # the config in use, and the file it came from
59
60
  ```
@@ -73,9 +74,10 @@ A config is optional. A one-line `citesync.toml` is `ignore = ["description-mism
73
74
  - [How write works](https://github.com/simonvanlierde/citesync/blob/main/docs/write.md): what it changes and what it leaves alone.
74
75
  - [Supported files](https://github.com/simonvanlierde/citesync/blob/main/docs/formats.md): which files citesync reads, updates and creates, including read-only Python distribution, R and Julia metadata.
75
76
  - [How init works](https://github.com/simonvanlierde/citesync/blob/main/docs/init.md): where a new CITATION.cff takes each field from.
77
+ - [Citation exports](https://github.com/simonvanlierde/citesync/blob/main/docs/export.md): BibTeX, CSL-JSON, APA and schema.org JSON-LD files kept in step with the source.
76
78
  - [Rules](https://github.com/simonvanlierde/citesync/blob/main/docs/rules.md): each rule id, what it checks and how to fix it.
77
79
  - [Configuration](https://github.com/simonvanlierde/citesync/blob/main/docs/config.md): where config goes, and every key.
78
- - [Use citation exports with Pandoc](https://github.com/simonvanlierde/citesync/blob/main/docs/pandoc.md): cite software from the playground’s CSL-JSON or BibTeX files.
80
+ - [Use citation exports with Pandoc](https://github.com/simonvanlierde/citesync/blob/main/docs/pandoc.md): cite software from the CSL-JSON or BibTeX files `citesync export` or the playground makes.
79
81
  - [Output formats](https://github.com/simonvanlierde/citesync/blob/main/docs/output.md): JSON, GitHub annotations and SARIF.
80
82
  - [Tested on real repositories](https://github.com/simonvanlierde/citesync/blob/main/docs/tested-repositories.md): what citesync reports on five public repositories.
81
83
 
@@ -90,13 +92,13 @@ For [prek](https://prek.j178.dev) or [pre-commit](https://pre-commit.com), in `.
90
92
  ```yaml
91
93
  repos:
92
94
  - repo: https://github.com/simonvanlierde/citesync
93
- rev: v0.3.0
95
+ rev: v0.4.0
94
96
  hooks:
95
97
  - id: citesync
96
98
  - id: citesync-write
97
99
  ```
98
100
 
99
- The `citesync` hook runs when a commit changes a supported metadata file or a citesync config, at any depth. It checks every file, not only the staged ones, and fails the commit on an error finding. The `citesync-write` hook runs only when you ask for it: `prek run citesync-write --stage manual --all-files`.
101
+ The `citesync` hook runs when a commit changes a supported metadata file, a citesync config or a file with an export suffix (`.bib`, `.csl.json`, `.apa.txt`, `.jsonld`), at any depth. It checks every file, not only the staged ones, and fails the commit on an error finding. The `citesync-write` hook runs only when you ask for it: `prek run citesync-write --stage manual --all-files`.
100
102
 
101
103
  ## Development
102
104
 
@@ -11,7 +11,7 @@ Status: experimental. It may change in ways that break your code, without notice
11
11
 
12
12
  Questions and bugs: see [CONTRIBUTING.md](https://github.com/simonvanlierde/citesync/blob/main/.github/CONTRIBUTING.md).
13
13
 
14
- Generate software citation files from package metadata, then keep them in sync across CITATION.cff, codemeta.json, .zenodo.json and package manifests. Use the CLI, a pre-commit hook or the [browser playground](https://simonvanlierde.com/citesync/). Field mappings come from CodeMeta's crosswalks, as exported by [codemeta-drift](https://github.com/simonvanlierde/codemeta-drift).
14
+ Generate software citation files from package metadata, then keep them in sync across CITATION.cff, codemeta.json, .zenodo.json and package manifests, including [Typst and Quarto plugin manifests](docs/formats.md#plugin-manifests). Use the CLI, a pre-commit hook or the [browser playground](https://simonvanlierde.com/citesync/). Field mappings come from CodeMeta's crosswalks, as exported by [codemeta-drift](https://github.com/simonvanlierde/codemeta-drift).
15
15
 
16
16
  ## Usage
17
17
 
@@ -24,6 +24,7 @@ citesync check --source pyproject.toml
24
24
  citesync write --diff # print what write would change, and change nothing
25
25
  citesync write # rewrite the other files to agree with the source
26
26
  citesync init # write a CITATION.cff from codemeta.json, .zenodo.json and the manifests
27
+ citesync export --format apa # print a citation: apa, bibtex, csl-json, jsonld, cff, codemeta or zenodo
27
28
  citesync explain version-mismatch # what a rule checks and how to fix it
28
29
  citesync config # the config in use, and the file it came from
29
30
  ```
@@ -43,9 +44,10 @@ A config is optional. A one-line `citesync.toml` is `ignore = ["description-mism
43
44
  - [How write works](https://github.com/simonvanlierde/citesync/blob/main/docs/write.md): what it changes and what it leaves alone.
44
45
  - [Supported files](https://github.com/simonvanlierde/citesync/blob/main/docs/formats.md): which files citesync reads, updates and creates, including read-only Python distribution, R and Julia metadata.
45
46
  - [How init works](https://github.com/simonvanlierde/citesync/blob/main/docs/init.md): where a new CITATION.cff takes each field from.
47
+ - [Citation exports](https://github.com/simonvanlierde/citesync/blob/main/docs/export.md): BibTeX, CSL-JSON, APA and schema.org JSON-LD files kept in step with the source.
46
48
  - [Rules](https://github.com/simonvanlierde/citesync/blob/main/docs/rules.md): each rule id, what it checks and how to fix it.
47
49
  - [Configuration](https://github.com/simonvanlierde/citesync/blob/main/docs/config.md): where config goes, and every key.
48
- - [Use citation exports with Pandoc](https://github.com/simonvanlierde/citesync/blob/main/docs/pandoc.md): cite software from the playground’s CSL-JSON or BibTeX files.
50
+ - [Use citation exports with Pandoc](https://github.com/simonvanlierde/citesync/blob/main/docs/pandoc.md): cite software from the CSL-JSON or BibTeX files `citesync export` or the playground makes.
49
51
  - [Output formats](https://github.com/simonvanlierde/citesync/blob/main/docs/output.md): JSON, GitHub annotations and SARIF.
50
52
  - [Tested on real repositories](https://github.com/simonvanlierde/citesync/blob/main/docs/tested-repositories.md): what citesync reports on five public repositories.
51
53
 
@@ -60,13 +62,13 @@ For [prek](https://prek.j178.dev) or [pre-commit](https://pre-commit.com), in `.
60
62
  ```yaml
61
63
  repos:
62
64
  - repo: https://github.com/simonvanlierde/citesync
63
- rev: v0.3.0
65
+ rev: v0.4.0
64
66
  hooks:
65
67
  - id: citesync
66
68
  - id: citesync-write
67
69
  ```
68
70
 
69
- The `citesync` hook runs when a commit changes a supported metadata file or a citesync config, at any depth. It checks every file, not only the staged ones, and fails the commit on an error finding. The `citesync-write` hook runs only when you ask for it: `prek run citesync-write --stage manual --all-files`.
71
+ The `citesync` hook runs when a commit changes a supported metadata file, a citesync config or a file with an export suffix (`.bib`, `.csl.json`, `.apa.txt`, `.jsonld`), at any depth. It checks every file, not only the staged ones, and fails the commit on an error finding. The `citesync-write` hook runs only when you ask for it: `prek run citesync-write --stage manual --all-files`.
70
72
 
71
73
  ## Development
72
74
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "citesync"
3
- version = "0.3.0"
3
+ version = "0.4.0"
4
4
  description = "Generate and synchronize software citation files from package metadata. CLI, pre-commit hook and browser playground."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "citesync"
3
- version = "0.3.0"
3
+ version = "0.4.0"
4
4
  description = "Generate and synchronize software citation files from package metadata. CLI, pre-commit hook and browser playground."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -0,0 +1,5 @@
1
+ # Vendored from simonvanlierde/codemeta-drift; tests/test_mapping.py checks the sha256 lines.
2
+ tag v0.5.0
3
+ commit dcc1fc825d38f0272767a250d80d53fdd5ba7713
4
+ sha256 69956d605d3143d660c553178cef185d96c63b2a2aab6e3e0dcc4778b9a82435 mapping-local.json examples/mapping-3.1.json
5
+ sha256 00e051f13cddfe95d338f6367a5b086f7f268e4f2d2c5ef1a6df7e5933a8bf5e mapping.schema.json src/codemeta_drift/mapping.schema.json
@@ -136,7 +136,12 @@ def check(root: Path, config: Config) -> tuple[list[Finding], int, list[str]]:
136
136
  """Every finding for the repo at ``root``, sorted, the number of files checked, and the unused ignore entries."""
137
137
  mapping = load_mapping()
138
138
  docs, read = read_docs(root, config, mapping)
139
- found, unused = findings(docs, [*read, *version_behind_tag(docs[0], git_tags(root))], config)
139
+ extra = [*read, *version_behind_tag(docs[0], git_tags(root))]
140
+ if config.exports:
141
+ from citesync.export import stale # noqa: PLC0415
142
+
143
+ extra += stale(root, docs, config)
144
+ found, unused = findings(docs, extra, config)
140
145
  if any(f.file and f.term for f in found): # a check with nothing to point at reads no file twice
141
146
  from citesync.positions import place # noqa: PLC0415
142
147
 
@@ -22,6 +22,9 @@ from citesync.errors import CheckError
22
22
  from citesync.rules import DOCS_URL, RULES, explain, url
23
23
 
24
24
  JSON_VERSION = 1
25
+ # the keys of citesync.export._WRITERS, spelled out so the parser needs no import of that module
26
+ _EXPORT_FORMATS = ("bibtex", "csl-json", "apa", "jsonld")
27
+ _CITATION_FILES = ("cff", "codemeta", "zenodo") # made by write's builders, so never under exports
25
28
  _ANSI = {"error": "1;31", "warning": "1;33", "info": "1;34"}
26
29
  _GITHUB_LEVEL = {"error": "error", "warning": "warning", "info": "notice"}
27
30
  _SARIF_LEVEL = {"error": "error", "warning": "warning", "info": "note"}
@@ -97,7 +100,8 @@ def _directory(value: str) -> Path:
97
100
 
98
101
 
99
102
  _DESCRIPTION = """Check that CITATION.cff, codemeta.json, .zenodo.json and the package manifests
100
- (pyproject.toml, Cargo.toml, package.json) agree, and rewrite them to match one source file."""
103
+ (pyproject.toml, Cargo.toml, package.json, typst.toml, _extension.yml) agree, and rewrite them
104
+ to match one source file."""
101
105
  _EPILOG = f"""exit codes:
102
106
  0 no error finding (warnings and info don't fail)
103
107
  1 an error finding; with write --diff, a change to make or a file it can't read
@@ -157,6 +161,17 @@ def _parser() -> argparse.ArgumentParser:
157
161
  " holds it: --source, then the files in the order above.",
158
162
  )
159
163
  init_.add_argument("--diff", action="store_true", help="print the new file as a unified diff and write nothing")
164
+ export = "print a citation or citation file made from the source, writing nothing"
165
+ export_ = sub.add_parser(
166
+ "export",
167
+ parents=[root],
168
+ help=export,
169
+ description=f"{export[0].upper()}{export[1:]}.\n"
170
+ "List bibtex, csl-json, apa or jsonld files under exports to keep them in step.",
171
+ )
172
+ export_.add_argument(
173
+ "--format", choices=_EXPORT_FORMATS + _CITATION_FILES, required=True, help="the citation format"
174
+ )
160
175
  sub.add_parser("config", parents=[root], help="print the config in use and where it came from")
161
176
  rules = sub.add_parser("rules", help="list the rules")
162
177
  rules.add_argument("--format", choices=("text", "json"), default="text", help="output format (default: text)")
@@ -178,6 +193,8 @@ def main(argv: list[str] | None = None) -> int: # noqa: C901, PLR0911 - a retur
178
193
  return 0
179
194
  if args.command == "init":
180
195
  return _init(args.root, config, diff=args.diff)
196
+ if args.command == "export":
197
+ return _export(args.root, config, args.format)
181
198
  if getattr(args, "diff", False):
182
199
  return _write_diff(args.root, config)
183
200
  written, skipped, fixed = _write(args.root, config) if args.command == "write" else ({}, {}, None)
@@ -271,6 +288,34 @@ def _write_diff(root: Path, config: Config) -> int:
271
288
  return 1 if texts or unreadable else 0
272
289
 
273
290
 
291
+ def _export(root: Path, config: Config, fmt: str) -> int:
292
+ """Print the source's citation in ``fmt``; what it left out goes to stderr."""
293
+ from citesync.check import read_docs # noqa: PLC0415
294
+ from citesync.export import record, render # noqa: PLC0415
295
+ from citesync.mapping import load_mapping # noqa: PLC0415
296
+ from citesync.write import _merged, citation_file, union # noqa: PLC0415
297
+
298
+ mapping = load_mapping()
299
+ if fmt == "cff": # built as init builds it, so it needs no CITATION.cff to read
300
+ text, skipped = citation_file(fmt, root, config, _merged(root, config, mapping), mapping)
301
+ notes = [f"leaving out {term}: {why}" for term, why in skipped.items()]
302
+ else:
303
+ docs, read = read_docs(root, config, mapping)
304
+ if not docs[0].readable:
305
+ bad = next(f for f in read if f.file == docs[0].path and f.rule == "unreadable")
306
+ msg = f"{bad.where}: {bad.message}"
307
+ raise CheckError(msg)
308
+ if fmt in _CITATION_FILES:
309
+ text, skipped = citation_file(fmt, root, config, replace(docs[0], record=union(docs, config)), mapping)
310
+ notes = [f"leaving out {term}: {why}" for term, why in skipped.items()]
311
+ else:
312
+ text, notes = render(fmt, record(docs))
313
+ sys.stdout.write(text)
314
+ for note in notes:
315
+ print(note, file=sys.stderr)
316
+ return 0
317
+
318
+
274
319
  def _init(root: Path, config: Config, *, diff: bool) -> int:
275
320
  """Write a new CITATION.cff, or with ``diff`` print it as a diff from nothing."""
276
321
  from citesync.write import init # noqa: PLC0415
@@ -24,6 +24,7 @@ class Config:
24
24
  files: tuple[str, ...] | None = None
25
25
  manifests: tuple[str, ...] | None = None
26
26
  write_manifests: tuple[str, ...] = ()
27
+ exports: tuple[str, ...] = ()
27
28
  zenodo_contributor_type: str | None = None
28
29
  keywords_case_sensitive: bool = False
29
30
  keywords_ignore_separators: bool = False
@@ -155,6 +156,10 @@ def _path(value: object, names: dict[str, str], origin: str, key: str) -> str:
155
156
  if not isinstance(value, str) or PurePosixPath(value).name not in names:
156
157
  msg = f"{origin}: {key} must name one of {', '.join(names)}, got {value!r}"
157
158
  raise CheckError(msg)
159
+ return _relative(value, origin, key)
160
+
161
+
162
+ def _relative(value: str, origin: str, key: str) -> str:
158
163
  path = PurePosixPath(value)
159
164
  if path.is_absolute() or ".." in path.parts:
160
165
  msg = f"{origin}: {key} {value!r} must be relative to the repo root, inside it"
@@ -203,6 +208,19 @@ def _write_manifests(value: object, origin: str) -> tuple[str, ...]:
203
208
  return MANIFEST_TERMS if "all" in items else tuple(items)
204
209
 
205
210
 
211
+ def _exports(value: object, origin: str) -> tuple[str, ...]:
212
+ from citesync.export import SUFFIXES, format_of # noqa: PLC0415 - only when a config lists exports
213
+
214
+ if not isinstance(value, list):
215
+ msg = f"{origin}: exports must be a list of paths"
216
+ raise CheckError(msg)
217
+ for item in value:
218
+ if not isinstance(item, str) or format_of(item) is None:
219
+ msg = f"{origin}: exports entry {item!r} must end in one of {', '.join(SUFFIXES)}"
220
+ raise CheckError(msg)
221
+ return tuple(dict.fromkeys(_relative(item, origin, "exports") for item in value))
222
+
223
+
206
224
  def _ignore(value: object, origin: str) -> tuple[str, ...]:
207
225
  if not isinstance(value, list) or not all(isinstance(i, str) for i in value):
208
226
  msg = f"{origin}: ignore must be a list of rule ids, got {value!r}"
@@ -225,6 +243,7 @@ _PARSE: dict[str, Callable[[object, str], Any]] = {
225
243
  "files": lambda value, origin: _paths(value, CITATION_FILES, origin, "files"),
226
244
  "manifests": lambda value, origin: _paths(value, MANIFESTS, origin, "manifests"),
227
245
  "write-manifests": _write_manifests,
246
+ "exports": _exports,
228
247
  "zenodo-contributor-type": _zenodo_contributor_type,
229
248
  "keywords-case-sensitive": lambda value, origin: _bool(value, origin, "keywords-case-sensitive"),
230
249
  "keywords-ignore-separators": lambda value, origin: _bool(value, origin, "keywords-ignore-separators"),
@@ -247,6 +266,7 @@ def render(config: Config) -> str:
247
266
  if config.manifests is not None
248
267
  else "# manifests: not set, so every release manifest at the repo root",
249
268
  f"write-manifests = {json.dumps(list(config.write_manifests))}",
269
+ f"exports = {json.dumps(list(config.exports))}",
250
270
  f"zenodo-contributor-type = {json.dumps(config.zenodo_contributor_type)}"
251
271
  if config.zenodo_contributor_type is not None
252
272
  else "# zenodo-contributor-type: not set, so new contributors need a hand edit",
@@ -44,9 +44,8 @@ def parse(text: str, rel: str) -> dict[str, Any]: # noqa: C901 - independent op
44
44
  Version(project["version"])
45
45
  except (InvalidName, InvalidVersion) as err:
46
46
  raise UnreadableError(rel, f"invalid Name or Version: {err}") from err
47
- description = one("Summary") or one("Description") or message.get_payload()
48
- if isinstance(description, str) and description.strip():
49
- project["description"] = description.strip()
47
+ if description := one("Summary"): # Description and the body hold the README, not a summary
48
+ project["description"] = description
50
49
  if authors := _authors(message, rel):
51
50
  project["authors"] = authors
52
51
  if urls := _urls(message, rel):
@@ -106,22 +105,28 @@ def _authors(message: Message, rel: str) -> list[dict[str, str]]:
106
105
  return list(authors.values())
107
106
 
108
107
 
108
+ # the mapping row's order, labels normalised as the well-known project URLs spec says
109
+ _REPOSITORY_LABELS = ("source", "repository", "sourcecode", "github")
110
+
111
+
109
112
  def _urls(message: Message, rel: str) -> dict[str, str]:
113
+ """The repository URL under the one PEP 621 label the mapping reads, from Project-URL or else Home-page."""
110
114
  urls = {}
111
115
  for raw in message.get_all("Project-URL", []):
112
116
  label, separator, address = str(raw).partition(",")
113
117
  label, address = label.strip(), address.strip()
114
118
  if not separator or not label or not address:
115
119
  raise UnreadableError(rel, "Project-URL must contain a label, comma and URL")
116
- if label in urls and urls[label] != address:
120
+ key = "".join(c for c in label.lower() if c.isalnum()) # as the well-known project URLs spec compares them
121
+ if key in urls and urls[key] != address:
117
122
  raise UnreadableError(rel, f"Project-URL has conflicting values for {label!r}")
118
- urls[label] = address
123
+ urls[key] = address
119
124
  homes = message.get_all("Home-page", [])
120
125
  if len(homes) > 1:
121
126
  raise UnreadableError(rel, "Home-page must appear only once")
122
- if homes:
123
- urls.setdefault("Homepage", str(homes[0]).strip())
124
- return urls
127
+ if repository := next((urls[k] for k in _REPOSITORY_LABELS if k in urls), None):
128
+ return {"Source": repository}
129
+ return {"Homepage": str(homes[0]).strip()} if homes else {}
125
130
 
126
131
 
127
132
  def _header(value: str, rel: str) -> str:
@@ -0,0 +1,272 @@
1
+ """Citations made from the source's record: BibTeX, CSL-JSON, APA 7 and schema.org JSON-LD.
2
+
3
+ A repo lists the files in the ``exports`` setting; the suffix picks the format. ``write``
4
+ keeps them in step and ``check`` reports one that isn't (``export-stale``).
5
+ """
6
+
7
+ import datetime as dt
8
+ import json
9
+ import re
10
+ import unicodedata
11
+ from pathlib import Path, PurePosixPath
12
+ from typing import Any
13
+
14
+ from citesync.check import Finding
15
+ from citesync.config import Config
16
+ from citesync.errors import CheckError
17
+ from citesync.formats import Doc, Person
18
+ from citesync.mapping import load_mapping
19
+
20
+ # suffix: format; the longest suffix is tried first, so citation.csl.json is never plain JSON
21
+ SUFFIXES = {".csl.json": "csl-json", ".apa.txt": "apa", ".bib": "bibtex", ".jsonld": "jsonld"}
22
+ # The file each format goes to when no path is given: the playground's names.
23
+ DEFAULT_NAMES = {
24
+ "csl-json": "citation.csl.json",
25
+ "apa": "citation.apa.txt",
26
+ "bibtex": "citation.bib",
27
+ "jsonld": "schema.jsonld",
28
+ }
29
+
30
+ _TEX = {
31
+ "\\": r"\textbackslash{}",
32
+ "{": r"\{",
33
+ "}": r"\}",
34
+ "&": r"\&",
35
+ "%": r"\%",
36
+ "$": r"\$",
37
+ "#": r"\#",
38
+ "_": r"\_",
39
+ "~": r"\textasciitilde{}",
40
+ "^": r"\textasciicircum{}",
41
+ }
42
+ # Latin letters NFKD leaves whole, so they would drop out of an ASCII key
43
+ _LATIN = str.maketrans(
44
+ {"ł": "l", "ø": "o", "đ": "d", "ħ": "h", "\u0131": "i", "ß": "ss", "æ": "ae", "œ": "oe", "þ": "th"}
45
+ )
46
+ _SPDX_ID = re.compile(r"[A-Za-z0-9.+-]+")
47
+
48
+
49
+ def format_of(path: str) -> str | None:
50
+ """The export format a path's suffix names, or None."""
51
+ name = PurePosixPath(path).name
52
+ return next((fmt for suffix, fmt in SUFFIXES.items() if name.endswith(suffix) and name != suffix), None)
53
+
54
+
55
+ def text(path: str, rec: dict[str, Any]) -> str:
56
+ """The text the export at ``path`` should hold; config has checked its suffix."""
57
+ return render(str(format_of(path)), rec)[0]
58
+
59
+
60
+ def record(docs: list[Doc]) -> dict[str, Any]:
61
+ """Each term from the first doc that holds it, the source first: what the exports cite.
62
+
63
+ An unreadable doc has an empty record, so it gives nothing.
64
+ """
65
+ merged: dict[str, Any] = {}
66
+ for doc in docs:
67
+ for term, value in doc.record.items():
68
+ merged.setdefault(term, value)
69
+ return merged
70
+
71
+
72
+ def render(fmt: str, rec: dict[str, Any]) -> tuple[str, list[str]]:
73
+ """The export's text in ``fmt``, and notes on what it left out. Never invents a release date.
74
+
75
+ Raises:
76
+ CheckError: when the record has no title.
77
+ """
78
+ if not rec.get("name"):
79
+ msg = "no file gives a title, which a citation needs"
80
+ raise CheckError(msg)
81
+ day, notes = _date(rec.get("datePublished")), []
82
+ if rec.get("datePublished") and day is None and fmt != "jsonld": # JSON-LD carries the date as written
83
+ notes.append(
84
+ "BibTeX, CSL-JSON and APA: release date omitted because it is not a YYYY, YYYY-MM or YYYY-MM-DD date."
85
+ )
86
+ return _WRITERS[fmt](rec, day), notes
87
+
88
+
89
+ def _date(value: str | None) -> tuple[int, ...] | None:
90
+ """``2026-10-31`` as ``(2026, 10, 31)``, ``2026`` as ``(2026,)``; None for anything else."""
91
+ match = re.fullmatch(r"(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?", value or "")
92
+ if not match:
93
+ return None
94
+ parts = tuple(int(p) for p in match.groups() if p)
95
+ try:
96
+ dt.date(*parts, *(1,) * (3 - len(parts)))
97
+ except ValueError:
98
+ return None
99
+ return parts
100
+
101
+
102
+ def citations(rec: dict[str, Any]) -> tuple[dict[str, str], list[str]]:
103
+ """Every format under its default name, and the notes once each."""
104
+ files, notes = {}, []
105
+ for fmt, name in DEFAULT_NAMES.items():
106
+ files[name], left = render(fmt, rec)
107
+ notes += left
108
+ return files, list(dict.fromkeys(notes))
109
+
110
+
111
+ def tex(text: str) -> str:
112
+ """Escape a literal UTF-8 metadata value for a braced BibTeX field."""
113
+ return "".join(_TEX.get(char, char) for char in " ".join(text.split()))
114
+
115
+
116
+ def key(rec: dict[str, Any]) -> str:
117
+ """The citation key: the title up to any subtitle, in lowercase ASCII with dashes (``credit-matrix``)."""
118
+ title = re.split(":|\\s[-\u2013\u2014]\\s", rec.get("name", ""), maxsplit=1)[0]
119
+ ascii_ = unicodedata.normalize("NFKD", title.lower().translate(_LATIN)).encode("ascii", "ignore").decode()
120
+ return re.sub(r"[^a-z0-9]+", "-", ascii_).strip("-") or "software"
121
+
122
+
123
+ def stale(root: Path, docs: list[Doc], config: Config) -> list[Finding]:
124
+ """An ``export-stale`` finding for each listed export that is missing or differs from what the source gives."""
125
+ if not config.exports or not docs[0].readable:
126
+ return []
127
+ rec, found = record(docs), []
128
+ if not rec.get("name"):
129
+ return [Finding(path, None, "export-stale", "can't be made: no file gives a title") for path in config.exports]
130
+ for path in config.exports:
131
+ file = root / path
132
+ if not writable(root, path):
133
+ found.append(Finding(path, None, "export-stale", "can't be written: a link, a folder, or under a file"))
134
+ elif not file.is_file():
135
+ found.append(Finding(path, None, "export-stale", "missing"))
136
+ elif file.read_bytes().decode("utf-8", "replace").replace("\r\n", "\n") != text(path, rec):
137
+ found.append(Finding(path, None, "export-stale", "differs from what the source gives"))
138
+ return found
139
+
140
+
141
+ def writable(root: Path, path: str) -> bool:
142
+ """Whether ``write`` may make the export: no link on the way, folders above it, and a file or nothing there.
143
+
144
+ An export is written whole, so a link could replace the file it points at, CITATION.cff included.
145
+ """
146
+ parts = PurePosixPath(path).parts
147
+ for i in range(1, len(parts) + 1):
148
+ here = root.joinpath(*parts[:i])
149
+ if here.is_symlink() or (i < len(parts) and here.exists() and not here.is_dir()):
150
+ return False
151
+ return not (root / path).exists() or (root / path).is_file()
152
+
153
+
154
+ def _bibtex(rec: dict[str, Any], day: tuple[int, ...] | None) -> str:
155
+ """A biblatex-software ``@software`` entry, each field named as codemeta-drift's bibtex rows name it.
156
+
157
+ A row with alternatives (``date | year``) writes each one, so plain BibTeX styles, which print an
158
+ unknown type as ``@misc``, still find the field they read.
159
+ """
160
+ rows = load_mapping()
161
+ authors = []
162
+ for p in _people(rec):
163
+ if p.organization or not p.family:
164
+ authors.append("{" + tex(p.name or "") + "}")
165
+ else:
166
+ authors.append("{" + tex(p.family) + "}" + (", {" + tex(p.given) + "}" if p.given else ""))
167
+ values = {
168
+ "name": "{" + tex(rec["name"]) + "}",
169
+ "author": " and ".join(authors),
170
+ "version": tex(rec.get("version") or ""),
171
+ "datePublished": "-".join(f"{part:02d}" for part in day) if day else "",
172
+ "identifier": str(rec.get("identifier") or ""),
173
+ "swhid": str(rec.get("swhid") or ""),
174
+ "codeRepository": str(rec.get("codeRepository") or ""),
175
+ "license": tex(rec.get("license") or ""),
176
+ "description": tex(rec.get("description") or ""),
177
+ "keywords": tex(", ".join(rec.get("keywords") or ())),
178
+ }
179
+ verbatim = {"identifier", "swhid", "codeRepository"} # biblatex reads these as written: only braces would break
180
+ fields: dict[str, str] = {}
181
+ for term, value in values.items():
182
+ names = str(rows["bibtex", term] or "").split(" | ")
183
+ if term == "codeRepository" and "url" not in names:
184
+ names.append("url") # NOTE: until codemeta-drift's row reads `repository | url`
185
+ for name in names if value else ():
186
+ text = value.replace("{", "%7B").replace("}", "%7D") if term in verbatim else value
187
+ fields.setdefault(name, str(day[0]) if name == "year" and day else text)
188
+ return f"@software{{{key(rec)},\n" + "".join(f" {k} = {{{v}}},\n" for k, v in fields.items()) + "}\n"
189
+
190
+
191
+ def _csl(rec: dict[str, Any], day: tuple[int, ...] | None) -> str:
192
+ authors = []
193
+ for p in _people(rec):
194
+ if p.organization or not p.family:
195
+ authors.append({"literal": p.name})
196
+ else:
197
+ authors.append({"family": p.family} | ({"given": p.given} if p.given else {}))
198
+ csl: dict[str, Any] = {"id": key(rec), "type": "software", "title": rec["name"], "author": authors}
199
+ for term, field in (("identifier", "DOI"), ("codeRepository", "URL"), ("version", "version")):
200
+ if value := rec.get(term):
201
+ csl[field] = value
202
+ if day:
203
+ csl["issued"] = {"date-parts": [list(day)]}
204
+ return json.dumps([csl], indent=2, ensure_ascii=False) + "\n"
205
+
206
+
207
+ def _apa(rec: dict[str, Any], day: tuple[int, ...] | None) -> str:
208
+ """An APA 7 software reference: ``Family, G. (2026). Title (Version 1.0) [Computer software]. URL``."""
209
+ names = [_apa_name(p) for p in _people(rec)]
210
+ if len(names) > 20: # APA 7: the first 19, an ellipsis, then the last
211
+ authors = ", ".join(names[:19]) + ", . . . " + names[-1]
212
+ elif len(names) > 1:
213
+ authors = ", ".join(names[:-1]) + ", & " + names[-1]
214
+ else:
215
+ authors = "".join(names)
216
+ work = f"{rec['name']}" + (f" (Version {rec['version']})" if rec.get("version") else "") + " [Computer software]."
217
+ year = f"({day[0] if day else 'n.d.'})."
218
+ # APA 7: with no author, the title takes the author's place
219
+ text = f"{authors}{'' if authors.endswith('.') else '.'} {year} {work}" if authors else f"{work} {year}"
220
+ doi = rec.get("identifier")
221
+ link = f"https://doi.org/{doi}" if doi else rec.get("codeRepository")
222
+ return f"{text} {link}\n" if link else f"{text}\n"
223
+
224
+
225
+ def _apa_name(p: Person) -> str:
226
+ if p.organization or not p.family:
227
+ return p.name or ""
228
+ initials = _initials(p.given)
229
+ return f"{p.family}, {initials}" if initials else p.family
230
+
231
+
232
+ def _jsonld(rec: dict[str, Any], _day: tuple[int, ...] | None) -> str:
233
+ """schema.org ``SoftwareSourceCode`` with the plain schema.org context, which search engines read."""
234
+ data: dict[str, Any] = {"@context": "https://schema.org", "@type": "SoftwareSourceCode", "name": rec["name"]}
235
+ for term in ("description", "version", "codeRepository", "datePublished"):
236
+ if value := rec.get(term):
237
+ data[term] = value
238
+ if doi := rec.get("identifier"):
239
+ data["identifier"] = f"https://doi.org/{doi}"
240
+ if licence := rec.get("license"):
241
+ data["license"] = f"https://spdx.org/licenses/{licence}" if _SPDX_ID.fullmatch(licence) else licence
242
+ if keywords := rec.get("keywords"):
243
+ data["keywords"] = list(keywords)
244
+ for term in ("author", "contributor"):
245
+ if people := [_schema_person(p) for p in rec.get(term, ()) if p.name]:
246
+ data[term] = people
247
+ # a site embeds this in a <script> tag, where a literal </script> in a title would end it
248
+ return json.dumps(data, indent=2, ensure_ascii=False).replace("<", "\\u003c") + "\n"
249
+
250
+
251
+ def _schema_person(p: Person) -> dict[str, str]:
252
+ if p.organization:
253
+ return {"@type": "Organization", "name": p.name or ""}
254
+ node = {"@type": "Person"} | ({"@id": f"https://orcid.org/{p.orcid}"} if p.orcid else {})
255
+ for field, value in (("givenName", p.given), ("familyName", p.family), ("name", p.name)):
256
+ if value:
257
+ node[field] = value
258
+ return node
259
+
260
+
261
+ def _people(rec: dict[str, Any]) -> list[Person]:
262
+ return [p for p in rec.get("author", ()) if p.name]
263
+
264
+
265
+ def _initials(given: str | None) -> str:
266
+ """``Marie`` as ``M.``, ``Jean-Paul`` as ``J.-P.``, ``Tu Youyou``'s ``Youyou`` as ``Y.``."""
267
+ return " ".join(
268
+ "-".join(f"{part[0].upper()}." for part in word.split("-") if part) for word in (given or "").split()
269
+ )
270
+
271
+
272
+ _WRITERS = {"bibtex": _bibtex, "csl-json": _csl, "apa": _apa, "jsonld": _jsonld}
@@ -21,7 +21,16 @@ from citesync.errors import CheckError, UnreadableError
21
21
  from citesync.mapping import PEOPLE, PERSON_TERMS, TERMS, Mapping, person_terms, relative, resolve
22
22
 
23
23
  CITATION_FILES = {"CITATION.cff": "cff-1.2.0", "codemeta.json": "codemeta", ".zenodo.json": "zenodo"}
24
- MANIFESTS = {"pyproject.toml": "pep621", "Cargo.toml": "cargo", "package.json": "npm"}
24
+ MANIFESTS = {
25
+ "pyproject.toml": "pep621",
26
+ "Cargo.toml": "cargo",
27
+ "package.json": "npm",
28
+ # Plugin manifests hold their fields where Cargo and npm do: typst.toml's [package], and
29
+ # Quarto's top-level version and one author string, so they read through those rows.
30
+ "typst.toml": "cargo",
31
+ "_extension.yml": "npm",
32
+ "_extension.yaml": "npm",
33
+ }
25
34
  IMPORTS = {
26
35
  "PKG-INFO": "pep621",
27
36
  "METADATA": "pep621",
@@ -307,7 +316,7 @@ def _is_release(fmt: str, data: dict[str, Any]) -> bool:
307
316
 
308
317
 
309
318
  def _adapt(fmt: str, data: dict[str, Any], root: Path, rel: str) -> dict[str, Any]:
310
- if fmt == "cargo":
319
+ if fmt == "cargo" and PurePosixPath(rel).name == "Cargo.toml": # a typst.toml has no workspace
311
320
  return _adapt_cargo(data, root, rel)
312
321
  if fmt == "pep621" and isinstance(project := data.get("project"), dict):
313
322
  dynamic = set(project.get("dynamic", [])) # a dynamic field is skipped, the rest still checked
@@ -418,7 +427,11 @@ def _find_workspace(root: Path, rel: str) -> dict[str, Any] | None:
418
427
 
419
428
  def _read_term(fmt: str, term: str, data: dict[str, Any], path: str, mapping: Mapping) -> Any: # noqa: ANN401
420
429
  if term in PEOPLE:
421
- people = tuple(p for p in (person(fmt, el, path, mapping, term) for el in resolve(data, path)) if p)
430
+ found = resolve(data, path)
431
+ if fmt == "npm" and any(isinstance(el, list) for el in found): # else it reads as no one, unchecked
432
+ msg = f"{term} holds a list, but this file takes one {term}"
433
+ raise TypeError(msg)
434
+ people = tuple(p for p in (person(fmt, el, path, mapping, term) for el in found) if p)
422
435
  return people or None
423
436
  slot = locate(fmt, term, data, path)
424
437
  if slot is None: