pyrefman 0.1.0a1__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.
pyrefman/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """pyrefman — reference management as a Python library."""
2
+
3
+ from .api import ReferenceManager
4
+ from .core.model import Reference
5
+
6
+ __all__ = ["Reference", "ReferenceManager"]
@@ -0,0 +1,191 @@
1
+ """Adapters: the directory-backed repository and the default layout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+ import shutil
8
+ from pathlib import Path
9
+
10
+ import yaml
11
+
12
+ from ..core.model import Reference
13
+ from ..core.reconcile import Finding, ReconcileReport
14
+ from ..ports import Layout
15
+
16
+ RECORD_NAME = "refman.csl.yaml"
17
+
18
+
19
+ def _digest(path: Path) -> str:
20
+ return hashlib.sha256(path.read_bytes()).hexdigest()
21
+
22
+
23
+ class DefaultLayout:
24
+ """One directory per record: ``<root>/<year>-<key>/refman.csl.yaml``."""
25
+
26
+ def __init__(self, root: str | Path, pattern: str = "{year}-{key}") -> None:
27
+ self.root = Path(root)
28
+ self.pattern = pattern
29
+
30
+ def directory_for(self, reference: Reference) -> Path:
31
+ return self.root / self.pattern.format(year=reference.year, key=reference.citation_key)
32
+
33
+ def record_for(self, reference: Reference) -> Path:
34
+ return self.directory_for(reference) / RECORD_NAME
35
+
36
+
37
+ class DirectoryRepository:
38
+ """Records on disk, an index in memory. The index is rebuilt by scanning."""
39
+
40
+ def __init__(self, layout: Layout) -> None:
41
+ self.layout = layout
42
+ self._items: dict[str, Reference] = {}
43
+ #: Where each record currently sits, so a key change can drop the old file.
44
+ self._paths: dict[str, Path] = {}
45
+ #: What each record looked like when we last read or wrote it.
46
+ self._digests: dict[str, str] = {}
47
+ self.load()
48
+
49
+ def load(self) -> None:
50
+ """Read every record. A corrupt one is skipped, not fatal for the library."""
51
+ for path in sorted(self.layout.root.rglob(RECORD_NAME)):
52
+ reference = self._read(path)
53
+ if reference is None or reference.id in self._items:
54
+ continue
55
+ self._remember(reference, path)
56
+
57
+ def save(self, reference: Reference) -> None:
58
+ path = self.layout.record_for(reference)
59
+ path.parent.mkdir(parents=True, exist_ok=True)
60
+ temporary = path.with_suffix(".tmp")
61
+ temporary.write_text(
62
+ yaml.safe_dump(reference.to_csl(), allow_unicode=True, sort_keys=False),
63
+ encoding="utf-8",
64
+ )
65
+ os.replace(temporary, path)
66
+ previous = self._paths.get(reference.id)
67
+ if previous is not None and previous != path and previous.exists():
68
+ previous.unlink()
69
+ try:
70
+ previous.parent.rmdir()
71
+ except OSError:
72
+ pass
73
+ self._items[reference.id] = reference
74
+ self._paths[reference.id] = path
75
+ self._digests[reference.id] = _digest(path)
76
+
77
+ def all(self) -> list[Reference]:
78
+ return list(self._items.values())
79
+
80
+ def get(self, reference_id: str) -> Reference | None:
81
+ return self._items.get(reference_id)
82
+
83
+ def organize(self, reference: Reference) -> tuple[Path, Path] | None:
84
+ """Move a record onto its layout path. Returns ``(old, new)`` when it moved.
85
+
86
+ Moves only. A record the index does not know is left alone: organising must not
87
+ invent records, and a caller who wants it written can call ``save``.
88
+ """
89
+ target = self.layout.record_for(reference)
90
+ current = self._paths.get(reference.id)
91
+ if current is None or current == target:
92
+ return None
93
+
94
+ target.parent.mkdir(parents=True, exist_ok=True)
95
+ shutil.move(str(current), str(target))
96
+ try:
97
+ current.parent.rmdir()
98
+ except OSError:
99
+ pass # attachments still live there; the directory stays
100
+ self._paths[reference.id] = target
101
+ self._digests[reference.id] = _digest(target)
102
+ return current, target
103
+
104
+ def reconcile(self) -> ReconcileReport:
105
+ """Compare the records on disk with what the index believes.
106
+
107
+ Reports, never repairs by guessing: a missing record leaves its reference in
108
+ place, and an unreadable file is left untouched.
109
+ """
110
+ report = ReconcileReport()
111
+
112
+ for reference_id, path in list(self._paths.items()):
113
+ if not path.exists():
114
+ report.missing.append(Finding(path=path, reference_id=reference_id))
115
+ continue
116
+ try:
117
+ digest = _digest(path)
118
+ except OSError:
119
+ report.orphaned.append(Finding(path=path, reference_id=reference_id))
120
+ continue
121
+ if digest == self._digests.get(reference_id):
122
+ continue
123
+ reference = self._read(path)
124
+ if reference is None:
125
+ report.orphaned.append(Finding(path=path, reference_id=reference_id))
126
+ continue
127
+ if reference.id != reference_id:
128
+ # The identity was edited outside the tool: the old entry is a ghost.
129
+ self._forget(reference_id)
130
+ self._items[reference.id] = reference
131
+ self._paths[reference.id] = path
132
+ self._digests[reference.id] = digest
133
+ report.changed.append(Finding(path=path, reference_id=reference.id))
134
+
135
+ known_paths = set(self._paths.values())
136
+ for path in sorted(self.layout.root.rglob(RECORD_NAME)):
137
+ if path in known_paths:
138
+ continue
139
+ reference = self._read(path)
140
+ if reference is None:
141
+ report.orphaned.append(Finding(path=path))
142
+ continue
143
+ if reference.id in self._items:
144
+ report.changed.append(Finding(path=path, reference_id=reference.id))
145
+ continue
146
+ self._remember(reference, path)
147
+ report.adopted.append(Finding(path=path, reference_id=reference.id))
148
+
149
+ return report
150
+
151
+ def _read(self, path: Path) -> Reference | None:
152
+ """A record, or ``None`` when the file carries no readable metadata."""
153
+ try:
154
+ return Reference.from_csl(yaml.safe_load(path.read_text(encoding="utf-8")))
155
+ except (OSError, UnicodeDecodeError, yaml.YAMLError, KeyError, TypeError, AttributeError):
156
+ return None
157
+
158
+ def _remember(self, reference: Reference, path: Path) -> None:
159
+ """Register a record and the state it was read in."""
160
+ self._items[reference.id] = reference
161
+ self._paths[reference.id] = path
162
+ self._digests[reference.id] = _digest(path)
163
+
164
+ def _forget(self, reference_id: str) -> None:
165
+ self._items.pop(reference_id, None)
166
+ self._paths.pop(reference_id, None)
167
+ self._digests.pop(reference_id, None)
168
+
169
+ def delete(self, reference: Reference) -> None:
170
+ """Forget a reference and remove its record."""
171
+ path = self._paths.pop(reference.id, None)
172
+ self._items.pop(reference.id, None)
173
+ self._digests.pop(reference.id, None)
174
+ if path is not None and path.exists():
175
+ path.unlink()
176
+ try:
177
+ path.parent.rmdir()
178
+ except OSError:
179
+ pass # attachments still live there; the directory stays
180
+
181
+ def find_by_key(self, key: str) -> Reference | None:
182
+ for reference in self._items.values():
183
+ if key in reference.all_keys():
184
+ return reference
185
+ return None
186
+
187
+ def keys(self) -> set[str]:
188
+ collected: set[str] = set()
189
+ for reference in self._items.values():
190
+ collected.update(reference.all_keys())
191
+ return collected
@@ -0,0 +1,122 @@
1
+ """A repository that keeps references in SQLite instead of files.
2
+
3
+ ADR-0001 makes files the record and the index disposable; ADR-0004 records why this
4
+ adapter exists anyway and what a caller gives up by choosing it.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import sqlite3
11
+ from pathlib import Path
12
+ from typing import Self
13
+
14
+ from ..core.model import Reference
15
+ from ..core.reconcile import Finding, ReconcileReport
16
+
17
+ SCHEMA = """
18
+ CREATE TABLE IF NOT EXISTS bib_references (
19
+ id TEXT PRIMARY KEY,
20
+ citation_key TEXT NOT NULL,
21
+ type TEXT NOT NULL,
22
+ document TEXT NOT NULL
23
+ );
24
+ CREATE TABLE IF NOT EXISTS bib_reference_keys (
25
+ key TEXT PRIMARY KEY,
26
+ reference_id TEXT NOT NULL,
27
+ is_alias INTEGER NOT NULL
28
+ );
29
+ """
30
+
31
+
32
+ class SqliteRepository:
33
+ """References as rows. The whole CSL document is the payload, so nothing is lost."""
34
+
35
+ def __init__(self, path: str | Path) -> None:
36
+ self.path = Path(path)
37
+ self.path.parent.mkdir(parents=True, exist_ok=True)
38
+ self._connection = sqlite3.connect(str(self.path))
39
+ self._connection.executescript(SCHEMA)
40
+ self._connection.commit()
41
+
42
+ # --- Repository ----------------------------------------------------------
43
+ def save(self, reference: Reference) -> None:
44
+ with self._connection:
45
+ self._connection.execute(
46
+ "INSERT INTO bib_references (id, citation_key, type, document) "
47
+ "VALUES (?, ?, ?, ?) "
48
+ "ON CONFLICT(id) DO UPDATE SET citation_key=excluded.citation_key, "
49
+ "type=excluded.type, document=excluded.document",
50
+ (
51
+ reference.id,
52
+ reference.citation_key,
53
+ reference.type,
54
+ json.dumps(reference.to_csl(), ensure_ascii=False),
55
+ ),
56
+ )
57
+ # Keys get their own table so a lookup does not read every document.
58
+ self._connection.execute(
59
+ "DELETE FROM bib_reference_keys WHERE reference_id = ?", (reference.id,)
60
+ )
61
+ for key in reference.all_keys():
62
+ self._connection.execute(
63
+ "INSERT OR REPLACE INTO bib_reference_keys (key, reference_id, is_alias) "
64
+ "VALUES (?, ?, ?)",
65
+ (key, reference.id, int(key != reference.citation_key)),
66
+ )
67
+
68
+ def all(self) -> list[Reference]:
69
+ rows = self._connection.execute("SELECT document FROM bib_references").fetchall()
70
+ return [reference for reference in map(self._decode, rows) if reference is not None]
71
+
72
+ def get(self, reference_id: str) -> Reference | None:
73
+ row = self._connection.execute(
74
+ "SELECT document FROM bib_references WHERE id = ?", (reference_id,)
75
+ ).fetchone()
76
+ return self._decode(row) if row else None
77
+
78
+ def find_by_key(self, key: str) -> Reference | None:
79
+ row = self._connection.execute(
80
+ "SELECT reference_id FROM bib_reference_keys WHERE key = ?", (key,)
81
+ ).fetchone()
82
+ return self.get(row[0]) if row else None
83
+
84
+ def keys(self) -> set[str]:
85
+ rows = self._connection.execute("SELECT key FROM bib_reference_keys").fetchall()
86
+ return {row[0] for row in rows}
87
+
88
+ def delete(self, reference: Reference) -> None:
89
+ with self._connection:
90
+ self._connection.execute("DELETE FROM bib_references WHERE id = ?", (reference.id,))
91
+ self._connection.execute(
92
+ "DELETE FROM bib_reference_keys WHERE reference_id = ?", (reference.id,)
93
+ )
94
+
95
+ def reconcile(self) -> ReconcileReport:
96
+ """A store cannot drift from itself, but a row can stop being readable.
97
+
98
+ ``missing``/``changed``/``adopted`` have no meaning without files; what does
99
+ occur is a document that no longer parses, and that is reported as orphaned.
100
+ """
101
+ report = ReconcileReport()
102
+ rows = self._connection.execute("SELECT id, document FROM bib_references").fetchall()
103
+ for reference_id, document in rows:
104
+ if self._decode((document,)) is None:
105
+ report.orphaned.append(Finding(path=self.path, reference_id=reference_id))
106
+ return report
107
+
108
+ # --- housekeeping --------------------------------------------------------
109
+ def _decode(self, row: tuple[str]) -> Reference | None:
110
+ try:
111
+ return Reference.from_csl(json.loads(row[0]))
112
+ except (TypeError, ValueError, KeyError, AttributeError):
113
+ return None
114
+
115
+ def close(self) -> None:
116
+ self._connection.close()
117
+
118
+ def __enter__(self) -> Self:
119
+ return self
120
+
121
+ def __exit__(self, *_: object) -> None:
122
+ self.close()
pyrefman/api.py ADDED
@@ -0,0 +1,347 @@
1
+ """The public façade: what callers use."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from dataclasses import replace
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from .adapters import DefaultLayout, DirectoryRepository
11
+ from .core.citation import STYLES
12
+ from .core.citation import render as render_citation
13
+ from .core.importing import ImportReport
14
+ from .core.keys import KeyFn, default_key, ensure_unique
15
+ from .core.matching import identifiers_of, normalise_title
16
+ from .core.merge import MergeReport
17
+ from .core.merge import merge as merge_references
18
+ from .core.model import KEY_PATTERN, Attachment, Reference, now, validate_key
19
+ from .core.organize import Move, OrganizeReport
20
+ from .core.reconcile import ReconcileReport
21
+ from .core.resolution import ResolutionReport, classify
22
+ from .plugins import BibTeXExporter, Registry, default_registry
23
+ from .ports import Importer, Layout, Organizer, Repository
24
+
25
+
26
+ class ReferenceManager:
27
+ """A library of references under one root directory."""
28
+
29
+ def __init__(
30
+ self,
31
+ root: str | Path,
32
+ *,
33
+ layout: Layout | None = None,
34
+ key_fn: KeyFn = default_key,
35
+ unique_keys: bool = True,
36
+ importers: list[Importer] | None = None,
37
+ registry: Registry | None = None,
38
+ repository: Repository | None = None,
39
+ ) -> None:
40
+ self.layout: Layout = layout or DefaultLayout(root)
41
+ self.key_fn = key_fn
42
+ self.unique_keys = unique_keys
43
+ self.registry = registry if registry is not None else default_registry()
44
+ #: An explicit list wins over discovery — the seam tests need that.
45
+ self._importers: list[Importer] | None = importers
46
+ self.repository: Repository = (
47
+ repository if repository is not None else DirectoryRepository(self.layout)
48
+ )
49
+ #: ``(requested, used)`` when the last ``add()`` had to change a key.
50
+ self.last_collision: tuple[str, str] | None = None
51
+ #: The account of the last merge, whether triggered by ``add()`` or ``merge()``.
52
+ self.last_merge: MergeReport | None = None
53
+ #: What happened the last time an identifier was resolved.
54
+ self.last_resolution: ResolutionReport | None = None
55
+
56
+ @property
57
+ def importers(self) -> list[Importer]:
58
+ """The importers this manager will use — read live, so late registration counts."""
59
+ if self._importers is not None:
60
+ return self._importers
61
+ return list(self.registry.importers.values())
62
+
63
+ @property
64
+ def plugin_warnings(self) -> list[str]:
65
+ """Plugins that failed to load, for a caller who wants to know."""
66
+ return list(self.registry.warnings)
67
+
68
+ def add(
69
+ self,
70
+ fields: dict[str, Any] | None = None,
71
+ *,
72
+ type: str = "article",
73
+ key: str | None = None,
74
+ source: str = "manual",
75
+ identifier: str | None = None,
76
+ ) -> Reference | None:
77
+ """Create a reference, or fold it into the one that already describes the work.
78
+
79
+ With ``identifier`` the fields come from a resolver instead of the caller. An
80
+ identifier no resolver can answer is not an error: the call returns ``None``
81
+ and ``last_resolution`` carries the reason.
82
+
83
+ Duplicates are recognised by identifier first and by normalised title second.
84
+ Two references sharing a key would share a record path, and the second write
85
+ would destroy the first, so uniqueness is enforced unless switched off.
86
+ """
87
+ self.last_collision = None
88
+ self.last_merge = None
89
+ self.last_resolution = None
90
+
91
+ scheme: str | None = None
92
+ if identifier is not None:
93
+ resolution = self._resolve(identifier)
94
+ self.last_resolution = resolution
95
+ if not resolution.ok:
96
+ return None
97
+ fields = dict(resolution.fields)
98
+ resolved_type = fields.pop("type", None)
99
+ if isinstance(resolved_type, str):
100
+ type = resolved_type
101
+ source = resolution.source or source
102
+ scheme = resolution.scheme
103
+ if fields is None:
104
+ raise ValueError("add() needs fields or an identifier")
105
+
106
+ if key:
107
+ validate_key(key)
108
+
109
+ incoming = Reference.create(type=type, citation_key=key or "", fields=fields, source=source)
110
+ if scheme is not None:
111
+ # The scheme outranks the resolver's own name when fields compete.
112
+ for name in incoming.provenance:
113
+ incoming.provenance[name]["scheme"] = scheme
114
+ duplicate = self._duplicate_of(incoming)
115
+ if duplicate is not None:
116
+ merged, report = self._fold(duplicate, incoming)
117
+ self.repository.save(merged)
118
+ self.last_merge = report
119
+ return merged
120
+
121
+ taken = frozenset(self.repository.keys())
122
+ requested = key or self.key_fn(incoming, taken)
123
+ if self.unique_keys:
124
+ used, collided_with = ensure_unique(requested, taken)
125
+ if collided_with is not None:
126
+ self.last_collision = (collided_with, used)
127
+ else:
128
+ used = requested
129
+
130
+ incoming.citation_key = used
131
+ self.repository.save(incoming)
132
+ return incoming
133
+
134
+ def _resolve(self, identifier: str) -> ResolutionReport:
135
+ """Ask a resolver for the fields of an identifier, first match wins."""
136
+ scheme, value = classify(identifier)
137
+ report = ResolutionReport(identifier=identifier, scheme=scheme)
138
+
139
+ candidates = [r for r in self.registry.of("resolvers").values() if scheme in r.schemes]
140
+ if not candidates:
141
+ report.error = f"no resolver claims the scheme {scheme!r}"
142
+ return report
143
+
144
+ for resolver in candidates:
145
+ try:
146
+ fields, error = resolver.resolve(value)
147
+ except Exception as failure: # noqa: BLE001 - a plugin must not break add()
148
+ report.error = f"{resolver.name} raised {failure}"
149
+ continue
150
+ if error is not None:
151
+ report.error = error
152
+ continue
153
+ if fields:
154
+ report.fields = fields
155
+ report.source = resolver.name
156
+ return report
157
+
158
+ report.error = report.error or f"no resolver returned fields for {value!r}"
159
+ return report
160
+
161
+ def _duplicate_of(self, incoming: Reference) -> Reference | None:
162
+ my_identifiers = dict(identifiers_of(incoming.fields))
163
+ if my_identifiers:
164
+ for reference in self.repository.all():
165
+ theirs = dict(identifiers_of(reference.fields))
166
+ if any(theirs.get(name) == value for name, value in my_identifiers.items()):
167
+ return reference
168
+
169
+ title = normalise_title(incoming.title)
170
+ if title:
171
+ for reference in self.repository.all():
172
+ if normalise_title(reference.title) == title:
173
+ return reference
174
+ return None
175
+
176
+ def _fold(self, keep: Reference, other: Reference) -> tuple[Reference, MergeReport]:
177
+ """Merge and drop aliases another reference already holds."""
178
+ merged, report = merge_references(keep, other)
179
+ blocked = self.repository.keys() - set(keep.all_keys()) - set(other.all_keys())
180
+ kept = [
181
+ alias for alias in merged.aliases if alias not in blocked and KEY_PATTERN.match(alias)
182
+ ]
183
+ dropped = [alias for alias in report.aliases_added if alias not in kept]
184
+ merged.aliases = kept
185
+ report.aliases_added = [alias for alias in report.aliases_added if alias in kept]
186
+ report.aliases_dropped = dropped
187
+ return merged, report
188
+
189
+ def find(self, query: str) -> list[Reference]:
190
+ """References whose title, any key or an author matches the query."""
191
+ return [reference for reference in self.repository.all() if reference.matches(query)]
192
+
193
+ def rename(self, current_key: str, new_key: str) -> Reference:
194
+ """Change a reference's citation key, keeping the old one as an alias.
195
+
196
+ Refuses a key another reference already holds: silently suffixing what the
197
+ caller typed would hide that the request could not be honoured.
198
+ """
199
+ reference = self.repository.find_by_key(current_key)
200
+ if reference is None:
201
+ raise KeyError(current_key)
202
+
203
+ taken = self.repository.keys() - set(reference.all_keys())
204
+ if new_key in taken:
205
+ raise ValueError(f"citation key {new_key!r} is already taken")
206
+
207
+ # Record first, index second: a failed write must not leave the index ahead.
208
+ renamed = reference.with_key(new_key)
209
+ self.repository.save(renamed)
210
+ return renamed
211
+
212
+ def merge(self, keep_key: str, other_key: str) -> MergeReport:
213
+ """Fold one reference into another that describes the same work."""
214
+ keep = self.repository.find_by_key(keep_key)
215
+ other = self.repository.find_by_key(other_key)
216
+ if keep is None:
217
+ raise KeyError(keep_key)
218
+ if other is None:
219
+ raise KeyError(other_key)
220
+ if keep.id == other.id:
221
+ raise ValueError("cannot merge a reference into itself")
222
+
223
+ merged, report = self._fold(keep, other)
224
+ # Record first, then forget the folded one: a crash leaves a duplicate, not a gap.
225
+ self.repository.save(merged)
226
+ self.repository.delete(other)
227
+ self.last_merge = report
228
+ return report
229
+
230
+ def attach(self, key: str, path: str | Path, source: str = "manual") -> Attachment:
231
+ """Record a file as belonging to a reference.
232
+
233
+ The same bytes are attached once: the hash decides, not the path, so a copy
234
+ under another name does not duplicate the attachment.
235
+ """
236
+ reference = self.repository.find_by_key(key)
237
+ if reference is None:
238
+ raise KeyError(key)
239
+
240
+ location = Path(path)
241
+ stored = self._stored_path(location)
242
+ attachment = Attachment(
243
+ path=stored,
244
+ sha256=hashlib.sha256(location.read_bytes()).hexdigest(),
245
+ added=now(),
246
+ source=source,
247
+ )
248
+ for existing in reference.attachments:
249
+ if existing.sha256 == attachment.sha256:
250
+ return existing
251
+
252
+ updated = replace(reference, attachments=[*reference.attachments, attachment])
253
+ self.repository.save(updated)
254
+ return attachment
255
+
256
+ def _stored_path(self, location: Path) -> str:
257
+ """A path relative to the library root when the file sits inside it.
258
+
259
+ A library that stores absolute paths cannot be moved to another machine or
260
+ synced through a folder — the layout owns where things live, not the caller's
261
+ working directory.
262
+ """
263
+ root = self.layout.root.resolve()
264
+ try:
265
+ return location.resolve().relative_to(root).as_posix()
266
+ except ValueError:
267
+ return str(location)
268
+
269
+ def organize(self) -> OrganizeReport:
270
+ """Move every record onto the layout currently in force."""
271
+ if not isinstance(self.repository, Organizer):
272
+ raise NotImplementedError("this repository has no records to move")
273
+
274
+ report = OrganizeReport()
275
+ for reference in self.repository.all():
276
+ move = self.repository.organize(reference)
277
+ if move is not None:
278
+ report.moves.append(Move(old=move[0], new=move[1]))
279
+ return report
280
+
281
+ def reconcile(self) -> ReconcileReport:
282
+ """Report where records and index disagree. Nothing is deleted or rewritten."""
283
+ return self.repository.reconcile()
284
+
285
+ def import_from(self, path: str | Path) -> ImportReport:
286
+ """Read a file through the importer that claims its extension.
287
+
288
+ An entry that duplicates a reference already in the library folds into it, so
289
+ importing the same file twice adds nothing the second time.
290
+ """
291
+ source = Path(path)
292
+ importer = next(
293
+ (
294
+ candidate
295
+ for candidate in self.importers
296
+ if source.suffix.lower() in candidate.extensions
297
+ ),
298
+ None,
299
+ )
300
+ if importer is None:
301
+ raise ValueError(f"no importer for {source.suffix!r}")
302
+
303
+ entries, warnings = importer.load(source)
304
+ report = ImportReport(source=source, warnings=list(warnings))
305
+
306
+ for entry in entries:
307
+ report.warnings.extend(entry.warnings)
308
+ try:
309
+ reference = self.add(
310
+ entry.fields, type=entry.type, key=entry.key, source=importer.name
311
+ )
312
+ except ValueError as error:
313
+ # A key that cannot be a directory name costs the key, not the entry.
314
+ report.warnings.append(f"{entry.key}: {error}; key generated instead")
315
+ reference = self.add(entry.fields, type=entry.type, source=importer.name)
316
+ if reference is None:
317
+ report.warnings.append(f"{entry.key}: nothing could be created")
318
+ continue
319
+ if self.last_merge is not None:
320
+ report.merged.append(reference.id)
321
+ else:
322
+ report.added.append(reference.id)
323
+
324
+ return report
325
+
326
+ def export_to(self, path: str | Path, fmt: str = "bibtex") -> Path:
327
+ """Write the whole library in one format."""
328
+ if fmt != "bibtex":
329
+ raise ValueError(f"unknown export format {fmt!r}")
330
+ return BibTeXExporter().write(self.repository.all(), Path(path))
331
+
332
+ def cite(self, key: str, style: str = "author-year") -> str:
333
+ """Render one reference as an in-text citation.
334
+
335
+ A numeric style needs an order, and the order is the library's own: sorted by
336
+ citation key, so the same library always numbers the same way.
337
+ """
338
+ reference = self.repository.find_by_key(key)
339
+ if reference is None:
340
+ raise KeyError(key)
341
+
342
+ ordered = sorted(self.repository.all(), key=lambda item: item.citation_key)
343
+ position = ordered.index(reference) + 1
344
+ return render_citation(reference, style, position)
345
+
346
+ #: Citation styles the core renders without a CSL processor.
347
+ available_styles = STYLES
@@ -0,0 +1,6 @@
1
+ """Core: the domain, free of I/O."""
2
+
3
+ from .keys import KeyFn, default_key
4
+ from .model import Reference
5
+
6
+ __all__ = ["KeyFn", "Reference", "default_key"]