claimlink 1.0.0__py3-none-any.whl
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.
- claimlink/__init__.py +6 -0
- claimlink/artifacts.py +191 -0
- claimlink/cli.py +115 -0
- claimlink/core.py +127 -0
- claimlink/errors.py +25 -0
- claimlink/keys.py +23 -0
- claimlink/latex.py +622 -0
- claimlink/location.py +163 -0
- claimlink/nbconvert.py +43 -0
- claimlink/serialization.py +104 -0
- claimlink/storage.py +133 -0
- claimlink-1.0.0.dist-info/METADATA +127 -0
- claimlink-1.0.0.dist-info/RECORD +16 -0
- claimlink-1.0.0.dist-info/WHEEL +4 -0
- claimlink-1.0.0.dist-info/entry_points.txt +2 -0
- claimlink-1.0.0.dist-info/licenses/LICENSE +21 -0
claimlink/__init__.py
ADDED
claimlink/artifacts.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Save figures and tables as files tracked in the claim lock."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
import warnings
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from . import keys, location, storage
|
|
13
|
+
from .errors import (
|
|
14
|
+
ArtifactError,
|
|
15
|
+
ClaimExportError,
|
|
16
|
+
ClaimLocationUnavailableWarning,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def artifact(
|
|
21
|
+
name: str,
|
|
22
|
+
payload: object,
|
|
23
|
+
*,
|
|
24
|
+
description: str | None = None,
|
|
25
|
+
**save_options: object,
|
|
26
|
+
) -> Path:
|
|
27
|
+
"""Save payload as a tracked artifact and return its path."""
|
|
28
|
+
_validate(name, description)
|
|
29
|
+
try:
|
|
30
|
+
key = keys.claim_key(name)
|
|
31
|
+
except ClaimExportError:
|
|
32
|
+
raise ArtifactError(
|
|
33
|
+
f"artifact name {name!r} contains no characters usable for a key"
|
|
34
|
+
) from None
|
|
35
|
+
saver, kind, suffix, options = _saver(payload, save_options)
|
|
36
|
+
|
|
37
|
+
root = storage.project_root()
|
|
38
|
+
lock = storage.lock_path(root)
|
|
39
|
+
registry = storage.load(lock)
|
|
40
|
+
artifacts = registry.get("artifacts", {})
|
|
41
|
+
for claim_name in registry.get("claims", {}):
|
|
42
|
+
try:
|
|
43
|
+
claim_key = keys.claim_key(claim_name)
|
|
44
|
+
except ClaimExportError:
|
|
45
|
+
continue
|
|
46
|
+
if claim_key == key:
|
|
47
|
+
raise ArtifactError(
|
|
48
|
+
f"artifact {name!r} collides with claim {claim_name!r} "
|
|
49
|
+
f"on the key {key!r}"
|
|
50
|
+
)
|
|
51
|
+
for other_name in artifacts:
|
|
52
|
+
if other_name == name:
|
|
53
|
+
continue
|
|
54
|
+
try:
|
|
55
|
+
other_key = keys.claim_key(other_name)
|
|
56
|
+
except ClaimExportError:
|
|
57
|
+
continue
|
|
58
|
+
if other_key == key:
|
|
59
|
+
raise ArtifactError(
|
|
60
|
+
f"artifact {name!r} collides with artifact {other_name!r} "
|
|
61
|
+
f"on the key {key!r}"
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
directory = lock.parent / "artifacts"
|
|
65
|
+
target = directory / f"{key}.{suffix}"
|
|
66
|
+
existing = artifacts.get(name)
|
|
67
|
+
previous_target = None
|
|
68
|
+
if isinstance(existing, dict) and isinstance(existing.get("path"), str):
|
|
69
|
+
previous_target = (lock.parent / existing["path"]).resolve()
|
|
70
|
+
if (target.exists() or target.is_symlink()) and (
|
|
71
|
+
target.resolve() != previous_target
|
|
72
|
+
):
|
|
73
|
+
raise ArtifactError(f"refusing to overwrite untracked artifact file {target}")
|
|
74
|
+
|
|
75
|
+
current, unavailable = location.detect_location(root)
|
|
76
|
+
for message in unavailable:
|
|
77
|
+
warnings.warn(
|
|
78
|
+
f"Artifact {name!r}: {message}.",
|
|
79
|
+
ClaimLocationUnavailableWarning,
|
|
80
|
+
stacklevel=2,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
84
|
+
fd, temp_name = tempfile.mkstemp(
|
|
85
|
+
dir=directory, prefix=f".{key}.", suffix=f".{suffix}"
|
|
86
|
+
)
|
|
87
|
+
temp = Path(temp_name)
|
|
88
|
+
try:
|
|
89
|
+
os.close(fd)
|
|
90
|
+
if kind == "text":
|
|
91
|
+
temp.write_bytes(payload.encode("utf-8"))
|
|
92
|
+
else:
|
|
93
|
+
saver(temp, **options)
|
|
94
|
+
# Hash before the replace so a post-replace failure never re-reads target.
|
|
95
|
+
data = temp.read_bytes()
|
|
96
|
+
os.replace(temp, target)
|
|
97
|
+
except BaseException:
|
|
98
|
+
try:
|
|
99
|
+
os.unlink(temp)
|
|
100
|
+
except OSError:
|
|
101
|
+
pass
|
|
102
|
+
raise
|
|
103
|
+
|
|
104
|
+
now = _now()
|
|
105
|
+
created_at = (existing.get("created_at") or now) if existing else now
|
|
106
|
+
artifacts = dict(artifacts)
|
|
107
|
+
artifacts[name] = {
|
|
108
|
+
"name": name,
|
|
109
|
+
"path": f"artifacts/{target.name}",
|
|
110
|
+
"description": description,
|
|
111
|
+
"location": current,
|
|
112
|
+
"file": {"sha256": hashlib.sha256(data).hexdigest(), "size": len(data)},
|
|
113
|
+
"created_at": created_at,
|
|
114
|
+
"updated_at": now,
|
|
115
|
+
}
|
|
116
|
+
registry["artifacts"] = artifacts
|
|
117
|
+
try:
|
|
118
|
+
storage.save(lock, registry)
|
|
119
|
+
except BaseException:
|
|
120
|
+
# Remove a new target, including a re-registration with a different
|
|
121
|
+
# format (pdf -> png), so it does not linger untracked and block retries.
|
|
122
|
+
if previous_target is None or target.resolve() != previous_target:
|
|
123
|
+
try:
|
|
124
|
+
os.unlink(target)
|
|
125
|
+
except OSError:
|
|
126
|
+
pass
|
|
127
|
+
raise
|
|
128
|
+
return target
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _validate(name: object, description: object) -> None:
|
|
132
|
+
"""Validate name and description like claim() does."""
|
|
133
|
+
if not isinstance(name, str):
|
|
134
|
+
raise TypeError(f"artifact name must be a string, got {type(name).__name__}")
|
|
135
|
+
if not name.strip():
|
|
136
|
+
raise ValueError("artifact name must not be empty")
|
|
137
|
+
if description is not None and not isinstance(description, str):
|
|
138
|
+
raise TypeError(
|
|
139
|
+
"artifact description must be a string or None, "
|
|
140
|
+
f"got {type(description).__name__}"
|
|
141
|
+
)
|
|
142
|
+
for label, text in (("name", name), ("description", description)):
|
|
143
|
+
if text is not None:
|
|
144
|
+
try:
|
|
145
|
+
text.encode("utf-8")
|
|
146
|
+
except UnicodeEncodeError:
|
|
147
|
+
raise ValueError(
|
|
148
|
+
f"artifact {label} is not valid UTF-8 (unpaired surrogate)"
|
|
149
|
+
) from None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _saver(payload: object, save_options: dict) -> tuple:
|
|
153
|
+
"""Return (saver, kind, suffix, options) for a payload in detection order."""
|
|
154
|
+
options = dict(save_options)
|
|
155
|
+
value = options.pop("format", None)
|
|
156
|
+
suffix = None
|
|
157
|
+
if value is not None:
|
|
158
|
+
suffix = str(value).lower().lstrip(".")
|
|
159
|
+
if not (suffix.isascii() and suffix.isalnum()):
|
|
160
|
+
raise ArtifactError(f"invalid artifact format {value!r}")
|
|
161
|
+
options["format"] = suffix
|
|
162
|
+
if isinstance(payload, str):
|
|
163
|
+
if options:
|
|
164
|
+
raise ArtifactError("a string artifact does not accept save options")
|
|
165
|
+
return None, "text", "tex", options
|
|
166
|
+
if hasattr(payload, "savefig"):
|
|
167
|
+
saver, kind, default = payload.savefig, "savefig", "pdf"
|
|
168
|
+
elif hasattr(payload, "write_image"):
|
|
169
|
+
saver, kind, default = payload.write_image, "write_image", "pdf"
|
|
170
|
+
elif hasattr(payload, "to_latex"):
|
|
171
|
+
saver, kind, default = payload.to_latex, "to_latex", "tex"
|
|
172
|
+
elif hasattr(payload, "save"):
|
|
173
|
+
saver, kind, default = payload.save, "save", "pdf"
|
|
174
|
+
else:
|
|
175
|
+
raise TypeError(
|
|
176
|
+
f"unsupported artifact payload type: {type(payload).__name__}; "
|
|
177
|
+
"expected a string or an object with savefig(), write_image(), "
|
|
178
|
+
"to_latex() or save()"
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
suffix = suffix or default
|
|
182
|
+
if kind == "to_latex":
|
|
183
|
+
if suffix != "tex":
|
|
184
|
+
raise ArtifactError("a to_latex artifact must use the 'tex' format")
|
|
185
|
+
options.pop("format", None)
|
|
186
|
+
return saver, kind, suffix, options
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _now() -> str:
|
|
190
|
+
"""Return the current UTC timestamp in the lock file format."""
|
|
191
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
claimlink/cli.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Command-line interface for ClaimLink."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from claimlink import latex, storage
|
|
12
|
+
from claimlink.errors import ClaimExportError, ClaimLockError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
16
|
+
parser = argparse.ArgumentParser(
|
|
17
|
+
prog="claimlink", description="Export ClaimLink claims to LaTeX."
|
|
18
|
+
)
|
|
19
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
20
|
+
export = commands.add_parser("export", help="write a claims.tex file")
|
|
21
|
+
export.add_argument(
|
|
22
|
+
"--input", type=Path, default=storage.project_root() / storage.LOCK_FILENAME
|
|
23
|
+
)
|
|
24
|
+
export.add_argument(
|
|
25
|
+
"--output",
|
|
26
|
+
type=Path,
|
|
27
|
+
default=Path("."),
|
|
28
|
+
help="destination directory for the claimlink/ export tree",
|
|
29
|
+
)
|
|
30
|
+
export.set_defaults(handler=_export)
|
|
31
|
+
return parser
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _require_file(path: Path) -> None:
|
|
35
|
+
if not path.is_file():
|
|
36
|
+
reason = "is not a file" if path.exists() else "file not found"
|
|
37
|
+
raise ClaimLockError(f"cannot read {path}: {reason}")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _announce(output: Path) -> None:
|
|
41
|
+
if sys.stdout is None:
|
|
42
|
+
return
|
|
43
|
+
try:
|
|
44
|
+
print(f"Wrote {output}")
|
|
45
|
+
sys.stdout.flush()
|
|
46
|
+
except OSError:
|
|
47
|
+
devnull = os.open(os.devnull, os.O_WRONLY)
|
|
48
|
+
try:
|
|
49
|
+
os.dup2(devnull, sys.stdout.fileno())
|
|
50
|
+
finally:
|
|
51
|
+
os.close(devnull)
|
|
52
|
+
except UnicodeEncodeError:
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _export(args: argparse.Namespace) -> int:
|
|
57
|
+
_require_file(args.input)
|
|
58
|
+
if args.output.exists() and not args.output.is_dir():
|
|
59
|
+
raise ClaimExportError(f"output path is not a directory: {args.output}")
|
|
60
|
+
registry = storage.load(args.input)
|
|
61
|
+
artifacts = registry.get("artifacts", {})
|
|
62
|
+
by_key = {latex.claim_key(record["name"]): record for record in artifacts.values()}
|
|
63
|
+
|
|
64
|
+
def resolve(record: dict) -> Path:
|
|
65
|
+
source = Path(record["path"])
|
|
66
|
+
if not source.is_absolute():
|
|
67
|
+
source = args.input.parent / source
|
|
68
|
+
if not source.is_file():
|
|
69
|
+
raise ClaimExportError(
|
|
70
|
+
f"artifact {record['name']!r}: file not found: {source}"
|
|
71
|
+
)
|
|
72
|
+
return source
|
|
73
|
+
|
|
74
|
+
sources = {key: resolve(by_key[key]) for key in sorted(by_key)}
|
|
75
|
+
|
|
76
|
+
def kind_of(source: Path) -> str:
|
|
77
|
+
return "tables" if source.suffix.lower() == ".tex" else "figures"
|
|
78
|
+
|
|
79
|
+
destinations: dict[tuple[str, str], str] = {}
|
|
80
|
+
emitted: dict[str, str] = {}
|
|
81
|
+
for key in sorted(sources):
|
|
82
|
+
source = sources[key]
|
|
83
|
+
kind = kind_of(source)
|
|
84
|
+
name = by_key[key]["name"]
|
|
85
|
+
if (kind, source.name) in destinations:
|
|
86
|
+
other = destinations[(kind, source.name)]
|
|
87
|
+
raise ClaimExportError(
|
|
88
|
+
f"artifacts {other!r} and {name!r} would both be written "
|
|
89
|
+
f"to {kind}/{source.name}"
|
|
90
|
+
)
|
|
91
|
+
destinations[(kind, source.name)] = name
|
|
92
|
+
emitted[key] = f"claimlink/{kind}/{source.name}"
|
|
93
|
+
|
|
94
|
+
text = latex.generate(registry, paths=emitted)
|
|
95
|
+
data = text.encode("utf-8")
|
|
96
|
+
|
|
97
|
+
root = args.output / "claimlink"
|
|
98
|
+
(root / "figures").mkdir(parents=True, exist_ok=True)
|
|
99
|
+
(root / "tables").mkdir(parents=True, exist_ok=True)
|
|
100
|
+
for key in sorted(sources):
|
|
101
|
+
source = sources[key]
|
|
102
|
+
shutil.copyfile(source, root / kind_of(source) / source.name)
|
|
103
|
+
claims_path = root / "claims.tex"
|
|
104
|
+
claims_path.write_bytes(data)
|
|
105
|
+
_announce(claims_path)
|
|
106
|
+
return 0
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def main(argv: list[str] | None = None) -> int:
|
|
110
|
+
args = _build_parser().parse_args(argv)
|
|
111
|
+
try:
|
|
112
|
+
return args.handler(args)
|
|
113
|
+
except (ClaimLockError, ClaimExportError, OSError, UnicodeError) as exc:
|
|
114
|
+
print(f"claimlink: error: {exc}", file=sys.stderr)
|
|
115
|
+
return 1
|
claimlink/core.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Register scientific claims in the project's claim-lock.json file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import warnings
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
|
|
9
|
+
from . import location, serialization, storage
|
|
10
|
+
from .errors import (
|
|
11
|
+
ClaimLocationChangedWarning,
|
|
12
|
+
ClaimLocationUnavailableWarning,
|
|
13
|
+
ClaimValueChangedWarning,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def claim(
|
|
18
|
+
name: str,
|
|
19
|
+
value: object,
|
|
20
|
+
*,
|
|
21
|
+
unit: str | None = None,
|
|
22
|
+
description: str | None = None,
|
|
23
|
+
) -> None:
|
|
24
|
+
"""Record a claim, warning about changed values or locations."""
|
|
25
|
+
if not isinstance(name, str):
|
|
26
|
+
raise TypeError(f"claim name must be a string, got {type(name).__name__}")
|
|
27
|
+
if not name.strip():
|
|
28
|
+
raise ValueError("claim name must not be empty")
|
|
29
|
+
for label, argument in (("unit", unit), ("description", description)):
|
|
30
|
+
if argument is not None and not isinstance(argument, str):
|
|
31
|
+
raise TypeError(
|
|
32
|
+
f"claim {label} must be a string or None, got {type(argument).__name__}"
|
|
33
|
+
)
|
|
34
|
+
for label, text in (("name", name), ("unit", unit), ("description", description)):
|
|
35
|
+
if text is not None:
|
|
36
|
+
try:
|
|
37
|
+
text.encode("utf-8")
|
|
38
|
+
except UnicodeEncodeError:
|
|
39
|
+
raise ValueError(
|
|
40
|
+
f"claim {label} is not valid UTF-8 (unpaired surrogate)"
|
|
41
|
+
) from None
|
|
42
|
+
|
|
43
|
+
normalized = serialization.normalize(value)
|
|
44
|
+
vtype = serialization.value_type(normalized)
|
|
45
|
+
|
|
46
|
+
root = storage.project_root()
|
|
47
|
+
path = storage.lock_path(root)
|
|
48
|
+
registry = storage.load(path)
|
|
49
|
+
current, unavailable = location.detect_location(root)
|
|
50
|
+
for message in unavailable:
|
|
51
|
+
warnings.warn(
|
|
52
|
+
f"Claim {name!r}: {message}.",
|
|
53
|
+
ClaimLocationUnavailableWarning,
|
|
54
|
+
stacklevel=2,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
now = _now()
|
|
58
|
+
claims = registry.setdefault("claims", {})
|
|
59
|
+
existing = claims.get(name)
|
|
60
|
+
if existing is None:
|
|
61
|
+
record = {
|
|
62
|
+
"name": name,
|
|
63
|
+
"value": normalized,
|
|
64
|
+
"value_type": vtype,
|
|
65
|
+
"unit": unit,
|
|
66
|
+
"description": description,
|
|
67
|
+
"location": current,
|
|
68
|
+
"created_at": now,
|
|
69
|
+
"updated_at": now,
|
|
70
|
+
}
|
|
71
|
+
else:
|
|
72
|
+
previous = existing.get("value")
|
|
73
|
+
if serialization.canonical(previous) != serialization.canonical(normalized):
|
|
74
|
+
warnings.warn(
|
|
75
|
+
f"Claim {name!r} changed:\n"
|
|
76
|
+
f" Previous value: {json.dumps(previous, ensure_ascii=False)}\n"
|
|
77
|
+
f" New value: {json.dumps(normalized, ensure_ascii=False)}\n\n"
|
|
78
|
+
"The claim-lock.json file has been updated.",
|
|
79
|
+
ClaimValueChangedWarning,
|
|
80
|
+
stacklevel=2,
|
|
81
|
+
)
|
|
82
|
+
canonical = existing.get("location")
|
|
83
|
+
if not isinstance(canonical, dict) or canonical.get("type") not in (
|
|
84
|
+
"script",
|
|
85
|
+
"notebook",
|
|
86
|
+
):
|
|
87
|
+
canonical = current
|
|
88
|
+
elif _identity(canonical) != _identity(current):
|
|
89
|
+
warnings.warn(
|
|
90
|
+
f"Claim {name!r} was declared from a different location:\n"
|
|
91
|
+
f" Canonical location: {_describe(canonical)}\n"
|
|
92
|
+
f" Current location: {_describe(current)}\n"
|
|
93
|
+
"The canonical location was kept.",
|
|
94
|
+
ClaimLocationChangedWarning,
|
|
95
|
+
stacklevel=2,
|
|
96
|
+
)
|
|
97
|
+
record = {
|
|
98
|
+
**existing,
|
|
99
|
+
"name": name,
|
|
100
|
+
"value": normalized,
|
|
101
|
+
"location": canonical,
|
|
102
|
+
"value_type": vtype,
|
|
103
|
+
"unit": unit,
|
|
104
|
+
"description": description,
|
|
105
|
+
"created_at": existing.get("created_at") or now,
|
|
106
|
+
"updated_at": now,
|
|
107
|
+
}
|
|
108
|
+
claims[name] = record
|
|
109
|
+
storage.save(path, registry)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _now() -> str:
|
|
113
|
+
"""Return the current UTC timestamp in the lock file format."""
|
|
114
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _identity(loc: dict) -> tuple:
|
|
118
|
+
"""Return the fields that identify a canonical location."""
|
|
119
|
+
return (loc.get("type"), loc.get("file"), loc.get("cell_id"), loc.get("line"))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _describe(loc: dict) -> str:
|
|
123
|
+
"""Return a one-line description of a source location."""
|
|
124
|
+
where = f"{loc.get('type')} {loc.get('file')}"
|
|
125
|
+
if loc.get("cell_id") is not None:
|
|
126
|
+
where += f" cell {loc['cell_id']}"
|
|
127
|
+
return f"{where} line {loc.get('line')}"
|
claimlink/errors.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Warnings and exceptions raised by ClaimLink."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ClaimLockError(Exception):
|
|
5
|
+
"""The claim lock file is unreadable, malformed, or has an unexpected shape."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ClaimExportError(Exception):
|
|
9
|
+
"""Claims could not be exported to LaTeX."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ArtifactError(Exception):
|
|
13
|
+
"""An artifact could not be saved or would overwrite another file."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ClaimValueChangedWarning(UserWarning):
|
|
17
|
+
"""A claim's value changed since it was last registered."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ClaimLocationChangedWarning(UserWarning):
|
|
21
|
+
"""A claim was registered from a location other than its canonical one."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ClaimLocationUnavailableWarning(UserWarning):
|
|
25
|
+
"""A claim's source location could not be fully determined."""
|
claimlink/keys.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Deterministic keys shared by claim export and artifact storage."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import unicodedata
|
|
5
|
+
|
|
6
|
+
from .errors import ClaimExportError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def claim_key(name: str) -> str:
|
|
10
|
+
"""Return the deterministic key used inside ``\\csname`` lookups."""
|
|
11
|
+
# ß has no NFKD decomposition and would be dropped; expand it like a casefold.
|
|
12
|
+
ascii_name = (
|
|
13
|
+
unicodedata.normalize("NFKD", name.replace("ß", "ss").replace("ẞ", "SS"))
|
|
14
|
+
.encode("ascii", "ignore")
|
|
15
|
+
.decode("ascii")
|
|
16
|
+
.lower()
|
|
17
|
+
)
|
|
18
|
+
key = re.sub(r"[^a-z0-9]+", "-", ascii_name).strip("-")
|
|
19
|
+
if not key:
|
|
20
|
+
raise ClaimExportError(
|
|
21
|
+
f"claim name {name!r} contains no characters usable for a key"
|
|
22
|
+
)
|
|
23
|
+
return key
|