citesync 0.2.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 (30) hide show
  1. {citesync-0.2.0 → citesync-0.4.0}/PKG-INFO +17 -7
  2. {citesync-0.2.0 → citesync-0.4.0}/README.md +13 -4
  3. {citesync-0.2.0 → citesync-0.4.0}/pyproject.toml +5 -3
  4. {citesync-0.2.0 → citesync-0.4.0}/pyproject.toml.orig +5 -3
  5. citesync-0.4.0/src/citesync/MAPPING_SOURCE +5 -0
  6. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/check.py +17 -3
  7. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/cli.py +46 -1
  8. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/config.py +58 -0
  9. citesync-0.4.0/src/citesync/core_metadata.py +136 -0
  10. citesync-0.4.0/src/citesync/export.py +272 -0
  11. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/formats.py +67 -14
  12. citesync-0.4.0/src/citesync/mapping-local.json +1219 -0
  13. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/mapping.schema.json +7 -3
  14. citesync-0.4.0/src/citesync/playground.py +199 -0
  15. citesync-0.4.0/src/citesync/playground_exports.py +89 -0
  16. citesync-0.4.0/src/citesync/research_metadata.py +314 -0
  17. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/rules.py +22 -3
  18. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/write.py +215 -52
  19. citesync-0.2.0/src/citesync/MAPPING_SOURCE +0 -5
  20. citesync-0.2.0/src/citesync/mapping-local.json +0 -626
  21. {citesync-0.2.0 → citesync-0.4.0}/LICENSE +0 -0
  22. {citesync-0.2.0 → citesync-0.4.0}/NOTICE +0 -0
  23. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/__init__.py +0 -0
  24. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/__main__.py +0 -0
  25. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/codecs.py +0 -0
  26. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/errors.py +0 -0
  27. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/jsonsplice.py +0 -0
  28. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/mapping.py +0 -0
  29. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/positions.py +0 -0
  30. {citesync-0.2.0 → citesync-0.4.0}/src/citesync/py.typed +0 -0
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: citesync
3
- Version: 0.2.0
4
- Summary: Check that CITATION.cff, codemeta.json, .zenodo.json and the package manifests (pyproject.toml, Cargo.toml, package.json) agree, rewrite them to match one source file, and start a CITATION.cff from them, using the CodeMeta crosswalks
3
+ Version: 0.4.0
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
7
7
  Author-email: Simon van Lierde <code@duinlab.nl>
@@ -22,7 +22,8 @@ Requires-Dist: packaging>=26.3
22
22
  Requires-Dist: ruamel-yaml>=0.19
23
23
  Requires-Dist: tomlkit>=0.15.2
24
24
  Requires-Python: >=3.12
25
- Project-URL: Homepage, https://github.com/simonvanlierde/citesync
25
+ Project-URL: Homepage, https://simonvanlierde.com/citesync/
26
+ Project-URL: Source, https://github.com/simonvanlierde/citesync
26
27
  Project-URL: Issues, https://github.com/simonvanlierde/citesync/issues
27
28
  Project-URL: Changelog, https://github.com/simonvanlierde/citesync/blob/main/CHANGELOG.md
28
29
  Description-Content-Type: text/markdown
@@ -40,7 +41,7 @@ Status: experimental. It may change in ways that break your code, without notice
40
41
 
41
42
  Questions and bugs: see [CONTRIBUTING.md](https://github.com/simonvanlierde/citesync/blob/main/.github/CONTRIBUTING.md).
42
43
 
43
- citesync checks that your software's citation metadata says the same thing everywhere: CITATION.cff, codemeta.json, .zenodo.json and the package manifests (pyproject.toml, Cargo.toml, package.json). It can also rewrite the files so they agree. It knows where each field sits in each file 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).
44
45
 
45
46
  ## Usage
46
47
 
@@ -53,6 +54,7 @@ citesync check --source pyproject.toml
53
54
  citesync write --diff # print what write would change, and change nothing
54
55
  citesync write # rewrite the other files to agree with the source
55
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
56
58
  citesync explain version-mismatch # what a rule checks and how to fix it
57
59
  citesync config # the config in use, and the file it came from
58
60
  ```
@@ -70,12 +72,19 @@ A config is optional. A one-line `citesync.toml` is `ignore = ["description-mism
70
72
 
71
73
  - [How check works](https://github.com/simonvanlierde/citesync/blob/main/docs/check.md): the fields, files, options and exit codes.
72
74
  - [How write works](https://github.com/simonvanlierde/citesync/blob/main/docs/write.md): what it changes and what it leaves alone.
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.
73
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.
74
78
  - [Rules](https://github.com/simonvanlierde/citesync/blob/main/docs/rules.md): each rule id, what it checks and how to fix it.
75
79
  - [Configuration](https://github.com/simonvanlierde/citesync/blob/main/docs/config.md): where config goes, and every key.
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.
76
81
  - [Output formats](https://github.com/simonvanlierde/citesync/blob/main/docs/output.md): JSON, GitHub annotations and SARIF.
77
82
  - [Tested on real repositories](https://github.com/simonvanlierde/citesync/blob/main/docs/tested-repositories.md): what citesync reports on five public repositories.
78
83
 
84
+ ## Browser playground
85
+
86
+ Generate citation files from existing metadata or basic project details, without installing Python. [Open the playground](https://simonvanlierde.com/citesync/) or [run it locally](https://github.com/simonvanlierde/citesync/blob/main/playground/README.md). Files are processed in the browser; downloading the converter requires a network connection.
87
+
79
88
  ## Pre-commit hook
80
89
 
81
90
  For [prek](https://prek.j178.dev) or [pre-commit](https://pre-commit.com), in `.pre-commit-config.yaml`:
@@ -83,20 +92,21 @@ For [prek](https://prek.j178.dev) or [pre-commit](https://pre-commit.com), in `.
83
92
  ```yaml
84
93
  repos:
85
94
  - repo: https://github.com/simonvanlierde/citesync
86
- rev: v0.2.0
95
+ rev: v0.4.0
87
96
  hooks:
88
97
  - id: citesync
89
98
  - id: citesync-write
90
99
  ```
91
100
 
92
- The `citesync` hook runs when a commit changes one of the six metadata files 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`.
93
102
 
94
103
  ## Development
95
104
 
96
- You need [uv](https://docs.astral.sh/uv/) and [just](https://just.systems).
105
+ You need [uv](https://docs.astral.sh/uv/), [just](https://just.systems), Node.js 26 and [pnpm](https://pnpm.io/).
97
106
 
98
107
  ```sh
99
108
  uv sync
109
+ pnpm install --frozen-lockfile
100
110
  uv tool install prek # once per machine
101
111
  prek install # git hooks
102
112
  ```
@@ -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
- citesync checks that your software's citation metadata says the same thing everywhere: CITATION.cff, codemeta.json, .zenodo.json and the package manifests (pyproject.toml, Cargo.toml, package.json). It can also rewrite the files so they agree. It knows where each field sits in each file 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
  ```
@@ -41,12 +42,19 @@ A config is optional. A one-line `citesync.toml` is `ignore = ["description-mism
41
42
 
42
43
  - [How check works](https://github.com/simonvanlierde/citesync/blob/main/docs/check.md): the fields, files, options and exit codes.
43
44
  - [How write works](https://github.com/simonvanlierde/citesync/blob/main/docs/write.md): what it changes and what it leaves alone.
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.
44
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.
45
48
  - [Rules](https://github.com/simonvanlierde/citesync/blob/main/docs/rules.md): each rule id, what it checks and how to fix it.
46
49
  - [Configuration](https://github.com/simonvanlierde/citesync/blob/main/docs/config.md): where config goes, and every key.
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.
47
51
  - [Output formats](https://github.com/simonvanlierde/citesync/blob/main/docs/output.md): JSON, GitHub annotations and SARIF.
48
52
  - [Tested on real repositories](https://github.com/simonvanlierde/citesync/blob/main/docs/tested-repositories.md): what citesync reports on five public repositories.
49
53
 
54
+ ## Browser playground
55
+
56
+ Generate citation files from existing metadata or basic project details, without installing Python. [Open the playground](https://simonvanlierde.com/citesync/) or [run it locally](https://github.com/simonvanlierde/citesync/blob/main/playground/README.md). Files are processed in the browser; downloading the converter requires a network connection.
57
+
50
58
  ## Pre-commit hook
51
59
 
52
60
  For [prek](https://prek.j178.dev) or [pre-commit](https://pre-commit.com), in `.pre-commit-config.yaml`:
@@ -54,20 +62,21 @@ For [prek](https://prek.j178.dev) or [pre-commit](https://pre-commit.com), in `.
54
62
  ```yaml
55
63
  repos:
56
64
  - repo: https://github.com/simonvanlierde/citesync
57
- rev: v0.2.0
65
+ rev: v0.4.0
58
66
  hooks:
59
67
  - id: citesync
60
68
  - id: citesync-write
61
69
  ```
62
70
 
63
- The `citesync` hook runs when a commit changes one of the six metadata files 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`.
64
72
 
65
73
  ## Development
66
74
 
67
- You need [uv](https://docs.astral.sh/uv/) and [just](https://just.systems).
75
+ You need [uv](https://docs.astral.sh/uv/), [just](https://just.systems), Node.js 26 and [pnpm](https://pnpm.io/).
68
76
 
69
77
  ```sh
70
78
  uv sync
79
+ pnpm install --frozen-lockfile
71
80
  uv tool install prek # once per machine
72
81
  prek install # git hooks
73
82
  ```
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "citesync"
3
- version = "0.2.0"
4
- description = "Check that CITATION.cff, codemeta.json, .zenodo.json and the package manifests (pyproject.toml, Cargo.toml, package.json) agree, rewrite them to match one source file, and start a CITATION.cff from them, using the CodeMeta crosswalks"
3
+ version = "0.4.0"
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"
7
7
  license = "Apache-2.0"
@@ -43,7 +43,8 @@ email = "code@duinlab.nl"
43
43
  citesync = "citesync.cli:main"
44
44
 
45
45
  [project.urls]
46
- Homepage = "https://github.com/simonvanlierde/citesync"
46
+ Homepage = "https://simonvanlierde.com/citesync/"
47
+ Source = "https://github.com/simonvanlierde/citesync"
47
48
  Issues = "https://github.com/simonvanlierde/citesync/issues"
48
49
  Changelog = "https://github.com/simonvanlierde/citesync/blob/main/CHANGELOG.md"
49
50
 
@@ -53,6 +54,7 @@ dev = [
53
54
  "jsonschema>=4.25",
54
55
  "memray>=1.20.0 ; sys_platform != 'win32'",
55
56
  "mutmut==3.8.0",
57
+ "pybtex>=0.25",
56
58
  "pyinstrument>=5.1.3",
57
59
  "pytest>=9.1.1",
58
60
  "pytest-cov>=7.1.0",
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "citesync"
3
- version = "0.2.0"
4
- description = "Check that CITATION.cff, codemeta.json, .zenodo.json and the package manifests (pyproject.toml, Cargo.toml, package.json) agree, rewrite them to match one source file, and start a CITATION.cff from them, using the CodeMeta crosswalks"
3
+ version = "0.4.0"
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"
7
7
  authors = [{ name = "Simon van Lierde", email = "code@duinlab.nl" }]
@@ -30,7 +30,8 @@ dependencies = [
30
30
  citesync = "citesync.cli:main"
31
31
 
32
32
  [project.urls]
33
- Homepage = "https://github.com/simonvanlierde/citesync"
33
+ Homepage = "https://simonvanlierde.com/citesync/"
34
+ Source = "https://github.com/simonvanlierde/citesync"
34
35
  Issues = "https://github.com/simonvanlierde/citesync/issues"
35
36
  Changelog = "https://github.com/simonvanlierde/citesync/blob/main/CHANGELOG.md"
36
37
 
@@ -40,6 +41,7 @@ dev = [
40
41
  "jsonschema>=4.25",
41
42
  "memray>=1.20.0 ; sys_platform != 'win32'",
42
43
  "mutmut==3.8.0",
44
+ "pybtex>=0.25",
43
45
  "pyinstrument>=5.1.3",
44
46
  "pytest>=9.1.1",
45
47
  "pytest-cov>=7.1.0",
@@ -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
@@ -105,7 +105,14 @@ def read_docs(root: Path, config: Config, mapping: Mapping) -> tuple[list[Doc],
105
105
  docs, unreadable = [], [Finding(p, None, "file-missing", "listed under files") for p in missing(root, config)]
106
106
  for path in discover(root, config):
107
107
  try:
108
- docs.append(read_doc(root, path, mapping))
108
+ docs.append(
109
+ read_doc(
110
+ root,
111
+ path,
112
+ mapping,
113
+ keep_empty_contributors=config.zenodo_contributor_type is not None and path != config.source,
114
+ )
115
+ )
109
116
  except UnreadableError as err:
110
117
  unreadable.append(Finding(err.path, None, "unreadable", err.message, err.line, err.column))
111
118
  fmt = format_of(path)
@@ -129,7 +136,12 @@ def check(root: Path, config: Config) -> tuple[list[Finding], int, list[str]]:
129
136
  """Every finding for the repo at ``root``, sorted, the number of files checked, and the unused ignore entries."""
130
137
  mapping = load_mapping()
131
138
  docs, read = read_docs(root, config, mapping)
132
- 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)
133
145
  if any(f.file and f.term for f in found): # a check with nothing to point at reads no file twice
134
146
  from citesync.positions import place # noqa: PLC0415
135
147
 
@@ -195,13 +207,15 @@ def findings(docs: list[Doc], extra: list[Finding], config: Config) -> tuple[set
195
207
  source = docs[0]
196
208
  for doc in docs:
197
209
  configured = config.codemeta_version
198
- if configured and doc.readable and doc.format == "codemeta" and doc.version != configured:
210
+ if configured and doc.readable and doc.is_citation and doc.format == "codemeta" and doc.version != configured:
199
211
  detail = f"{doc.version}, configured {configured}"
200
212
  found.add(Finding(doc.path, "@context", "context-mismatch", detail))
201
213
  for key in dict.fromkeys(key for key, _ in doc.dangling_roles):
202
214
  orcids = ", ".join(orcid for k, orcid in doc.dangling_roles if k == key)
203
215
  detail = f"a Role points at {orcids}, which no Person in author or contributor has"
204
216
  found.add(Finding(doc.path, key, "role-dangling", detail))
217
+ for term, message in doc.import_notes:
218
+ found.add(Finding(doc.path, term, "metadata-omitted", message))
205
219
  for key, rule in doc.zenodo_gaps:
206
220
  found.add(Finding(doc.path, key, rule, ZENODO_GAPS[rule]))
207
221
  for term in TERMS:
@@ -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,8 @@ 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, ...] = ()
28
+ zenodo_contributor_type: str | None = None
27
29
  keywords_case_sensitive: bool = False
28
30
  keywords_ignore_separators: bool = False
29
31
  ignore: tuple[str, ...] = ()
@@ -110,6 +112,39 @@ def _codemeta_version(value: object, origin: str) -> str:
110
112
  return str(value)
111
113
 
112
114
 
115
+ # Zenodo deposition metadata: https://developers.zenodo.org/#representation
116
+ ZENODO_CONTRIBUTOR_TYPES = (
117
+ "ContactPerson",
118
+ "DataCollector",
119
+ "DataCurator",
120
+ "DataManager",
121
+ "Distributor",
122
+ "Editor",
123
+ "HostingInstitution",
124
+ "Other",
125
+ "Producer",
126
+ "ProjectLeader",
127
+ "ProjectManager",
128
+ "ProjectMember",
129
+ "RegistrationAgency",
130
+ "RegistrationAuthority",
131
+ "RelatedPerson",
132
+ "ResearchGroup",
133
+ "RightsHolder",
134
+ "Researcher",
135
+ "Sponsor",
136
+ "Supervisor",
137
+ "WorkPackageLeader",
138
+ )
139
+
140
+
141
+ def _zenodo_contributor_type(value: object, origin: str) -> str:
142
+ if not isinstance(value, str) or value not in ZENODO_CONTRIBUTOR_TYPES:
143
+ msg = f"{origin}: zenodo-contributor-type must be one of {', '.join(ZENODO_CONTRIBUTOR_TYPES)}"
144
+ raise CheckError(msg)
145
+ return value
146
+
147
+
113
148
  def _bool(value: object, origin: str, key: str) -> bool:
114
149
  if not isinstance(value, bool):
115
150
  msg = f"{origin}: {key} must be true or false"
@@ -121,6 +156,10 @@ def _path(value: object, names: dict[str, str], origin: str, key: str) -> str:
121
156
  if not isinstance(value, str) or PurePosixPath(value).name not in names:
122
157
  msg = f"{origin}: {key} must name one of {', '.join(names)}, got {value!r}"
123
158
  raise CheckError(msg)
159
+ return _relative(value, origin, key)
160
+
161
+
162
+ def _relative(value: str, origin: str, key: str) -> str:
124
163
  path = PurePosixPath(value)
125
164
  if path.is_absolute() or ".." in path.parts:
126
165
  msg = f"{origin}: {key} {value!r} must be relative to the repo root, inside it"
@@ -169,6 +208,19 @@ def _write_manifests(value: object, origin: str) -> tuple[str, ...]:
169
208
  return MANIFEST_TERMS if "all" in items else tuple(items)
170
209
 
171
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
+
172
224
  def _ignore(value: object, origin: str) -> tuple[str, ...]:
173
225
  if not isinstance(value, list) or not all(isinstance(i, str) for i in value):
174
226
  msg = f"{origin}: ignore must be a list of rule ids, got {value!r}"
@@ -191,6 +243,8 @@ _PARSE: dict[str, Callable[[object, str], Any]] = {
191
243
  "files": lambda value, origin: _paths(value, CITATION_FILES, origin, "files"),
192
244
  "manifests": lambda value, origin: _paths(value, MANIFESTS, origin, "manifests"),
193
245
  "write-manifests": _write_manifests,
246
+ "exports": _exports,
247
+ "zenodo-contributor-type": _zenodo_contributor_type,
194
248
  "keywords-case-sensitive": lambda value, origin: _bool(value, origin, "keywords-case-sensitive"),
195
249
  "keywords-ignore-separators": lambda value, origin: _bool(value, origin, "keywords-ignore-separators"),
196
250
  "ignore": _ignore,
@@ -212,6 +266,10 @@ def render(config: Config) -> str:
212
266
  if config.manifests is not None
213
267
  else "# manifests: not set, so every release manifest at the repo root",
214
268
  f"write-manifests = {json.dumps(list(config.write_manifests))}",
269
+ f"exports = {json.dumps(list(config.exports))}",
270
+ f"zenodo-contributor-type = {json.dumps(config.zenodo_contributor_type)}"
271
+ if config.zenodo_contributor_type is not None
272
+ else "# zenodo-contributor-type: not set, so new contributors need a hand edit",
215
273
  f"keywords-case-sensitive = {json.dumps(config.keywords_case_sensitive)}",
216
274
  f"keywords-ignore-separators = {json.dumps(config.keywords_ignore_separators)}",
217
275
  f"ignore = {json.dumps(list(config.ignore))}",
@@ -0,0 +1,136 @@
1
+ """Read distribution headers into the existing PEP 621 field shapes, without loading package code."""
2
+
3
+ import csv
4
+ import unicodedata
5
+ from email.header import decode_header, make_header
6
+ from email.message import Message
7
+ from email.parser import Parser
8
+ from email.policy import compat32
9
+ from email.utils import getaddresses
10
+ from typing import Any
11
+
12
+ from packaging.licenses import InvalidLicenseExpression, canonicalize_license_expression
13
+ from packaging.utils import InvalidName, canonicalize_name
14
+ from packaging.version import InvalidVersion, Version
15
+
16
+ from citesync.errors import UnreadableError
17
+
18
+
19
+ def parse(text: str, rel: str) -> dict[str, Any]: # noqa: C901 - independent optional headers
20
+ """Normalize UTF-8 Core Metadata 1.x to 2.6; retain import notices for fields that cannot be represented.
21
+
22
+ Repeated author/address and Project-URL headers are read in full. Conflicting
23
+ scalar fields and repeated URL labels are errors. No build or package import runs.
24
+ """
25
+ message = Parser(policy=compat32).parsestr(text)
26
+ if message.defects:
27
+ raise UnreadableError(rel, f"malformed metadata headers: {type(message.defects[0]).__name__}")
28
+
29
+ def one(key: str, *, required: bool = False) -> str:
30
+ values = message.get_all(key, [])
31
+ if len(values) > 1:
32
+ raise UnreadableError(rel, f"{key} must appear only once")
33
+ value = str(values[0]).strip() if values else ""
34
+ if required and not value:
35
+ raise UnreadableError(rel, f"missing {key} header")
36
+ return value
37
+
38
+ version = one("Metadata-Version", required=True)
39
+ if version not in {"1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5", "2.6"}:
40
+ raise UnreadableError(rel, f"unsupported Metadata-Version {version!r}; citesync reads 1.0 to 2.6")
41
+ project: dict[str, Any] = {"name": one("Name", required=True), "version": one("Version", required=True)}
42
+ try:
43
+ canonicalize_name(project["name"], validate=True)
44
+ Version(project["version"])
45
+ except (InvalidName, InvalidVersion) as err:
46
+ raise UnreadableError(rel, f"invalid Name or Version: {err}") from err
47
+ if description := one("Summary"): # Description and the body hold the README, not a summary
48
+ project["description"] = description
49
+ if authors := _authors(message, rel):
50
+ project["authors"] = authors
51
+ if urls := _urls(message, rel):
52
+ project["urls"] = urls
53
+ if words := one("Keywords"):
54
+ project["keywords"] = [word.strip() for word in words.split(",") if word.strip()]
55
+ notes = _license(project, one("License-Expression"), one("License"), rel)
56
+ return {"project": project, "build-system": {}, "_import_notes": notes}
57
+
58
+
59
+ def _license(project: dict[str, Any], expression: str, legacy: str, rel: str) -> list[tuple[str, str]]:
60
+ notes = []
61
+ if expression or legacy:
62
+ try:
63
+ canonical = canonicalize_license_expression(expression or legacy)
64
+ if "LicenseRef-" in canonical:
65
+ notes.append(
66
+ ("license", "LicenseRef has no public SPDX licence URL; review this licence in each citation file.")
67
+ )
68
+ else:
69
+ project["license"] = canonical
70
+ except InvalidLicenseExpression as err:
71
+ if expression:
72
+ raise UnreadableError(rel, f"invalid License-Expression: {err}") from err
73
+ notes.append(
74
+ (
75
+ "license",
76
+ "Legacy License text is not an SPDX expression; set License-Expression before converting it.",
77
+ )
78
+ )
79
+ return notes
80
+
81
+
82
+ def _authors(message: Message, rel: str) -> list[dict[str, str]]:
83
+ contacts: dict[str, dict[str, str]] = {}
84
+ for raw_name, address in getaddresses(message.get_all("Author-email", [])):
85
+ if not address or "@" not in address or any(c.isspace() for c in address):
86
+ raise UnreadableError(rel, "Author-email must contain valid addresses with optional display names")
87
+ if raw_name:
88
+ name = _header(raw_name, rel)
89
+ key = name.casefold()
90
+ if key in contacts and contacts[key].get("email") != address:
91
+ raise UnreadableError(rel, f"Author-email gives conflicting addresses for {name!r}")
92
+ contacts[key] = {"name": name, "email": address}
93
+ authors: dict[str, dict[str, str]] = {}
94
+ for header in message.get_all("Author", []):
95
+ try:
96
+ names = next(csv.reader([_header(str(header), rel)], skipinitialspace=True, strict=True))
97
+ except csv.Error as err:
98
+ raise UnreadableError(rel, f"cannot read Author names: {err}") from err
99
+ for raw_name in names:
100
+ name = raw_name.strip()
101
+ if name:
102
+ authors.setdefault(name.casefold(), contacts.get(name.casefold(), {"name": name}))
103
+ for key, contact in contacts.items():
104
+ authors.setdefault(key, contact)
105
+ return list(authors.values())
106
+
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
+
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."""
114
+ urls = {}
115
+ for raw in message.get_all("Project-URL", []):
116
+ label, separator, address = str(raw).partition(",")
117
+ label, address = label.strip(), address.strip()
118
+ if not separator or not label or not address:
119
+ raise UnreadableError(rel, "Project-URL must contain a label, comma and URL")
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:
122
+ raise UnreadableError(rel, f"Project-URL has conflicting values for {label!r}")
123
+ urls[key] = address
124
+ homes = message.get_all("Home-page", [])
125
+ if len(homes) > 1:
126
+ raise UnreadableError(rel, "Home-page must appear only once")
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 {}
130
+
131
+
132
+ def _header(value: str, rel: str) -> str:
133
+ try:
134
+ return unicodedata.normalize("NFC", " ".join(str(make_header(decode_header(value))).split()))
135
+ except (LookupError, UnicodeError) as err:
136
+ raise UnreadableError(rel, f"invalid encoded author header: {err}") from err