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,296 @@
1
+ """
2
+ The basstler modules and skills a document cites, and which of them this release no
3
+ longer ships.
4
+
5
+ Usage:
6
+ "${BASSTLER_PYTHON}" -m basstler.document_references <document>...
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from dataclasses import dataclass
13
+ from enum import Enum
14
+ from collections.abc import Mapping
15
+ from functools import cache
16
+ from types import MappingProxyType
17
+ from importlib.metadata import version
18
+ from itertools import takewhile
19
+ from pathlib import Path
20
+
21
+ from cyclopts import App
22
+
23
+ from basstler.locations import PackageLocation
24
+ from basstler.package_layout import package_modules
25
+ from basstler.standard_streams import StandardStreamHandler
26
+ from basstler.text_file import TextFile
27
+
28
+ logger = StandardStreamHandler.logger_for(__name__)
29
+ """
30
+ This module's logger, which is also what its command prints through.
31
+ """
32
+
33
+ # %% what a document cites
34
+
35
+ PACKAGE_NAME = PackageLocation.DIRECTORY.name
36
+ """
37
+ The package every cited module belongs to.
38
+ """
39
+
40
+ DOTTED_CITATION = re.compile(
41
+ rf"(?<![\w./-]){PACKAGE_NAME}\.(?!sh\b)([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)(?![\w-])"
42
+ )
43
+ """
44
+ Matches a dotted import path into the package, capturing it below the package.
45
+ """
46
+
47
+ SOURCE_FILE_CITATION = re.compile(rf"\bsrc/{PACKAGE_NAME}/([\w/]+)\.py\b")
48
+ """
49
+ Matches a source file of the package, capturing its path below the package directory.
50
+ """
51
+
52
+ ENTRY_POINT_CITATION = re.compile(
53
+ rf"\b{PACKAGE_NAME}\.sh\"?\s+([a-z_]\w*(?:\.[a-z_]\w*)*)(?![\w-])"
54
+ )
55
+ """
56
+ Matches the module the plugin's entry point script is asked to run.
57
+ """
58
+
59
+ SKILL_CITATION = re.compile(r"(?<![\w/.])/([a-z][a-z0-9]*(?:-[a-z0-9]+)+)(?![\w/-])")
60
+ """
61
+ Matches a slash command, capturing the skill it invokes.
62
+ """
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Retirement:
67
+ """
68
+ What replaced a retired skill, and the major release that retired it.
69
+ """
70
+
71
+ replacement: str
72
+ """
73
+ What to cite or do instead.
74
+ """
75
+
76
+ major_version: int
77
+ """
78
+ The major release that retired the skill; the next major release no longer
79
+ reports it.
80
+ """
81
+
82
+
83
+ class RetiredSkill(Enum):
84
+ """
85
+ A skill the plugin once shipped and no longer does.
86
+ """
87
+
88
+ @property
89
+ def invoked_as(self) -> str:
90
+ """
91
+ The slash command that invoked it.
92
+ """
93
+ return "/" + self._name_.lower().replace("_", "-")
94
+
95
+ @classmethod
96
+ def retirements(cls) -> dict[str, Retirement]:
97
+ """
98
+ :return: Each retired skill's retirement, by the skill's name without the slash.
99
+ """
100
+ return {skill.invoked_as.removeprefix("/"): skill.value for skill in cls}
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class StaleReference:
105
+ """
106
+ One name a document cites that this release does not ship.
107
+ """
108
+
109
+ cited: str
110
+ """
111
+ The name as a session would run it: a module's import path, or a slash command.
112
+ """
113
+
114
+ replacement: str | None
115
+ """
116
+ What to cite or do instead, ``None`` when nothing shipped takes its place.
117
+ """
118
+
119
+ def as_line(self) -> str:
120
+ """:return: The reference and its replacement, as one line."""
121
+ if self.replacement is None:
122
+ return f"{self.cited}: not shipped, and nothing replaces it"
123
+ return f"{self.cited}: not shipped; {self.replacement}"
124
+
125
+
126
+ # %% what the package ships
127
+
128
+
129
+ @dataclass(frozen=True)
130
+ class ShippedModules:
131
+ """
132
+ Every module and subpackage of the installed package, named below the package.
133
+ """
134
+
135
+ modules: frozenset[str]
136
+ """
137
+ Every module's dotted name, e.g. ``"plan.manifest_tools"``.
138
+ """
139
+
140
+ major_version: int
141
+ """
142
+ The major release these modules belong to.
143
+ """
144
+
145
+ @classmethod
146
+ @cache
147
+ def installed(cls) -> ShippedModules:
148
+ """:return: The modules and major release of the package this runs from."""
149
+ return cls(
150
+ frozenset(module.name for module in package_modules()),
151
+ int(version(PACKAGE_NAME).partition(".")[0]),
152
+ )
153
+
154
+ @property
155
+ def subpackages(self) -> frozenset[str]:
156
+ """
157
+ Every package that holds a module, by its dotted name.
158
+ """
159
+ return frozenset(
160
+ ".".join(parts[:end])
161
+ for parts in (module.split(".") for module in self.modules)
162
+ for end in range(1, len(parts))
163
+ )
164
+
165
+ def ships(self, cited: str) -> bool:
166
+ """
167
+ :param cited: A dotted name below the package, its classes already removed.
168
+ :return: Whether it is a module or subpackage, or a function of a module.
169
+ """
170
+ parent = cited.rpartition(".")[0]
171
+ return (
172
+ cited in self.modules or cited in self.subpackages or parent in self.modules
173
+ )
174
+
175
+ def replacement_for(self, cited: str) -> str | None:
176
+ """
177
+ :param cited: A dotted name below the package that :meth:`ships` refuses.
178
+ :return: The import path of the one module it moved to - the same name with its
179
+ dots and underscores swapped, or else the only module of the same last
180
+ name - or ``None`` when there is no such module.
181
+ """
182
+ flattened = cited.replace(".", "_")
183
+ renamed = [
184
+ module for module in self.modules if module.replace(".", "_") == flattened
185
+ ]
186
+ last_name = cited.rpartition(".")[2]
187
+ same_last_name = [
188
+ module for module in self.modules if module.rpartition(".")[2] == last_name
189
+ ]
190
+ moved_to = renamed or same_last_name
191
+ if len(moved_to) != 1:
192
+ return None
193
+ return f"{PACKAGE_NAME}.{moved_to[0]}"
194
+
195
+
196
+ # %% reading a document
197
+
198
+
199
+ @dataclass(frozen=True)
200
+ class CitedNames:
201
+ """
202
+ The package's modules and the slash commands one document cites.
203
+ """
204
+
205
+ modules: frozenset[str]
206
+ """
207
+ Every cited module's dotted name below the package, without any class or method
208
+ named after it.
209
+ """
210
+
211
+ skills: frozenset[str]
212
+ """
213
+ Every skill a cited slash command invokes, without the slash.
214
+ """
215
+
216
+ @classmethod
217
+ def in_text(cls, text: str) -> CitedNames:
218
+ """:param text: A document's text.
219
+ :return: The names it cites."""
220
+ dotted = {
221
+ ".".join(takewhile(lambda part: not part[:1].isupper(), name.split(".")))
222
+ for name in DOTTED_CITATION.findall(text)
223
+ }
224
+ source_files = {
225
+ path.replace("/", ".") for path in SOURCE_FILE_CITATION.findall(text)
226
+ }
227
+ entry_points = set(ENTRY_POINT_CITATION.findall(text))
228
+ return cls(
229
+ modules=frozenset(
230
+ name for name in dotted | source_files | entry_points if name
231
+ ),
232
+ skills=frozenset(SKILL_CITATION.findall(text)),
233
+ )
234
+
235
+ def stale(
236
+ self,
237
+ shipped: ShippedModules,
238
+ retirements: Mapping[str, Retirement] = MappingProxyType(
239
+ RetiredSkill.retirements()
240
+ ),
241
+ ) -> list[StaleReference]:
242
+ """
243
+ :param shipped: What the installed package ships.
244
+ :param retirements: Each retired skill's retirement, by the skill's name without
245
+ the slash.
246
+ :return: Every cited name it does not ship, skills retired in its major release
247
+ first, each in name order.
248
+ """
249
+ retired = {
250
+ name: retirement
251
+ for name, retirement in retirements.items()
252
+ if retirement.major_version >= shipped.major_version
253
+ }
254
+ skills = [
255
+ StaleReference(f"/{name}", retired[name].replacement)
256
+ for name in sorted(self.skills & retired.keys())
257
+ ]
258
+ modules = []
259
+ for name in sorted(self.modules):
260
+ if shipped.ships(name):
261
+ continue
262
+ moved_to = shipped.replacement_for(name)
263
+ modules.append(
264
+ StaleReference(
265
+ f"{PACKAGE_NAME}.{name}",
266
+ None if moved_to is None else f"now {moved_to}",
267
+ )
268
+ )
269
+ return skills + modules
270
+
271
+
272
+ # %% the command line
273
+
274
+ app = App(help=__doc__)
275
+ """
276
+ The command, which takes the documents to check.
277
+ """
278
+
279
+
280
+ @app.default
281
+ def report_stale_references(*documents: Path) -> int:
282
+ """
283
+ Print one line per name the documents cite that this release does not ship.
284
+
285
+ :param documents: The documents to check.
286
+ :return: 0, also when a reference is stale: the lines are the report.
287
+ """
288
+ shipped = ShippedModules.installed()
289
+ for document in documents:
290
+ for reference in CitedNames.in_text(TextFile(document).read()).stale(shipped):
291
+ logger.info(reference.as_line())
292
+ return 0
293
+
294
+
295
+ if __name__ == "__main__":
296
+ app()
File without changes
@@ -0,0 +1,141 @@
1
+ """
2
+ Print how a Claude Code cloud session gets the personal-notes repository attached when
3
+ it is not the checkout's own and the session cannot reach it, and nothing otherwise.
4
+
5
+ Usage:
6
+ "${BASSTLER_PYTHON}" -m basstler.personal_notes.access --retry <command>
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from collections.abc import Mapping
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+
16
+ from cyclopts import App
17
+
18
+ from basstler.exit_codes import StackExitCode
19
+ from basstler.git.commands import GitCommandRunner
20
+ from basstler.github.client import GitHubAttemptClient, GitHubRestClient
21
+ from basstler.github.repository import Repository
22
+ from basstler.github.repository_attachment import RepositoryAttachment
23
+ from basstler.locations import ClaudeCodeVariable
24
+ from basstler.personal_notes.branch import PersonalNotesLocation
25
+ from basstler.standard_streams import StandardStreamHandler
26
+
27
+ logger = StandardStreamHandler.logger_for(__name__)
28
+ """
29
+ This module's logger, which is also what its command prints through.
30
+ """
31
+
32
+ # %% the access
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class NotesRepositoryAccess:
37
+ """
38
+ Whether this session reaches :attr:`notes_repository`, and how to make it reach it.
39
+ """
40
+
41
+ notes_repository: Repository
42
+ """
43
+ The repository the personal-notes branch is fetched from and pushed to.
44
+ """
45
+
46
+ checkout_repository: Repository | None
47
+ """
48
+ The repository the session's checkout is a clone of, ``None`` when its ``origin``
49
+ names none.
50
+ """
51
+
52
+ @classmethod
53
+ def of_clone(
54
+ cls, project_root: Path, environment: Mapping[str, str], origin: str = "origin"
55
+ ) -> NotesRepositoryAccess | None:
56
+ """
57
+ :param project_root: The clone whose remotes to read.
58
+ :param environment: The environment the notes settings are read from.
59
+ :param origin: The remote whose repository is the checkout's own.
60
+ :return: The clone's notes and checkout repositories, ``None`` when the notes
61
+ remote names no repository.
62
+ """
63
+ git = GitCommandRunner(project_root)
64
+ notes_remote = PersonalNotesLocation.resolve(project_root, environment).remote
65
+ notes_url = git.configured_remote_url(notes_remote) or notes_remote
66
+ if not Repository.names_a_repository(notes_url):
67
+ return None
68
+ origin_url = git.configured_remote_url(origin)
69
+ checkout_repository = (
70
+ Repository.from_remote_url(origin_url)
71
+ if origin_url and Repository.names_a_repository(origin_url)
72
+ else None
73
+ )
74
+ return cls(Repository.from_remote_url(notes_url), checkout_repository)
75
+
76
+ def attachment(self, retry_command: str) -> RepositoryAttachment:
77
+ """
78
+ :param retry_command: The command that does what failed, once attached.
79
+ :return: How the session gets :attr:`notes_repository` attached.
80
+ """
81
+ return RepositoryAttachment(
82
+ self.notes_repository,
83
+ retry_command=retry_command,
84
+ benefit="this session then reads and saves the personal notes, plans and "
85
+ "PR progress kept there",
86
+ )
87
+
88
+ def missing_access(
89
+ self, client: GitHubAttemptClient, retry_command: str
90
+ ) -> str | None:
91
+ """
92
+ :param client: Reads the notes repository.
93
+ :param retry_command: The command that does what failed, once attached.
94
+ :return: Why the session cannot reach the notes repository and how it gets it
95
+ attached, ``None`` when it is the checkout's own or the session reaches it.
96
+ """
97
+ if self.notes_repository == self.checkout_repository:
98
+ return None
99
+ read = client.attempt_get(self.notes_repository.api_path)
100
+ if read.failure is None:
101
+ return None
102
+ return (
103
+ f"This session cannot reach the personal-notes repository "
104
+ f"{self.notes_repository.full_name} yet ({read.failure.error_message()}). "
105
+ f"{self.attachment(retry_command).instruction()}"
106
+ )
107
+
108
+
109
+ # %% the command line
110
+
111
+ app = App(help=__doc__)
112
+ """
113
+ The command, which takes the retry command.
114
+ """
115
+
116
+
117
+ @app.default
118
+ def check_access(*, retry: str) -> StackExitCode:
119
+ """
120
+ Print how this cloud session gets the notes repository attached, when it has to.
121
+
122
+ :param retry: The command that does what failed, once the repository is attached.
123
+ :return: :attr:`StackExitCode.SUCCESS`, also when the access is missing: the line
124
+ printed is the answer.
125
+ """
126
+ if not ClaudeCodeVariable.REMOTE.is_true():
127
+ return StackExitCode.SUCCESS
128
+ project_root = Path(
129
+ os.environ.get(ClaudeCodeVariable.PROJECT_DIRECTORY, Path.cwd())
130
+ )
131
+ access = NotesRepositoryAccess.of_clone(project_root, os.environ)
132
+ if access is None:
133
+ return StackExitCode.SUCCESS
134
+ missing = access.missing_access(GitHubRestClient(), retry)
135
+ if missing is not None:
136
+ logger.info(missing)
137
+ return StackExitCode.SUCCESS
138
+
139
+
140
+ if __name__ == "__main__":
141
+ app()