cslbib 0.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.
cslbib/__init__.py ADDED
@@ -0,0 +1,51 @@
1
+ """Bibliographies kept as CSL-JSON files.
2
+
3
+ cslbib keeps the references of a project as lists of CSL-JSON items in one
4
+ or more JSON files. It makes entries from DOIs and GitHub repositories with
5
+ metadata from the registries, and checks the files against the CSL-JSON
6
+ schema and the project's settings. Its command line is `cslbib`, and its
7
+ Sphinx extension, `cslbib.sphinx`, renders citations and a bibliography of
8
+ the files in a CSL style through pandoc.
9
+
10
+ Entries hold every CSL variable that the registry gives, in the shape that
11
+ CSL-JSON gives it, except the excluded variables of the settings, which are
12
+ `abstract` by default.
13
+ A paper's key is the first author's family name, the year, and the first
14
+ title word that is no stop word, such as ``salentin2015plip``, and a
15
+ preprint's key ends in ``-preprint``;
16
+ a program's key is its name and version, such as ``plip:v3.0.1``.
17
+ """
18
+
19
+ from cslbib._config import Settings, SettingsError, read_settings
20
+ from cslbib._entries import (
21
+ EntryError,
22
+ Request,
23
+ cff_authors,
24
+ from_crossref,
25
+ from_csl,
26
+ make_entry,
27
+ paper_key,
28
+ )
29
+ from cslbib._files import BibliographyError, add, check, read, write
30
+ from cslbib._registries import RegistryError
31
+ from cslbib._schema import Item
32
+
33
+ __all__ = [
34
+ "BibliographyError",
35
+ "EntryError",
36
+ "Item",
37
+ "RegistryError",
38
+ "Request",
39
+ "Settings",
40
+ "SettingsError",
41
+ "add",
42
+ "cff_authors",
43
+ "check",
44
+ "from_crossref",
45
+ "from_csl",
46
+ "make_entry",
47
+ "paper_key",
48
+ "read",
49
+ "read_settings",
50
+ "write",
51
+ ]
cslbib/__main__.py ADDED
@@ -0,0 +1,154 @@
1
+ """Command line of cslbib.
2
+
3
+ Usage::
4
+
5
+ cslbib check [SETTINGS]
6
+ cslbib add [SETTINGS] [--into FILE] ID[=KEY] ...
7
+
8
+ `check` lists the problems of the bibliography files and fails if there is
9
+ one. `add` makes the entry of each identifier, a DOI or ``owner/name@ref``
10
+ of a GitHub repository, and adds it to the file that holds its type, or to
11
+ `--into`; ``=KEY`` sets its key. If any identifier fails, no file changes.
12
+
13
+ Settings come from a settings file and from options; an option replaces
14
+ the setting of the file:
15
+
16
+ ``--config FILE``
17
+ Settings file.
18
+ ``--file PATH[=TYPE,...]``
19
+ Bibliography file with the item types it holds; repeat for each file.
20
+ ``--require TYPE=VARIABLE,...``
21
+ Variables that items of a type must have, ``*`` for every type; repeat
22
+ for each type.
23
+ ``--exclude VARIABLE,...``
24
+ Variables that no item may have; empty for none.
25
+
26
+ Exit status: 0 on success, 1 if the bibliography has problems or an entry
27
+ cannot be added, and 2 for invalid settings or arguments.
28
+ """
29
+
30
+ import argparse
31
+ import sys
32
+ from collections.abc import Sequence
33
+ from dataclasses import replace
34
+ from pathlib import Path
35
+
36
+ from cslbib._config import (
37
+ ALL_TYPES,
38
+ Settings,
39
+ SettingsError,
40
+ check_types,
41
+ check_variables,
42
+ read_settings,
43
+ )
44
+ from cslbib._entries import Request
45
+ from cslbib._files import BibliographyError, add, check
46
+
47
+ EXIT_PROBLEMS = 1
48
+ """Exit status when the bibliography has problems or an entry fails."""
49
+
50
+ EXIT_USAGE = 2
51
+ """Exit status for invalid settings or arguments."""
52
+
53
+
54
+ def _names(text: str) -> list[str]:
55
+ """Return the names of a comma-separated list."""
56
+ return [name.strip() for name in text.split(",") if name.strip()]
57
+
58
+
59
+ def _parser() -> argparse.ArgumentParser:
60
+ """Return the parser of the command line."""
61
+ common = argparse.ArgumentParser(add_help=False)
62
+ common.add_argument("--config", type=Path, metavar="FILE")
63
+ common.add_argument(
64
+ "--file", action="append", metavar="PATH[=TYPE,...]", dest="files"
65
+ )
66
+ common.add_argument(
67
+ "--require", action="append", metavar="TYPE=VARIABLE,..."
68
+ )
69
+ common.add_argument("--exclude", metavar="VARIABLE,...")
70
+ parser = argparse.ArgumentParser(
71
+ prog="cslbib", description="Bibliographies kept as CSL-JSON."
72
+ )
73
+ commands = parser.add_subparsers(dest="command", required=True)
74
+ commands.add_parser(
75
+ "check", parents=[common], help="list the problems of the files"
76
+ )
77
+ adding = commands.add_parser(
78
+ "add", parents=[common], help="add entries from their identifiers"
79
+ )
80
+ adding.add_argument("--into", type=Path, metavar="FILE")
81
+ adding.add_argument("requests", nargs="+", metavar="ID[=KEY]")
82
+ return parser
83
+
84
+
85
+ def _settings(arguments: argparse.Namespace) -> Settings:
86
+ """Return the settings of the settings file and the options."""
87
+ settings = Settings()
88
+ if arguments.config:
89
+ settings = read_settings(arguments.config)
90
+ if arguments.files:
91
+ files = {}
92
+ for text in arguments.files:
93
+ path, _, types = text.partition("=")
94
+ files[Path(path)] = check_types(_names(types), f"--file {text}")
95
+ settings = replace(settings, files=files)
96
+ if arguments.require:
97
+ required = {}
98
+ for text in arguments.require:
99
+ item_type, _, names = text.partition("=")
100
+ if item_type != ALL_TYPES:
101
+ check_types([item_type], f"--require {text}")
102
+ where = f"--require {text}"
103
+ required[item_type] = check_variables(_names(names), where)
104
+ settings = replace(settings, required=required)
105
+ if arguments.exclude is not None:
106
+ names = _names(arguments.exclude)
107
+ excluded = check_variables(names, "--exclude")
108
+ settings = replace(settings, excluded=excluded)
109
+ return settings
110
+
111
+
112
+ def main(argv: Sequence[str]) -> int:
113
+ """Run a command.
114
+
115
+ Parameters
116
+ ----------
117
+ argv
118
+ Command and its arguments.
119
+
120
+ Returns
121
+ -------
122
+ Exit status.
123
+ """
124
+ arguments = _parser().parse_args(argv)
125
+ try:
126
+ settings = _settings(arguments)
127
+ except SettingsError as error:
128
+ sys.stderr.write(f"cslbib: {error}\n")
129
+ return EXIT_USAGE
130
+ found: list[str] = []
131
+ if arguments.command == "check":
132
+ found = check(settings)
133
+ else:
134
+ requests = [Request.parse(text) for text in arguments.requests]
135
+ try:
136
+ added = add(settings, requests, arguments.into)
137
+ except BibliographyError as error:
138
+ found = error.problems
139
+ else:
140
+ sys.stdout.writelines(f"added {k} to {p}\n" for k, p in added)
141
+ if found:
142
+ sys.stdout.write(f"errors ({len(found)}):\n")
143
+ sys.stdout.writelines(f" {problem}\n" for problem in found)
144
+ return EXIT_PROBLEMS
145
+ return 0
146
+
147
+
148
+ def run() -> None:
149
+ """Run the command of the process arguments and exit with its status."""
150
+ sys.exit(main(sys.argv[1:]))
151
+
152
+
153
+ if __name__ == "__main__":
154
+ run()
cslbib/_config.py ADDED
@@ -0,0 +1,253 @@
1
+ """Bibliography settings, from a TOML file and from arguments."""
2
+
3
+ import tomllib
4
+ from collections.abc import Iterable, Mapping
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+
8
+ from cslbib._schema import item_types, variables
9
+
10
+ ALL_TYPES = "*"
11
+ """Key of `Settings.required` that stands for every item type."""
12
+
13
+ _KEYS = frozenset({"excluded", "files", "required", "style"})
14
+
15
+
16
+ class SettingsError(ValueError):
17
+ """Invalid settings."""
18
+
19
+
20
+ @dataclass(frozen=True, kw_only=True)
21
+ class Settings:
22
+ """Bibliography settings.
23
+
24
+ A settings file is TOML with the same names. Its paths are relative to
25
+ the directory of the file:
26
+
27
+ .. code-block:: toml
28
+
29
+ excluded = ["abstract"]
30
+ style = "refs/apa.csl"
31
+
32
+ [files]
33
+ "refs/papers.json" = ["article", "article-journal", "chapter"]
34
+ "refs/software.json" = ["software"]
35
+
36
+ [required]
37
+ "*" = ["author", "title"]
38
+ article-journal = ["container-title", "issued"]
39
+ """
40
+
41
+ files: Mapping[Path, frozenset[str]] = field(default_factory=dict)
42
+ """Bibliography files, each with the item types it holds.
43
+
44
+ An empty set allows every type.
45
+ A new entry goes to the first file that allows its type.
46
+ """
47
+
48
+ required: Mapping[str, frozenset[str]] = field(default_factory=dict)
49
+ """Variables that each item of a type must have, by item type.
50
+
51
+ The key ``"*"`` stands for every type.
52
+ """
53
+
54
+ excluded: frozenset[str] = field(
55
+ default_factory=lambda: frozenset({"abstract"})
56
+ )
57
+ """Variables that no item may have.
58
+
59
+ By default `abstract`, since abstracts stay under the copyright of their
60
+ publishers or authors.
61
+ """
62
+
63
+ style: Path | None = None
64
+ """CSL style of citations and bibliographies, or None.
65
+
66
+ The Sphinx extension renders them in this style.
67
+ """
68
+
69
+ def file_for(self, item_type: str) -> Path | None:
70
+ """Return the file that new items of a type go to.
71
+
72
+ Parameters
73
+ ----------
74
+ item_type
75
+ CSL item type.
76
+
77
+ Returns
78
+ -------
79
+ First file that allows the type, or None if no file does.
80
+ """
81
+ for path, allowed in self.files.items():
82
+ if not allowed or item_type in allowed:
83
+ return path
84
+ return None
85
+
86
+ def required_for(self, item_type: str) -> frozenset[str]:
87
+ """Return the variables that items of a type must have.
88
+
89
+ Parameters
90
+ ----------
91
+ item_type
92
+ CSL item type.
93
+
94
+ Returns
95
+ -------
96
+ Variables required for every type and for this one.
97
+ """
98
+ empty: frozenset[str] = frozenset()
99
+ every = self.required.get(ALL_TYPES, empty)
100
+ return every | self.required.get(item_type, empty)
101
+
102
+
103
+ def check_types(names: Iterable[str], where: str) -> frozenset[str]:
104
+ """Return item types after checking that CSL defines them.
105
+
106
+ Parameters
107
+ ----------
108
+ names
109
+ Names of item types.
110
+ where
111
+ Setting that gives them, for the message.
112
+
113
+ Returns
114
+ -------
115
+ The types.
116
+
117
+ Raises
118
+ ------
119
+ SettingsError
120
+ If a name is no CSL item type.
121
+ """
122
+ found = frozenset(names)
123
+ unknown = sorted(found - item_types())
124
+ if unknown:
125
+ message = f"{where}: no CSL item types: {', '.join(unknown)}"
126
+ raise SettingsError(message)
127
+ return found
128
+
129
+
130
+ def check_variables(names: Iterable[str], where: str) -> frozenset[str]:
131
+ """Return variables after checking that CSL defines them.
132
+
133
+ Parameters
134
+ ----------
135
+ names
136
+ Names of variables.
137
+ where
138
+ Setting that gives them, for the message.
139
+
140
+ Returns
141
+ -------
142
+ The variables.
143
+
144
+ Raises
145
+ ------
146
+ SettingsError
147
+ If a name is no CSL variable.
148
+ """
149
+ found = frozenset(names)
150
+ unknown = sorted(found - variables())
151
+ if unknown:
152
+ message = f"{where}: no CSL variables: {', '.join(unknown)}"
153
+ raise SettingsError(message)
154
+ return found
155
+
156
+
157
+ def _strings(value: object, where: str) -> list[str]:
158
+ """Return a value after checking that it is a list of strings."""
159
+ if not isinstance(value, list) or not all(
160
+ isinstance(item, str) for item in value
161
+ ):
162
+ message = f"{where}: expected a list of strings"
163
+ raise SettingsError(message)
164
+ return value
165
+
166
+
167
+ def _table(value: object, where: str) -> dict[str, list[str]]:
168
+ """Return a value after checking that it maps strings to string lists."""
169
+ if not isinstance(value, dict):
170
+ message = f"{where}: expected a table"
171
+ raise SettingsError(message)
172
+ return {
173
+ str(key): _strings(item, f"{where}.{key}")
174
+ for key, item in value.items()
175
+ }
176
+
177
+
178
+ def settings_from(data: Mapping[str, object], base: Path) -> Settings:
179
+ """Return the settings of a mapping in the form of a settings file.
180
+
181
+ Parameters
182
+ ----------
183
+ data
184
+ Settings by name.
185
+ base
186
+ Directory that the paths are relative to.
187
+
188
+ Returns
189
+ -------
190
+ The settings; those that `data` omits keep their defaults.
191
+
192
+ Raises
193
+ ------
194
+ SettingsError
195
+ If a setting is unknown or invalid.
196
+ """
197
+ unknown = sorted(set(data) - _KEYS)
198
+ if unknown:
199
+ message = f"unknown settings: {', '.join(unknown)}"
200
+ raise SettingsError(message)
201
+ settings = Settings()
202
+ files = {
203
+ base / path: check_types(names, f"files.{path}")
204
+ for path, names in _table(data.get("files", {}), "files").items()
205
+ }
206
+ required = {
207
+ key: check_variables(names, f"required.{key}")
208
+ for key, names in _table(data.get("required", {}), "required").items()
209
+ }
210
+ check_types(set(required) - {ALL_TYPES}, "required")
211
+ excluded = settings.excluded
212
+ if "excluded" in data:
213
+ names = _strings(data["excluded"], "excluded")
214
+ excluded = check_variables(names, "excluded")
215
+ style = data.get("style")
216
+ if style is not None and not isinstance(style, str):
217
+ message = "style: expected a string"
218
+ raise SettingsError(message)
219
+ return Settings(
220
+ files=files,
221
+ required=required,
222
+ excluded=excluded,
223
+ style=base / style if style else None,
224
+ )
225
+
226
+
227
+ def read_settings(path: Path) -> Settings:
228
+ """Read a settings file.
229
+
230
+ Parameters
231
+ ----------
232
+ path
233
+ TOML file; its paths are relative to its directory.
234
+
235
+ Returns
236
+ -------
237
+ The settings.
238
+
239
+ Raises
240
+ ------
241
+ SettingsError
242
+ If the file cannot be read, or a setting is unknown or invalid.
243
+ """
244
+ try:
245
+ data = tomllib.loads(path.read_text("utf-8"))
246
+ except (OSError, tomllib.TOMLDecodeError) as error:
247
+ message = f"{path}: {error}"
248
+ raise SettingsError(message) from error
249
+ try:
250
+ return settings_from(data, path.parent)
251
+ except SettingsError as error:
252
+ message = f"{path}: {error}"
253
+ raise SettingsError(message) from error
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2007-2018 Citation Style Language and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.