basstler-notes 4.2.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.
@@ -0,0 +1,433 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ What this package needs installed, and which of it this environment is missing: read
4
+ from the checkout's declarations, else from the installed distributions' metadata.
5
+
6
+ Usage:
7
+ "${BASSTLER_PYTHON}" -m basstler.setup.dependencies [--declaration <pyproject.toml>]
8
+
9
+ ..note:: Imports nothing outside the standard library, since it runs before any
10
+ install.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import re
17
+ import sys
18
+ import tomllib
19
+ from abc import ABC, abstractmethod
20
+ from dataclasses import dataclass, field
21
+ from enum import StrEnum
22
+ from importlib.metadata import distributions
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ from basstler.class_property import classproperty
27
+ from basstler.exit_codes import CommandFailure, ExitCode
28
+ from basstler.locations import PackageLocation, WorkspaceLocation
29
+ from basstler.standard_streams import StandardStreamHandler
30
+ from basstler.text_file import TextFile
31
+
32
+ logger = StandardStreamHandler.logger_for(__name__)
33
+ """
34
+ This module's logger, which is also what its command prints through.
35
+ """
36
+
37
+
38
+ class PyprojectKey(StrEnum):
39
+ """
40
+ The keys of ``pyproject.toml`` this module reads.
41
+ """
42
+
43
+ PROJECT = "project"
44
+ """
45
+ The table a package's own metadata lives in.
46
+ """
47
+
48
+ NAME = "name"
49
+ """
50
+ The field of that table naming the package's own distribution.
51
+ """
52
+
53
+ DEPENDENCIES = "dependencies"
54
+ """
55
+ The field of that table, and of the sibling-pins hook's, listing the requirement
56
+ specifiers.
57
+ """
58
+
59
+ TOOL = "tool"
60
+ """
61
+ The table every tool's settings sit under.
62
+ """
63
+
64
+ HATCH = "hatch"
65
+ """
66
+ The build backend's table.
67
+ """
68
+
69
+ METADATA = "metadata"
70
+ """
71
+ The backend's table of how the metadata is built.
72
+ """
73
+
74
+ HOOKS = "hooks"
75
+ """
76
+ The table of the hooks filling in the metadata's dynamic fields.
77
+ """
78
+
79
+ SIBLING_PINS = "basstler-sibling-pins"
80
+ """
81
+ The hook holding a distribution's requirements, its basstler ones unpinned.
82
+ """
83
+
84
+
85
+ class RequirementMarker(StrEnum):
86
+ """
87
+ The environment-marker fragments of an installed distribution's requirements this
88
+ module reads.
89
+ """
90
+
91
+ EXTRA = "extra =="
92
+ """
93
+ Marks a requirement that applies only when one of the distribution's extras is
94
+ requested, which a plain install does not.
95
+ """
96
+
97
+
98
+ class DependencyExitCode(ExitCode):
99
+ """
100
+ How the command ended, as its caller reads it.
101
+ """
102
+
103
+ SUCCESS = 0
104
+ """
105
+ The missing requirements, if any, were printed.
106
+ """
107
+
108
+ UNREADABLE_DECLARATION = 1
109
+ """
110
+ The declaration could not be read, so nothing was printed.
111
+ """
112
+
113
+
114
+ @dataclass
115
+ class UnreadableDependencyDeclarationError(CommandFailure):
116
+ """
117
+ Raised when the declaration cannot be read, so nothing can be said about what is
118
+ missing.
119
+
120
+ Distinct from *nothing is missing*, which is what a caller would otherwise conclude
121
+ from an empty answer and act on by installing nothing.
122
+ """
123
+
124
+ @classproperty
125
+ def exit_code(cls) -> DependencyExitCode:
126
+ """:return: The status this kind of error ends a command with."""
127
+ return DependencyExitCode.UNREADABLE_DECLARATION
128
+
129
+ declaration: Path
130
+ """
131
+ The file that was to be read.
132
+ """
133
+
134
+ def __str__(self) -> str:
135
+ """:return: What to tell a reader who asked what is missing and cannot be told."""
136
+ return (
137
+ f"{self.declaration} does not exist, so this package's dependencies cannot "
138
+ f"be read"
139
+ )
140
+
141
+
142
+ @dataclass
143
+ class MalformedDependencyDeclarationError(UnreadableDependencyDeclarationError):
144
+ """
145
+ Raised when the declaration exists but is not valid TOML.
146
+ """
147
+
148
+ def __str__(self) -> str:
149
+ """:return: What to tell a reader who asked what is missing and cannot be told."""
150
+ return (
151
+ f"{self.declaration} is not valid TOML, so this package's dependencies "
152
+ f"cannot be read"
153
+ )
154
+
155
+
156
+ @dataclass(frozen=True)
157
+ class Dependency:
158
+ """
159
+ One requirement this package declares.
160
+ """
161
+
162
+ specifier: str
163
+ """
164
+ The requirement as ``pyproject.toml`` writes it, version bounds and all.
165
+ """
166
+
167
+ constraint_start: re.Pattern[str] = field(
168
+ default=re.compile(r"[<>=!~;\[ ]"), repr=False, compare=False
169
+ )
170
+ """
171
+ The first character that ends a distribution's name and begins a version bound, an extra
172
+ or an environment marker, in a PEP 508 specifier.
173
+ """
174
+
175
+ @property
176
+ def distribution_name(self) -> str:
177
+ """:return: The distribution this requirement names, without its constraints."""
178
+ return self.constraint_start.split(self.specifier, maxsplit=1)[0].strip()
179
+
180
+ @property
181
+ def is_basstler_distribution(self) -> bool:
182
+ """
183
+ :return: Whether this requirement names ``basstler`` or one of its
184
+ ``basstler-`` distributions.
185
+ """
186
+ family = PackageLocation.DIRECTORY.value.name
187
+ name = self.distribution_name.lower()
188
+ return name == family or name.startswith(f"{family}-")
189
+
190
+ @property
191
+ def is_missing(self) -> bool:
192
+ """
193
+ Presence rather than version: an installed distribution is left alone, which is
194
+ what lets a session start run this on every start and install nothing. Names are
195
+ compared as PEP 503 does, so a declaration need not match a distribution's own
196
+ spelling.
197
+
198
+ :return: Whether this environment has no distribution of that name.
199
+ """
200
+ return next(iter(distributions(name=self.distribution_name)), None) is None
201
+
202
+
203
+ class RequirementSource(ABC):
204
+ """
205
+ Somewhere a package's requirements are stated: the package itself, then its
206
+ dependencies.
207
+ """
208
+
209
+ @abstractmethod
210
+ def requirements(self) -> tuple[Dependency, ...]:
211
+ """
212
+ :return: Everything an environment needs to run the package: the package itself,
213
+ then its dependencies.
214
+ """
215
+
216
+ def missing(self) -> tuple[Dependency, ...]:
217
+ """
218
+ :return: The requirements this environment does not have.
219
+ """
220
+ return tuple(
221
+ requirement for requirement in self.requirements() if requirement.is_missing
222
+ )
223
+
224
+ @staticmethod
225
+ def for_this_package() -> RequirementSource:
226
+ """
227
+ :return: The checkout's workspace where the package runs from one, else the
228
+ installed ``basstler`` distribution.
229
+ """
230
+ if PackageLocation.META_PACKAGE_METADATA.value.is_file():
231
+ return WorkspaceDeclaration(PackageLocation.SOURCE_TREE.value)
232
+ return InstalledDistribution(PackageLocation.DIRECTORY.value.name)
233
+
234
+
235
+ @dataclass(frozen=True)
236
+ class InstalledDistribution(RequirementSource):
237
+ """
238
+ An installed distribution, and the dependencies its metadata states.
239
+ """
240
+
241
+ name: str
242
+ """
243
+ The distribution's name.
244
+ """
245
+
246
+ def requirements(self) -> tuple[Dependency, ...]:
247
+ """
248
+ :return: The distribution itself, then every requirement its metadata states
249
+ without an extra, in the order stated, each basstler distribution among them
250
+ followed by its own; only itself when it is not installed.
251
+ """
252
+ installed = next(iter(distributions(name=self.name)), None)
253
+ if installed is None:
254
+ return (Dependency(self.name),)
255
+ found = [Dependency(self.name)]
256
+ for specifier in installed.requires or []:
257
+ if RequirementMarker.EXTRA in specifier:
258
+ continue
259
+ dependency = Dependency(specifier)
260
+ stated = (
261
+ InstalledDistribution(dependency.distribution_name).requirements()
262
+ if dependency.is_basstler_distribution
263
+ else (dependency,)
264
+ )
265
+ found.extend(
266
+ requirement for requirement in stated if requirement not in found
267
+ )
268
+ return tuple(found)
269
+
270
+
271
+ @dataclass(frozen=True)
272
+ class DependencyDeclaration(RequirementSource):
273
+ """
274
+ A ``pyproject.toml`` and the dependencies it declares.
275
+ """
276
+
277
+ path: Path
278
+ """
279
+ The ``pyproject.toml`` to read.
280
+ """
281
+
282
+ def project(self) -> Dependency:
283
+ """
284
+ :return: The package's own distribution, as a requirement of an environment that
285
+ runs it.
286
+ :raises UnreadableDependencyDeclarationError: If the file is absent.
287
+ """
288
+ return Dependency(self._project_table()[PyprojectKey.NAME])
289
+
290
+ def dependencies(self) -> tuple[Dependency, ...]:
291
+ """
292
+ :return: Every dependency it declares, in ``[project]`` and then in the
293
+ sibling-pins hook, in the order it declares them.
294
+ :raises UnreadableDependencyDeclarationError: If the file is absent.
295
+ """
296
+ document = self._document()
297
+ hook = (
298
+ document.get(PyprojectKey.TOOL, {})
299
+ .get(PyprojectKey.HATCH, {})
300
+ .get(PyprojectKey.METADATA, {})
301
+ .get(PyprojectKey.HOOKS, {})
302
+ .get(PyprojectKey.SIBLING_PINS, {})
303
+ )
304
+ return tuple(
305
+ Dependency(specifier)
306
+ for specifier in (
307
+ *document[PyprojectKey.PROJECT].get(PyprojectKey.DEPENDENCIES, []),
308
+ *hook.get(PyprojectKey.DEPENDENCIES, []),
309
+ )
310
+ )
311
+
312
+ def requirements(self) -> tuple[Dependency, ...]:
313
+ """
314
+ :return: Everything an environment needs to run the package: the package itself,
315
+ then its dependencies.
316
+ :raises UnreadableDependencyDeclarationError: If the file is absent.
317
+ """
318
+ return (self.project(), *self.dependencies())
319
+
320
+ def _project_table(self) -> dict[str, Any]:
321
+ """
322
+ :return: The ``[project]`` table, the package's own metadata.
323
+ :raises UnreadableDependencyDeclarationError: If the file is absent.
324
+ :raises MalformedDependencyDeclarationError: If the file is not valid TOML.
325
+ """
326
+ return self._document()[PyprojectKey.PROJECT]
327
+
328
+ def _document(self) -> dict[str, Any]:
329
+ """
330
+ :return: The whole ``pyproject.toml``.
331
+ :raises UnreadableDependencyDeclarationError: If the file is absent.
332
+ :raises MalformedDependencyDeclarationError: If the file is not valid TOML.
333
+ """
334
+ if not self.path.is_file():
335
+ raise UnreadableDependencyDeclarationError(self.path)
336
+ try:
337
+ return tomllib.loads(TextFile(self.path).read())
338
+ except tomllib.TOMLDecodeError as error:
339
+ raise MalformedDependencyDeclarationError(self.path) from error
340
+
341
+
342
+ @dataclass(frozen=True)
343
+ class WorkspaceDeclaration(RequirementSource):
344
+ """
345
+ A checkout's workspace, whose ``basstler`` distribution requires what its own
346
+ ``pyproject.toml`` and those of the basstler distributions it lists declare.
347
+ """
348
+
349
+ root: Path
350
+ """
351
+ The workspace's root.
352
+ """
353
+
354
+ def requirements(self) -> tuple[Dependency, ...]:
355
+ """
356
+ :return: The ``basstler`` distribution, then each requirement its declaration
357
+ lists, each workspace distribution among them followed by its own.
358
+ :raises UnreadableDependencyDeclarationError: If a declaration is absent.
359
+ """
360
+ declarations = {
361
+ declaration.project().specifier: declaration
362
+ for declaration in (
363
+ DependencyDeclaration(path)
364
+ for path in sorted(
365
+ (self.root / WorkspaceLocation.PACKAGES).glob(
366
+ f"*/{WorkspaceLocation.METADATA}"
367
+ )
368
+ )
369
+ )
370
+ }
371
+ return self.reached(
372
+ declarations, Dependency(PackageLocation.DIRECTORY.value.name), []
373
+ )
374
+
375
+ def reached(
376
+ self,
377
+ declarations: dict[str, DependencyDeclaration],
378
+ requirement: Dependency,
379
+ found: list[Dependency],
380
+ ) -> tuple[Dependency, ...]:
381
+ """
382
+ :param declarations: Each workspace distribution's declaration, by its name.
383
+ :param requirement: A requirement to add to *found*.
384
+ :param found: The requirements reached so far, extended in place.
385
+ :return: *found*, with *requirement* and, for a workspace distribution, what it
386
+ declares in turn.
387
+ """
388
+ declaration = declarations.get(requirement.distribution_name)
389
+ if declaration is None:
390
+ if requirement not in found:
391
+ found.append(requirement)
392
+ return tuple(found)
393
+ own = Dependency(requirement.distribution_name)
394
+ if own in found:
395
+ return tuple(found)
396
+ found.append(own)
397
+ for dependency in declaration.dependencies():
398
+ self.reached(declarations, dependency, found)
399
+ return tuple(found)
400
+
401
+
402
+ def main() -> DependencyExitCode:
403
+ """
404
+ Print one specifier per missing requirement, for a caller to report.
405
+
406
+ :return: How the command ended.
407
+ """
408
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[1])
409
+ parser.add_argument(
410
+ "--declaration",
411
+ type=Path,
412
+ help="A pyproject.toml to read the dependencies from, instead of this package's "
413
+ "own requirements",
414
+ )
415
+ declaration_path = parser.parse_args().declaration
416
+ try:
417
+ if declaration_path is None:
418
+ source = RequirementSource.for_this_package()
419
+ elif declaration_path.is_file():
420
+ source = DependencyDeclaration(declaration_path)
421
+ else:
422
+ raise UnreadableDependencyDeclarationError(declaration_path)
423
+ missing = source.missing()
424
+ except CommandFailure as error:
425
+ logger.error(str(error))
426
+ return error.exit_code
427
+ for requirement in missing:
428
+ logger.info(requirement.specifier)
429
+ return DependencyExitCode.SUCCESS
430
+
431
+
432
+ if __name__ == "__main__":
433
+ sys.exit(main())
@@ -0,0 +1,154 @@
1
+ """
2
+ The reasons the personal-notes setup stops before it finishes.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING
10
+
11
+ from basstler.class_property import classproperty
12
+ from basstler.exceptions import DataclassException
13
+ from basstler.exit_codes import CommandFailure, PersonalNotesSetupExitCode
14
+ from basstler.github.repository import Repository
15
+
16
+ if TYPE_CHECKING:
17
+ from basstler.setup.report import SetupCheck
18
+
19
+
20
+ @dataclass
21
+ class ForeignNotesRemoteError(CommandFailure, DataclassException, PermissionError):
22
+ """
23
+ Raised when GitHub says the notes remote belongs to somebody other than the caller,
24
+ who may not push to it or finds no notes branch there to share.
25
+ """
26
+
27
+ @classproperty
28
+ def exit_code(cls) -> PersonalNotesSetupExitCode:
29
+ """:return: The status this kind of error ends a command with."""
30
+ return PersonalNotesSetupExitCode.FOREIGN_NOTES_REMOTE
31
+
32
+ repository: Repository
33
+ """
34
+ The repository the notes remote names.
35
+ """
36
+
37
+ login: str
38
+ """
39
+ The account the available credential belongs to.
40
+ """
41
+
42
+ def error_message(self) -> str:
43
+ return (
44
+ f"refusing to set up personal notes on '{self.repository.full_name}': it "
45
+ f"is owned by '{self.repository.owner}', but the credential belongs to "
46
+ f"'{self.login}'"
47
+ )
48
+
49
+ def suggest_correction(self) -> str:
50
+ return (
51
+ "pass --remote naming your own fork, or a repository you may push to whose "
52
+ "owner has set up its notes branch"
53
+ )
54
+
55
+
56
+ @dataclass
57
+ class HookScriptFailedError(CommandFailure, DataclassException, RuntimeError):
58
+ """
59
+ Raised when a hook script a setup step runs exits with a failure.
60
+ """
61
+
62
+ @classproperty
63
+ def exit_code(cls) -> PersonalNotesSetupExitCode:
64
+ """:return: The status this kind of error ends a command with."""
65
+ return PersonalNotesSetupExitCode.HOOK_SCRIPT_FAILED
66
+
67
+ script: Path
68
+ """
69
+ The script that failed.
70
+ """
71
+
72
+ status: int
73
+ """
74
+ The status it exited with.
75
+ """
76
+
77
+ def error_message(self) -> str:
78
+ return f"{self.script.name} exited with status {self.status}"
79
+
80
+ def suggest_correction(self) -> str:
81
+ return "its own output above says why; fix that and run the setup again"
82
+
83
+
84
+ @dataclass
85
+ class CheckSetupFailedError(CommandFailure, DataclassException, RuntimeError):
86
+ """
87
+ Raised when a check-setup.sh run exits with a status that carries no report, or its
88
+ report lacks a requested check or holds a row this package cannot read.
89
+ """
90
+
91
+ @classproperty
92
+ def exit_code(cls) -> PersonalNotesSetupExitCode:
93
+ """:return: The status this kind of error ends a command with."""
94
+ return PersonalNotesSetupExitCode.CHECK_SETUP_FAILED
95
+
96
+ status: int
97
+ """
98
+ The status check-setup.sh exited with.
99
+ """
100
+
101
+ standard_error: str
102
+ """
103
+ What check-setup.sh printed to its standard error.
104
+ """
105
+ missing_checks: list[SetupCheck]
106
+ """
107
+ The requested checks the report has no row for.
108
+ """
109
+
110
+ unreadable_rows: list[str]
111
+ """
112
+ The rows naming a check or a status this package does not declare, or not holding a
113
+ check, a status and a detail.
114
+ """
115
+
116
+ def error_message(self) -> str:
117
+ problems = [f"check-setup.sh exited with status {self.status}"]
118
+ if self.missing_checks:
119
+ problems.append(f"reported no row for {', '.join(self.missing_checks)}")
120
+ if self.unreadable_rows:
121
+ problems.append(
122
+ f"printed rows this package cannot read: {self.unreadable_rows}"
123
+ )
124
+ return f"{'; '.join(problems)}\nIts standard error:\n{self.standard_error}"
125
+
126
+ def suggest_correction(self) -> str:
127
+ return "fix what its standard error names, then run the setup again"
128
+
129
+
130
+ @dataclass
131
+ class UnknownSkillError(CommandFailure, DataclassException, LookupError):
132
+ """
133
+ Raised when the setup gate is asked for a skill it does not gate.
134
+ """
135
+
136
+ @classproperty
137
+ def exit_code(cls) -> PersonalNotesSetupExitCode:
138
+ """:return: The status this kind of error ends a command with."""
139
+ return PersonalNotesSetupExitCode.USAGE
140
+
141
+ skill_name: str
142
+ """
143
+ The name asked for.
144
+ """
145
+ gated_skill_names: list[str]
146
+ """
147
+ The names of the skills the gate knows.
148
+ """
149
+
150
+ def error_message(self) -> str:
151
+ return f"no gated skill is named '{self.skill_name}'"
152
+
153
+ def suggest_correction(self) -> str:
154
+ return f"name one of: {', '.join(self.gated_skill_names)}"