citesync 0.6.0__tar.gz → 0.7.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.
- {citesync-0.6.0 → citesync-0.7.0}/PKG-INFO +9 -6
- {citesync-0.6.0 → citesync-0.7.0}/README.md +8 -5
- {citesync-0.6.0 → citesync-0.7.0}/pyproject.toml +2 -1
- {citesync-0.6.0 → citesync-0.7.0}/pyproject.toml.orig +5 -3
- citesync-0.7.0/src/citesync/MAPPING_SOURCE +7 -0
- citesync-0.7.0/src/citesync/cite.py +95 -0
- citesync-0.7.0/src/citesync/cite_evidence.py +112 -0
- citesync-0.7.0/src/citesync/cite_http.py +200 -0
- citesync-0.7.0/src/citesync/cite_sources.py +463 -0
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/cli.py +201 -45
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/codecs.py +13 -3
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/config.py +60 -32
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/export.py +93 -23
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/formats.py +114 -18
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/jsonsplice.py +26 -1
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/mapping-4.0.json +4259 -2525
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/mapping-local.json +4119 -2387
- citesync-0.7.0/src/citesync/mapping-vectors.json +2060 -0
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/mapping.py +12 -5
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/mapping.schema.json +6 -2
- citesync-0.7.0/src/citesync/maven.py +104 -0
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/playground.py +10 -3
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/positions.py +6 -2
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/write.py +216 -32
- citesync-0.6.0/src/citesync/MAPPING_SOURCE +0 -7
- citesync-0.6.0/src/citesync/mapping-vectors.json +0 -1358
- {citesync-0.6.0 → citesync-0.7.0}/LICENSE +0 -0
- {citesync-0.6.0 → citesync-0.7.0}/NOTICE +0 -0
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/__init__.py +0 -0
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/__main__.py +0 -0
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/check.py +0 -0
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/core_metadata.py +0 -0
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/errors.py +0 -0
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/playground_exports.py +0 -0
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/py.typed +0 -0
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/research_metadata.py +0 -0
- {citesync-0.6.0 → citesync-0.7.0}/src/citesync/rules.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: citesync
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.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
|
|
@@ -56,6 +56,7 @@ citesync write --diff # print what write would change, and change
|
|
|
56
56
|
citesync write # rewrite the other files to agree with the source
|
|
57
57
|
citesync init # write a CITATION.cff from codemeta.json, .zenodo.json and the manifests
|
|
58
58
|
citesync export --format apa # print a citation: apa, bibtex, csl-json, jsonld, datacite, ris, endnote, cff, codemeta or zenodo
|
|
59
|
+
citesync cite 10.7717/peerj.4375 --format ris # resolve public metadata and print a citation
|
|
59
60
|
citesync explain version-mismatch # what a rule checks and how to fix it
|
|
60
61
|
citesync config # the config in use, and the file it came from
|
|
61
62
|
```
|
|
@@ -73,8 +74,9 @@ A config is optional. A one-line `citesync.toml` is `ignore = ["description-mism
|
|
|
73
74
|
|
|
74
75
|
- [How check works](https://simonvanlierde.com/citesync/docs/check/): the fields, files, options and exit codes.
|
|
75
76
|
- [How write works](https://simonvanlierde.com/citesync/docs/write/): what it changes and what it leaves alone.
|
|
76
|
-
- [Supported files](https://simonvanlierde.com/citesync/docs/formats/): which files citesync reads, updates and creates, including read-only Python distribution, R and
|
|
77
|
+
- [Supported files](https://simonvanlierde.com/citesync/docs/formats/): which files citesync reads, updates and creates, including read-only Python distribution, R, Julia, Composer and Maven metadata, and the RO-Crate and Croissant files sourceledger makes.
|
|
77
78
|
- [How init works](https://simonvanlierde.com/citesync/docs/init/): where a new CITATION.cff takes each field from.
|
|
79
|
+
- [Cite a DOI, arXiv ID or GitHub repository](https://simonvanlierde.com/citesync/docs/cite/): print its citation, or save the provider responses to replay offline.
|
|
78
80
|
- [Citation exports](https://simonvanlierde.com/citesync/docs/export/): BibTeX, CSL-JSON, APA, schema.org JSON-LD, DataCite XML, RIS and EndNote files kept in step with the source.
|
|
79
81
|
- [Rules](https://simonvanlierde.com/citesync/docs/rules/): each rule id, what it checks and how to fix it.
|
|
80
82
|
- [Configuration](https://simonvanlierde.com/citesync/docs/config/): where config goes, and every key.
|
|
@@ -82,6 +84,8 @@ A config is optional. A one-line `citesync.toml` is `ignore = ["description-mism
|
|
|
82
84
|
- [Output formats](https://simonvanlierde.com/citesync/docs/output/): JSON, GitHub annotations and SARIF.
|
|
83
85
|
- [Tested on real repositories](https://simonvanlierde.com/citesync/docs/tested-repositories/): what citesync reports on five public repositories.
|
|
84
86
|
|
|
87
|
+
See [Architecture and security](https://simonvanlierde.com/citesync/docs/assurance/) and [release verification](https://simonvanlierde.com/citesync/docs/getting-started/#verify-a-release-download).
|
|
88
|
+
|
|
85
89
|
## Browser playground
|
|
86
90
|
|
|
87
91
|
Generate citation files from existing metadata or basic project details, without installing Python. [Open the playground](https://simonvanlierde.com/citesync/) or [read the playground guide](playground/README.md). Files are processed in the browser; downloading the converter requires a network connection.
|
|
@@ -93,7 +97,7 @@ For [prek](https://prek.j178.dev) or [pre-commit](https://pre-commit.com), in `.
|
|
|
93
97
|
```yaml
|
|
94
98
|
repos:
|
|
95
99
|
- repo: https://github.com/simonvanlierde/citesync
|
|
96
|
-
rev: v0.
|
|
100
|
+
rev: v0.7.0
|
|
97
101
|
hooks:
|
|
98
102
|
- id: citesync
|
|
99
103
|
- id: citesync-write
|
|
@@ -109,11 +113,10 @@ For a dataset file with a custom name, set `always_run: true` on each citesync h
|
|
|
109
113
|
[`docs/og-card.html`](docs/og-card.html), whose example is `tests/fixtures/synthetic-agree/pyproject.toml` run through `citesync init`. Edit the HTML, then from the repo root:
|
|
110
114
|
|
|
111
115
|
```sh
|
|
112
|
-
|
|
113
|
-
file://$PWD/docs/og-card.html playground/og.png
|
|
116
|
+
just og-card
|
|
114
117
|
```
|
|
115
118
|
|
|
116
|
-
|
|
119
|
+
Both builds use the same card. The site includes its image hash so sharing services fetch the current version.
|
|
117
120
|
|
|
118
121
|
## Development
|
|
119
122
|
|
|
@@ -26,6 +26,7 @@ citesync write --diff # print what write would change, and change
|
|
|
26
26
|
citesync write # rewrite the other files to agree with the source
|
|
27
27
|
citesync init # write a CITATION.cff from codemeta.json, .zenodo.json and the manifests
|
|
28
28
|
citesync export --format apa # print a citation: apa, bibtex, csl-json, jsonld, datacite, ris, endnote, cff, codemeta or zenodo
|
|
29
|
+
citesync cite 10.7717/peerj.4375 --format ris # resolve public metadata and print a citation
|
|
29
30
|
citesync explain version-mismatch # what a rule checks and how to fix it
|
|
30
31
|
citesync config # the config in use, and the file it came from
|
|
31
32
|
```
|
|
@@ -43,8 +44,9 @@ A config is optional. A one-line `citesync.toml` is `ignore = ["description-mism
|
|
|
43
44
|
|
|
44
45
|
- [How check works](https://simonvanlierde.com/citesync/docs/check/): the fields, files, options and exit codes.
|
|
45
46
|
- [How write works](https://simonvanlierde.com/citesync/docs/write/): what it changes and what it leaves alone.
|
|
46
|
-
- [Supported files](https://simonvanlierde.com/citesync/docs/formats/): which files citesync reads, updates and creates, including read-only Python distribution, R and
|
|
47
|
+
- [Supported files](https://simonvanlierde.com/citesync/docs/formats/): which files citesync reads, updates and creates, including read-only Python distribution, R, Julia, Composer and Maven metadata, and the RO-Crate and Croissant files sourceledger makes.
|
|
47
48
|
- [How init works](https://simonvanlierde.com/citesync/docs/init/): where a new CITATION.cff takes each field from.
|
|
49
|
+
- [Cite a DOI, arXiv ID or GitHub repository](https://simonvanlierde.com/citesync/docs/cite/): print its citation, or save the provider responses to replay offline.
|
|
48
50
|
- [Citation exports](https://simonvanlierde.com/citesync/docs/export/): BibTeX, CSL-JSON, APA, schema.org JSON-LD, DataCite XML, RIS and EndNote files kept in step with the source.
|
|
49
51
|
- [Rules](https://simonvanlierde.com/citesync/docs/rules/): each rule id, what it checks and how to fix it.
|
|
50
52
|
- [Configuration](https://simonvanlierde.com/citesync/docs/config/): where config goes, and every key.
|
|
@@ -52,6 +54,8 @@ A config is optional. A one-line `citesync.toml` is `ignore = ["description-mism
|
|
|
52
54
|
- [Output formats](https://simonvanlierde.com/citesync/docs/output/): JSON, GitHub annotations and SARIF.
|
|
53
55
|
- [Tested on real repositories](https://simonvanlierde.com/citesync/docs/tested-repositories/): what citesync reports on five public repositories.
|
|
54
56
|
|
|
57
|
+
See [Architecture and security](https://simonvanlierde.com/citesync/docs/assurance/) and [release verification](https://simonvanlierde.com/citesync/docs/getting-started/#verify-a-release-download).
|
|
58
|
+
|
|
55
59
|
## Browser playground
|
|
56
60
|
|
|
57
61
|
Generate citation files from existing metadata or basic project details, without installing Python. [Open the playground](https://simonvanlierde.com/citesync/) or [read the playground guide](playground/README.md). Files are processed in the browser; downloading the converter requires a network connection.
|
|
@@ -63,7 +67,7 @@ For [prek](https://prek.j178.dev) or [pre-commit](https://pre-commit.com), in `.
|
|
|
63
67
|
```yaml
|
|
64
68
|
repos:
|
|
65
69
|
- repo: https://github.com/simonvanlierde/citesync
|
|
66
|
-
rev: v0.
|
|
70
|
+
rev: v0.7.0
|
|
67
71
|
hooks:
|
|
68
72
|
- id: citesync
|
|
69
73
|
- id: citesync-write
|
|
@@ -79,11 +83,10 @@ For a dataset file with a custom name, set `always_run: true` on each citesync h
|
|
|
79
83
|
[`docs/og-card.html`](docs/og-card.html), whose example is `tests/fixtures/synthetic-agree/pyproject.toml` run through `citesync init`. Edit the HTML, then from the repo root:
|
|
80
84
|
|
|
81
85
|
```sh
|
|
82
|
-
|
|
83
|
-
file://$PWD/docs/og-card.html playground/og.png
|
|
86
|
+
just og-card
|
|
84
87
|
```
|
|
85
88
|
|
|
86
|
-
|
|
89
|
+
Both builds use the same card. The site includes its image hash so sharing services fetch the current version.
|
|
87
90
|
|
|
88
91
|
## Development
|
|
89
92
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "citesync"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.7.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.13"
|
|
@@ -63,6 +63,7 @@ dev = [
|
|
|
63
63
|
"ty>=0.0.93",
|
|
64
64
|
"xmlschema>=4.3.2",
|
|
65
65
|
]
|
|
66
|
+
fuzz = ["atheris==3.1.0 ; sys_platform == 'linux' and platform_machine == 'x86_64' and python_version < '3.15'"]
|
|
66
67
|
|
|
67
68
|
[build-system]
|
|
68
69
|
requires = ["uv_build>=0.12.19,<0.14.0"]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "citesync"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.7.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.13"
|
|
@@ -50,6 +50,9 @@ dev = [
|
|
|
50
50
|
"ty>=0.0.93",
|
|
51
51
|
"xmlschema>=4.3.2",
|
|
52
52
|
]
|
|
53
|
+
fuzz = [
|
|
54
|
+
"atheris==3.1.0 ; sys_platform == 'linux' and platform_machine == 'x86_64' and python_version < '3.15'",
|
|
55
|
+
]
|
|
53
56
|
|
|
54
57
|
[build-system]
|
|
55
58
|
requires = ["uv_build>=0.12.19,<0.14.0"]
|
|
@@ -121,8 +124,7 @@ filterwarnings = ["error"]
|
|
|
121
124
|
log_level = "INFO"
|
|
122
125
|
|
|
123
126
|
# Coverage is opt-in via `pytest --cov` (`just py-cov`), not addopts, because it
|
|
124
|
-
# slows every plain test run.
|
|
125
|
-
# one against.
|
|
127
|
+
# slows every plain test run. CI enables coverage and requires 80%.
|
|
126
128
|
# Mutation testing covers check, codecs, write and jsonsplice via `just mutation`
|
|
127
129
|
# and the weekly or manually triggered workflow.
|
|
128
130
|
[tool.mutmut]
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Vendored from simonvanlierde/codemeta-drift; tests/test_mapping.py checks the sha256 lines.
|
|
2
|
+
tag v0.10.0
|
|
3
|
+
commit 41f844072ecee081e76a9480cf0e4f137e7253f9
|
|
4
|
+
sha256 68b431dd7a65d25978fa94a99b4722aab097b9f2af862c77d6d74b5d58648760 mapping-local.json examples/mapping-3.1.json
|
|
5
|
+
sha256 82147f5b40e3a8cf92b4a0160013eafb56ac556749971f41e144bd007f08eede mapping-4.0.json examples/mapping-4.0.json
|
|
6
|
+
sha256 006d990ef30f82a0df22e1beffc68071ad27ecf118a594be6157abc9d2ce4cd9 mapping.schema.json src/codemeta_drift/mapping.schema.json
|
|
7
|
+
sha256 35d58f8afa99663d5309d170924335c4c07f3241416c7119d1dc7a3f4024b87c mapping-vectors.json src/codemeta_drift/mapping-vectors.json
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Build citations from public metadata while keeping source evidence available."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import asdict
|
|
5
|
+
from hashlib import sha256
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from tempfile import TemporaryDirectory
|
|
8
|
+
|
|
9
|
+
from citesync.cite_evidence import openalex_evidence
|
|
10
|
+
from citesync.cite_http import Responses
|
|
11
|
+
from citesync.cite_sources import Identifier, Work, arxiv_id, doi, resolve_work
|
|
12
|
+
from citesync.config import Config
|
|
13
|
+
from citesync.errors import CheckError
|
|
14
|
+
from citesync.export import render
|
|
15
|
+
from citesync.formats import Doc
|
|
16
|
+
from citesync.mapping import Mapping, load_mapping, source_pin
|
|
17
|
+
from citesync.write import citation_file
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _render(work: Work, fmt: str, mapping: Mapping) -> tuple[str, list[str]]:
|
|
21
|
+
if fmt not in {"cff", "codemeta"}:
|
|
22
|
+
return render(fmt, work.record, kind=work.kind)
|
|
23
|
+
if work.kind not in {"software", "dataset"}:
|
|
24
|
+
msg = f"{fmt} is available for software and dataset citations"
|
|
25
|
+
raise CheckError(msg)
|
|
26
|
+
if fmt == "cff" and not work.record.get("author"):
|
|
27
|
+
msg = f"{work.source}: CFF requires at least one named author"
|
|
28
|
+
raise CheckError(msg)
|
|
29
|
+
doc = Doc(work.source, "", work.record, frozenset(), None, release=True)
|
|
30
|
+
with TemporaryDirectory() as root:
|
|
31
|
+
text, skipped = citation_file(fmt, Path(root), Config(), doc, mapping, resource_type=work.kind)
|
|
32
|
+
return text, [f"leaving out {term}: {reason}" for term, reason in skipped.items()]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _unversioned(arxiv: str) -> str:
|
|
36
|
+
return re.sub(r"v\d+$", "", arxiv, flags=re.IGNORECASE).casefold()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _check_evidence(work: Work, evidence: dict[str, object]) -> None:
|
|
40
|
+
source_doi = doi(evidence.get("doi"))
|
|
41
|
+
work_doi = doi(work.record.get("identifier"))
|
|
42
|
+
if source_doi and work_doi and source_doi.casefold() == work_doi.casefold():
|
|
43
|
+
return
|
|
44
|
+
location = evidence.get("primary_location")
|
|
45
|
+
landing = location.get("landing_page_url") if isinstance(location, dict) else None
|
|
46
|
+
if (
|
|
47
|
+
isinstance(landing, str)
|
|
48
|
+
and (source_arxiv := arxiv_id(landing))
|
|
49
|
+
and work.record.get("arxiv")
|
|
50
|
+
and _unversioned(source_arxiv) == _unversioned(work.record["arxiv"])
|
|
51
|
+
):
|
|
52
|
+
return
|
|
53
|
+
msg = "OpenAlex work does not match the citation's DOI or arXiv ID"
|
|
54
|
+
raise CheckError(msg)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def cite(
|
|
58
|
+
query: Identifier,
|
|
59
|
+
fmt: str,
|
|
60
|
+
*,
|
|
61
|
+
preferred: bool,
|
|
62
|
+
openalex: str | None,
|
|
63
|
+
replay: Path | None,
|
|
64
|
+
save_responses: Path | None,
|
|
65
|
+
) -> tuple[str, list[str], dict[str, object]]:
|
|
66
|
+
"""Resolve and render one citation with its exact source and optional evidence."""
|
|
67
|
+
package = Path(__file__).parent
|
|
68
|
+
mapping_hash = sha256((package / "mapping-local.json").read_bytes()).hexdigest()
|
|
69
|
+
http = Responses(mapping_hash, replay)
|
|
70
|
+
mapping = load_mapping()
|
|
71
|
+
work = resolve_work(query, http, mapping)
|
|
72
|
+
selected = work
|
|
73
|
+
if preferred:
|
|
74
|
+
if work.preferred is None:
|
|
75
|
+
msg = work.preferred_issue or f"{work.source}: no preferred citation"
|
|
76
|
+
raise CheckError(msg)
|
|
77
|
+
selected = work.preferred
|
|
78
|
+
|
|
79
|
+
text, notes = _render(selected, fmt, mapping)
|
|
80
|
+
evidence = openalex_evidence(openalex, http.required) if openalex else None
|
|
81
|
+
if evidence is not None:
|
|
82
|
+
_check_evidence(selected, evidence)
|
|
83
|
+
if save_responses is not None:
|
|
84
|
+
http.save(save_responses)
|
|
85
|
+
result: dict[str, object] = {
|
|
86
|
+
"input": asdict(query),
|
|
87
|
+
"work": asdict(work),
|
|
88
|
+
"selected": "preferred" if preferred else "main",
|
|
89
|
+
"citation": {"format": fmt, "text": text},
|
|
90
|
+
"notes": notes,
|
|
91
|
+
"provenance": {**http.manifest(), "mapping": source_pin()},
|
|
92
|
+
}
|
|
93
|
+
if evidence is not None:
|
|
94
|
+
result["openalex"] = evidence
|
|
95
|
+
return text, notes, result
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Read attribution and reference evidence for one OpenAlex work."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
|
|
7
|
+
from citesync.errors import CheckError
|
|
8
|
+
|
|
9
|
+
_WORK_PREFIX = "https://openalex.org/"
|
|
10
|
+
_API = "https://api.openalex.org/works"
|
|
11
|
+
_WORK_ID = re.compile(r"W[0-9]{1,20}")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def work_id(value: str) -> str | None:
|
|
15
|
+
"""An explicit OpenAlex work ID, with or without its public URL."""
|
|
16
|
+
bare = value.removeprefix(_WORK_PREFIX)
|
|
17
|
+
return bare if _WORK_ID.fullmatch(bare) else None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def openalex_work(work: str, request: Callable[[str], bytes]) -> dict[str, object]:
|
|
21
|
+
"""Read an explicitly selected OpenAlex work and verify its identity."""
|
|
22
|
+
record = _response(request, f"{_API}/{work}")
|
|
23
|
+
identity = _nullable_text(record, "id", "work")
|
|
24
|
+
if identity is None or work_id(identity) != work:
|
|
25
|
+
msg = f"OpenAlex returned another work or no ID for {work}"
|
|
26
|
+
raise CheckError(msg)
|
|
27
|
+
return record
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def openalex_evidence(work: str, request: Callable[[str], bytes]) -> dict[str, object]:
|
|
31
|
+
"""Read a work and its reference list, keeping claims scoped to their provider and work."""
|
|
32
|
+
if (canonical := work_id(work)) is None:
|
|
33
|
+
msg = "expected an OpenAlex work ID such as W1234 or https://openalex.org/W1234"
|
|
34
|
+
raise CheckError(msg)
|
|
35
|
+
record = openalex_work(canonical, request)
|
|
36
|
+
doi = _nullable_text(record, "doi", "work")
|
|
37
|
+
location = record.get("primary_location")
|
|
38
|
+
landing_page = (
|
|
39
|
+
_nullable_text(_object(location, "primary_location"), "landing_page_url", "primary_location")
|
|
40
|
+
if location is not None
|
|
41
|
+
else None
|
|
42
|
+
)
|
|
43
|
+
authorships = [_authorship(item) for item in _array(record.get("authorships"), "authorships")]
|
|
44
|
+
references = _array(_response(request, f"{_API}/{canonical}/references").get("references"), "references")
|
|
45
|
+
return {
|
|
46
|
+
"provider": "openalex",
|
|
47
|
+
"work_id": canonical,
|
|
48
|
+
"doi": doi,
|
|
49
|
+
"primary_location": {"landing_page_url": landing_page} if location is not None else None,
|
|
50
|
+
"authorships": authorships,
|
|
51
|
+
"references": [_reference(item) for item in references],
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _authorship(item: object) -> dict[str, object]:
|
|
56
|
+
authorship = _object(item, "authorships entry")
|
|
57
|
+
identity = authorship.get("author")
|
|
58
|
+
author = _object(identity, "authorships.author") if identity is not None else {}
|
|
59
|
+
roles = _array(authorship.get("contributor_roles", []), "authorships.contributor_roles")
|
|
60
|
+
return {
|
|
61
|
+
"author_id": _nullable_text(author, "id", "authorships.author"),
|
|
62
|
+
"orcid": _nullable_text(author, "orcid", "authorships.author"),
|
|
63
|
+
"raw_author_name": _nullable_text(authorship, "raw_author_name", "authorships"),
|
|
64
|
+
"contributor_roles": [_role(item) for item in roles],
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _role(item: object) -> dict[str, str | None]:
|
|
69
|
+
field = "authorships.contributor_roles"
|
|
70
|
+
role = _object(item, field)
|
|
71
|
+
identity = _nullable_text(role, "id", field)
|
|
72
|
+
if not identity:
|
|
73
|
+
msg = f"OpenAlex {field}.id is missing"
|
|
74
|
+
raise CheckError(msg)
|
|
75
|
+
return {"id": identity, "display_name": _nullable_text(role, "display_name", field)}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _reference(item: object) -> dict[str, str | None]:
|
|
79
|
+
reference = _object(item, "references entry")
|
|
80
|
+
return {key: _nullable_text(reference, key, "references") for key in ("raw_reference_string", "raw_doi", "work_id")}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _response(request: Callable[[str], bytes], url: str) -> dict[str, object]:
|
|
84
|
+
content = request(url)
|
|
85
|
+
try:
|
|
86
|
+
parsed = json.loads(content)
|
|
87
|
+
except (ValueError, RecursionError) as error:
|
|
88
|
+
msg = "OpenAlex returned invalid JSON"
|
|
89
|
+
raise CheckError(msg) from error
|
|
90
|
+
return _object(parsed, "response")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _object(value: object, field: str) -> dict[str, object]:
|
|
94
|
+
if not isinstance(value, dict):
|
|
95
|
+
msg = f"OpenAlex {field} is not an object"
|
|
96
|
+
raise CheckError(msg)
|
|
97
|
+
return value
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _array(value: object, field: str) -> list[object]:
|
|
101
|
+
if not isinstance(value, list):
|
|
102
|
+
msg = f"OpenAlex {field} is not a list"
|
|
103
|
+
raise CheckError(msg)
|
|
104
|
+
return value
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _nullable_text(obj: dict[str, object], key: str, field: str) -> str | None:
|
|
108
|
+
value = obj.get(key)
|
|
109
|
+
if value is not None and not isinstance(value, str):
|
|
110
|
+
msg = f"OpenAlex {field}.{key} is not text or null"
|
|
111
|
+
raise CheckError(msg)
|
|
112
|
+
return value
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""Fetch citation metadata from known services and replay recorded responses."""
|
|
2
|
+
|
|
3
|
+
import datetime as dt
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
import stat
|
|
9
|
+
import tempfile
|
|
10
|
+
from dataclasses import asdict, dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from urllib.error import HTTPError, URLError
|
|
13
|
+
from urllib.parse import urlsplit
|
|
14
|
+
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|
15
|
+
|
|
16
|
+
from citesync.errors import CheckError
|
|
17
|
+
|
|
18
|
+
_MAX_BYTES = 4_000_000
|
|
19
|
+
_MAX_RESPONSES = 10
|
|
20
|
+
_HOSTS = {
|
|
21
|
+
"api.crossref.org": "crossref",
|
|
22
|
+
"api.datacite.org": "datacite",
|
|
23
|
+
"export.arxiv.org": "arxiv",
|
|
24
|
+
"api.github.com": "github",
|
|
25
|
+
"raw.githubusercontent.com": "github",
|
|
26
|
+
"api.openalex.org": "openalex",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _NoRedirect(HTTPRedirectHandler):
|
|
31
|
+
def redirect_request(self, *_args: object, **_kwargs: object) -> None:
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def fetch(url: str) -> tuple[int, bytes]:
|
|
36
|
+
"""Read a bounded response without following redirects or sending credentials."""
|
|
37
|
+
provider = _provider(url)
|
|
38
|
+
request = Request( # noqa: S310 - _provider checks HTTPS and the full host against the allowlist
|
|
39
|
+
url, headers={"User-Agent": "citesync (https://github.com/simonvanlierde/citesync)"}
|
|
40
|
+
)
|
|
41
|
+
try:
|
|
42
|
+
with build_opener(_NoRedirect()).open(request, timeout=15) as response:
|
|
43
|
+
data = response.read(_MAX_BYTES + 1)
|
|
44
|
+
except HTTPError as err:
|
|
45
|
+
with err:
|
|
46
|
+
if err.code == 404:
|
|
47
|
+
return 404, b""
|
|
48
|
+
if err.code in {301, 308}:
|
|
49
|
+
msg = f"{provider} reports the resource moved (HTTP {err.code}); cite its current URL"
|
|
50
|
+
else:
|
|
51
|
+
msg = f"{provider} unavailable (HTTP {err.code})"
|
|
52
|
+
raise CheckError(msg) from err
|
|
53
|
+
except (URLError, OSError) as err:
|
|
54
|
+
msg = f"{provider} unavailable"
|
|
55
|
+
raise CheckError(msg) from err
|
|
56
|
+
if len(data) > _MAX_BYTES:
|
|
57
|
+
msg = "citation metadata response exceeds 4 MB"
|
|
58
|
+
raise CheckError(msg)
|
|
59
|
+
return 200, data
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _provider(url: str) -> str:
|
|
63
|
+
parsed = urlsplit(url)
|
|
64
|
+
provider = _HOSTS.get(parsed.netloc)
|
|
65
|
+
if provider is None or parsed.scheme != "https" or parsed.fragment:
|
|
66
|
+
msg = "unsupported citation metadata endpoint"
|
|
67
|
+
raise CheckError(msg)
|
|
68
|
+
return provider
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True)
|
|
72
|
+
class Response:
|
|
73
|
+
"""One response and the evidence needed to verify it."""
|
|
74
|
+
|
|
75
|
+
provider: str
|
|
76
|
+
url: str
|
|
77
|
+
status: int
|
|
78
|
+
retrieved_at: str
|
|
79
|
+
sha256: str
|
|
80
|
+
file: str
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _read(path: Path) -> bytes:
|
|
84
|
+
expected = path.lstat()
|
|
85
|
+
msg = f"{path.name}: expected a regular file in the citation capture"
|
|
86
|
+
if not stat.S_ISREG(expected.st_mode):
|
|
87
|
+
raise CheckError(msg)
|
|
88
|
+
# The directory entry can change between inspection and open.
|
|
89
|
+
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
|
|
90
|
+
with os.fdopen(os.open(path, flags), "rb") as stream:
|
|
91
|
+
opened = os.fstat(stream.fileno())
|
|
92
|
+
if not stat.S_ISREG(opened.st_mode) or not os.path.samestat(expected, opened):
|
|
93
|
+
raise CheckError(msg)
|
|
94
|
+
data = stream.read(_MAX_BYTES + 1)
|
|
95
|
+
if len(data) > _MAX_BYTES:
|
|
96
|
+
msg = f"{path.name}: citation response exceeds 4 MB"
|
|
97
|
+
raise CheckError(msg)
|
|
98
|
+
return data
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass
|
|
102
|
+
class Responses:
|
|
103
|
+
"""Live metadata response capture, or a replay that never calls the network."""
|
|
104
|
+
|
|
105
|
+
mapping: str
|
|
106
|
+
replay: Path | None = None
|
|
107
|
+
_records: dict[str, tuple[Response, bytes]] = field(default_factory=dict, init=False)
|
|
108
|
+
|
|
109
|
+
def __post_init__(self) -> None:
|
|
110
|
+
if self.replay is None:
|
|
111
|
+
return
|
|
112
|
+
try:
|
|
113
|
+
manifest = json.loads(_read(self.replay / "responses.json"))
|
|
114
|
+
if manifest["schema_version"] != 1 or manifest["mapping_sha256"] != self.mapping:
|
|
115
|
+
msg = "citation capture uses a different schema or mapping"
|
|
116
|
+
raise CheckError(msg)
|
|
117
|
+
rows = manifest["responses"]
|
|
118
|
+
if not isinstance(rows, list) or len(rows) > _MAX_RESPONSES:
|
|
119
|
+
msg = "citation capture has an invalid response list"
|
|
120
|
+
raise CheckError(msg)
|
|
121
|
+
for index, row in enumerate(rows, 1):
|
|
122
|
+
record = Response(**row)
|
|
123
|
+
if not self._valid(record, index):
|
|
124
|
+
msg = f"citation capture has an invalid response at position {index}"
|
|
125
|
+
raise CheckError(msg)
|
|
126
|
+
body = _read(self.replay / record.file)
|
|
127
|
+
if hashlib.sha256(body).hexdigest() != record.sha256:
|
|
128
|
+
msg = f"citation capture checksum differs for {record.file}"
|
|
129
|
+
raise CheckError(msg)
|
|
130
|
+
self._records[record.url] = record, body
|
|
131
|
+
except (OSError, ValueError, KeyError, TypeError, AttributeError, RecursionError) as err:
|
|
132
|
+
msg = "cannot read citation capture"
|
|
133
|
+
raise CheckError(msg) from err
|
|
134
|
+
|
|
135
|
+
def _valid(self, record: Response, index: int) -> bool:
|
|
136
|
+
url = urlsplit(record.url)
|
|
137
|
+
provider = _HOSTS.get(url.netloc)
|
|
138
|
+
timestamp = dt.datetime.fromisoformat(record.retrieved_at)
|
|
139
|
+
return (
|
|
140
|
+
record.file == f"response-{index}.bin"
|
|
141
|
+
and provider is not None
|
|
142
|
+
and provider == record.provider
|
|
143
|
+
and url.scheme == "https"
|
|
144
|
+
and not url.fragment
|
|
145
|
+
and record.url not in self._records
|
|
146
|
+
and type(record.status) is int
|
|
147
|
+
and record.status in {200, 404}
|
|
148
|
+
and timestamp.utcoffset() == dt.timedelta()
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
def get(self, url: str) -> bytes | None:
|
|
152
|
+
"""Return response bytes, or None on HTTP 404."""
|
|
153
|
+
provider = _provider(url)
|
|
154
|
+
if url not in self._records:
|
|
155
|
+
if self.replay is not None:
|
|
156
|
+
msg = f"citation capture lacks a response for {provider}"
|
|
157
|
+
raise CheckError(msg)
|
|
158
|
+
status, body = fetch(url)
|
|
159
|
+
record = Response(
|
|
160
|
+
provider,
|
|
161
|
+
url,
|
|
162
|
+
status,
|
|
163
|
+
dt.datetime.now(dt.UTC).isoformat(timespec="seconds"),
|
|
164
|
+
hashlib.sha256(body).hexdigest(),
|
|
165
|
+
f"response-{len(self._records) + 1}.bin",
|
|
166
|
+
)
|
|
167
|
+
self._records[url] = record, body
|
|
168
|
+
record, body = self._records[url]
|
|
169
|
+
return body if record.status == 200 else None
|
|
170
|
+
|
|
171
|
+
def required(self, url: str) -> bytes:
|
|
172
|
+
"""Return response bytes, raising if the provider has no such resource."""
|
|
173
|
+
body = self.get(url)
|
|
174
|
+
if body is None:
|
|
175
|
+
msg = f"no record at {_HOSTS[urlsplit(url).netloc]}"
|
|
176
|
+
raise CheckError(msg)
|
|
177
|
+
return body
|
|
178
|
+
|
|
179
|
+
def manifest(self) -> dict[str, object]:
|
|
180
|
+
"""Report hashes, URLs and timestamps without embedding provider payloads."""
|
|
181
|
+
return {
|
|
182
|
+
"schema_version": 1,
|
|
183
|
+
"mapping_sha256": self.mapping,
|
|
184
|
+
"responses": [asdict(record) for record, _ in self._records.values()],
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
def save(self, destination: Path) -> None:
|
|
188
|
+
"""Save raw responses to a new directory, which appears only once every file is written."""
|
|
189
|
+
staging = None
|
|
190
|
+
try:
|
|
191
|
+
staging = Path(tempfile.mkdtemp(prefix=f".{destination.name}.", dir=destination.parent))
|
|
192
|
+
for record, body in self._records.values():
|
|
193
|
+
(staging / record.file).write_bytes(body)
|
|
194
|
+
(staging / "responses.json").write_text(json.dumps(self.manifest(), indent=2) + "\n", encoding="utf-8")
|
|
195
|
+
staging.rename(destination)
|
|
196
|
+
except OSError as err:
|
|
197
|
+
if staging is not None:
|
|
198
|
+
shutil.rmtree(staging, ignore_errors=True)
|
|
199
|
+
msg = f"{destination}: can't save responses: {err.strerror}"
|
|
200
|
+
raise CheckError(msg) from err
|