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,474 @@
1
+ """
2
+ Performs the one-time personal-notes setup without a session: points the notes remote at
3
+ a repository you own, creates the notes branch, optionally seeds it and records your git
4
+ identity, picks the notes up in this clone, and checks the pull request labels the
5
+ tooling applies.
6
+
7
+ Safe to re-run: each step is skipped when check-setup.sh already reports it done. Exits
8
+ with check-setup.sh's own final status, so a setup that only half worked never reports
9
+ success.
10
+
11
+ Usage:
12
+ "${BASSTLER_PYTHON}" -m basstler.setup.personal_notes --remote <name-or-url> \\
13
+ [--name "Your Name" --email you@example.com] [--starter-notes] [--create-labels]
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import os
20
+ import subprocess
21
+ import sys
22
+ from collections.abc import Mapping, Sequence
23
+ from dataclasses import dataclass
24
+ from enum import StrEnum
25
+ from pathlib import Path
26
+
27
+ from basstler.bash import Bash
28
+ from basstler.class_property import classproperty
29
+ from basstler.email_address import EmailAddress
30
+ from basstler.environment import GitHubCredentialVariable
31
+ from basstler.exceptions import MalformedEmailAddressError
32
+ from basstler.exit_codes import CommandFailure, PersonalNotesSetupExitCode
33
+ from basstler.git.commands import TransientGitSetting
34
+ from basstler.github.client import GitHubRestClient
35
+ from basstler.github.permission_level import PermissionLevel
36
+ from basstler.github.repository_access import GitHubRepository
37
+ from basstler.github.repository_details import RepositoryDetailsRead
38
+ from basstler.github.tooling_labels import GitHubLabel
39
+ from basstler.locations import (
40
+ ClaudeCodeVariable,
41
+ PluginLocation,
42
+ PluginSkillLocation,
43
+ )
44
+ from basstler.plugin_root import PluginRoot
45
+ from basstler.setup.exceptions import ForeignNotesRemoteError, HookScriptFailedError
46
+ from basstler.setup.report import (
47
+ CheckStatus,
48
+ SetupCheck,
49
+ SetupCheckScript,
50
+ SetupReport,
51
+ )
52
+ from basstler.setup.steps import PersonalNotesSetting, resolve_repository
53
+ from basstler.standard_streams import StandardStreamHandler
54
+
55
+ logger = StandardStreamHandler.logger_for(__name__)
56
+ """
57
+ This module's logger, which is also what its command prints through.
58
+ """
59
+
60
+ # %% what a run is asked to do
61
+
62
+
63
+ class SetupOption(StrEnum):
64
+ """
65
+ Every option the command takes, named once so no caller spells one out.
66
+ """
67
+
68
+ REMOTE = "--remote"
69
+ """
70
+ The remote, or raw URL, the notes belong on.
71
+ """
72
+
73
+ NAME = "--name"
74
+ """
75
+ The name the user's commits carry.
76
+ """
77
+
78
+ EMAIL = "--email"
79
+ """
80
+ The email the user's commits carry.
81
+ """
82
+
83
+ STARTER_NOTES = "--starter-notes"
84
+ """
85
+ Seed a new notes file from the starter template.
86
+ """
87
+
88
+ CREATE_LABELS = "--create-labels"
89
+ """
90
+ Create the labels the repository lacks, rather than only report them.
91
+ """
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class GitIdentity:
96
+ """
97
+ The name and email every clone's commits are authored with.
98
+ """
99
+
100
+ name: str
101
+ """
102
+ The value of ``user.name``.
103
+ """
104
+
105
+ email: EmailAddress
106
+ """
107
+ The address ``user.email`` is set to.
108
+ """
109
+
110
+
111
+ @dataclass(frozen=True)
112
+ class SetupRequest:
113
+ """
114
+ What one run is asked to set up.
115
+ """
116
+
117
+ remote: str
118
+ """
119
+ The remote the notes belong on, as a remote name in this clone or a raw URL.
120
+ """
121
+
122
+ identity: GitIdentity | None
123
+ """
124
+ The identity to record on the notes branch, or ``None`` to record none.
125
+ """
126
+
127
+ starter_notes: bool
128
+ """
129
+ Whether to seed a new notes file from the starter template.
130
+ """
131
+
132
+ create_labels: bool
133
+ """
134
+ Whether to create the labels the repository lacks, rather than only report them.
135
+ """
136
+
137
+ @classmethod
138
+ def from_arguments(cls, arguments: Sequence[str] | None) -> SetupRequest:
139
+ """
140
+ Read a request from the command line.
141
+
142
+ :param arguments: The command line without the program name, defaulting to the
143
+ process's own.
144
+ :return: The request.
145
+ """
146
+ parser = argparse.ArgumentParser(
147
+ prog=f"python3 -m {__spec__.name}", description=__doc__.split("\n\n")[0]
148
+ )
149
+ parser.add_argument(
150
+ SetupOption.REMOTE,
151
+ required=True,
152
+ help="the remote your notes belong on; required rather than guessed, since "
153
+ "a wrong guess pushes them to a repository you may not own",
154
+ )
155
+ parser.add_argument(SetupOption.NAME, help="the name your commits carry")
156
+ parser.add_argument(SetupOption.EMAIL, help="the email your commits carry")
157
+ parser.add_argument(
158
+ SetupOption.STARTER_NOTES,
159
+ action="store_true",
160
+ help="seed a new notes file from the starter template",
161
+ )
162
+ parser.add_argument(
163
+ SetupOption.CREATE_LABELS,
164
+ action="store_true",
165
+ help="create the labels the repository lacks; off by default, since labels "
166
+ "are visible to everyone who can see the repository",
167
+ )
168
+ parsed = parser.parse_args(arguments)
169
+ if bool(parsed.name) != bool(parsed.email):
170
+ parser.error(
171
+ f"{SetupOption.NAME} and {SetupOption.EMAIL} go together: a commit "
172
+ f"needs both"
173
+ )
174
+ if parsed.email and not EmailAddress.is_well_formed(parsed.email):
175
+ parser.error(
176
+ f"{SetupOption.EMAIL}: "
177
+ f"{MalformedEmailAddressError(parsed.email).error_message()}"
178
+ )
179
+ return cls(
180
+ remote=parsed.remote,
181
+ identity=(
182
+ GitIdentity(parsed.name, EmailAddress.parse(parsed.email))
183
+ if parsed.name
184
+ else None
185
+ ),
186
+ starter_notes=parsed.starter_notes,
187
+ create_labels=parsed.create_labels,
188
+ )
189
+
190
+
191
+ # %% the run
192
+
193
+
194
+ @dataclass(frozen=True)
195
+ class PersonalNotesSetup:
196
+ """
197
+ One setup run against one clone, in the order the steps depend on each other.
198
+ """
199
+
200
+ project_root: Path
201
+ """
202
+ The clone being set up.
203
+ """
204
+
205
+ environment: Mapping[str, str]
206
+ """
207
+ The environment the hook scripts run in and the settings resolve from.
208
+ """
209
+
210
+ request: SetupRequest
211
+ """
212
+ What the run was asked to do.
213
+ """
214
+
215
+ github: GitHubRepository | None
216
+ """
217
+ Access to the repository the notes remote names, or ``None`` when that is not a
218
+ GitHub repository or no credential is available - which leaves the owner and the
219
+ labels unchecked rather than stopping the run.
220
+ """
221
+
222
+ plugin_root: PluginRoot
223
+ """
224
+ The plugin whose hook scripts the steps run.
225
+ """
226
+
227
+ @classproperty
228
+ def starter_notes_message(cls) -> str:
229
+ """
230
+ The commit message a new notes file is seeded with.
231
+ """
232
+ return "Initialize personal notes from the starter template"
233
+
234
+ @classmethod
235
+ def for_clone(
236
+ cls, project_root: Path, environment: Mapping[str, str], request: SetupRequest
237
+ ) -> PersonalNotesSetup:
238
+ """
239
+ Set up a run with whatever GitHub access the environment offers.
240
+
241
+ :param project_root: The clone to set up.
242
+ :param environment: The environment to run in.
243
+ :param request: What the run was asked to do.
244
+ :return: The run, not yet started.
245
+ """
246
+ repository = resolve_repository(project_root, request.remote)
247
+ token = GitHubCredentialVariable.first_token()
248
+ github = (
249
+ None
250
+ if repository is None or token is None
251
+ else GitHubRepository(repository, GitHubRestClient(token))
252
+ )
253
+ return cls(
254
+ project_root, environment, request, github, PluginRoot.locate(environment)
255
+ )
256
+
257
+ def run(self) -> PersonalNotesSetupExitCode:
258
+ """
259
+ Perform every step, then report what is true now.
260
+
261
+ :return: The status check-setup.sh finishes with.
262
+ :raises ForeignNotesRemoteError: If the notes remote is somebody else's and holds
263
+ no notes branch the credential's account may share.
264
+ :raises HookScriptFailedError: If a step's hook script fails.
265
+ :raises CheckSetupFailedError: If check-setup.sh fails or its report is
266
+ incomplete.
267
+ :raises GitHubRequestFailed: If GitHub refuses a call a step depends on.
268
+ """
269
+ requested_remote = TransientGitSetting(
270
+ PersonalNotesSetting.REMOTE.git_config_key, self.request.remote
271
+ )
272
+ initial_report = SetupReport.from_completed_process(
273
+ self.run_check_setup(requested_remote)
274
+ )
275
+ self.verify_notes_remote_access(initial_report)
276
+ self.point_notes_remote()
277
+ self.create_notes_branch(initial_report)
278
+ self.seed_notes(initial_report)
279
+ self.record_identity()
280
+ self.run_hook_script(PluginLocation.SESSION_START_SCRIPT)
281
+ self.check_labels()
282
+ final_check = self.run_check_setup()
283
+ logger.info(
284
+ f"Setup finished. check-setup.sh now reports:\n{final_check.stdout}"
285
+ )
286
+ final_report = SetupReport.from_completed_process(final_check)
287
+ return PersonalNotesSetupExitCode(final_report.exit_code)
288
+
289
+ def verify_notes_remote_access(self, initial_report: SetupReport) -> None:
290
+ """
291
+ Refuse a notes remote GitHub says is somebody else's, unless it holds a notes
292
+ branch the credential's account may push to, which colleagues then share.
293
+
294
+ Without GitHub access the remote is reported unchecked and allowed, since
295
+ ``--remote`` named it explicitly.
296
+
297
+ :param initial_report: check-setup.sh's report from before anything was written.
298
+ :raises ForeignNotesRemoteError: If the remote is neither the credential's own
299
+ nor a notes branch it may share.
300
+ """
301
+ if self.github is None:
302
+ logger.info(
303
+ f"Did not verify who owns '{self.request.remote}': it names no GitHub "
304
+ f"repository, or no GitHub token is set. Continuing, since "
305
+ f"{SetupOption.REMOTE} named it."
306
+ )
307
+ return
308
+ repository = self.github.repository
309
+ login = self.github.authenticated_login()
310
+ if repository.owner.casefold() == login.casefold():
311
+ logger.info(f"'{repository.full_name}' is owned by '{login}'.")
312
+ return
313
+ details = RepositoryDetailsRead(repository)
314
+ access = details.parse(self.github.client.get(details.path)).contents_access
315
+ notes_branch = initial_report.results[SetupCheck.NOTES_BRANCH].status
316
+ if notes_branch is not CheckStatus.OK or access is not PermissionLevel.WRITE:
317
+ raise ForeignNotesRemoteError(repository, login)
318
+ logger.info(
319
+ f"'{repository.full_name}' is owned by '{repository.owner}'; '{login}' "
320
+ f"may push to it and joins its notes branch."
321
+ )
322
+
323
+ def point_notes_remote(self) -> None:
324
+ """
325
+ Record the chosen remote in this clone's git config, where every hook reads it.
326
+ """
327
+ subprocess.run(
328
+ [
329
+ "git",
330
+ "config",
331
+ PersonalNotesSetting.REMOTE.git_config_key,
332
+ self.request.remote,
333
+ ],
334
+ cwd=self.project_root,
335
+ check=True,
336
+ )
337
+ logger.info(f"Notes remote set to '{self.request.remote}'.")
338
+
339
+ def create_notes_branch(self, initial_report: SetupReport) -> None:
340
+ """
341
+ Create the notes branch unless check-setup.sh already found it.
342
+
343
+ :param initial_report: check-setup.sh's report from before anything was written.
344
+ """
345
+ if (
346
+ initial_report.results[SetupCheck.NOTES_BRANCH].status
347
+ is not CheckStatus.NEEDS_SETUP
348
+ ):
349
+ logger.info("The notes branch already exists; left untouched.")
350
+ return
351
+ self.run_hook_script(PluginLocation.PERSONAL_NOTES_BRANCH_CREATION_SCRIPT)
352
+
353
+ def seed_notes(self, initial_report: SetupReport) -> None:
354
+ """
355
+ Seed a notes file that did not exist before this run from the starter template,
356
+ when asked to.
357
+
358
+ :param initial_report: check-setup.sh's report from before anything was written.
359
+ """
360
+ if not self.request.starter_notes:
361
+ return
362
+ if (
363
+ initial_report.results[SetupCheck.NOTES_FILE].status
364
+ is not CheckStatus.NEEDS_SETUP
365
+ ):
366
+ logger.info("The notes file already exists; not seeding it.")
367
+ return
368
+ self.run_hook_script(
369
+ PluginLocation.PERSONAL_NOTES_WRITER_SCRIPT,
370
+ "--source",
371
+ str(self.plugin_root.path_of(PluginSkillLocation.STARTER_NOTES)),
372
+ "--destination",
373
+ PersonalNotesSetting.PATH.resolve(self.project_root, self.environment),
374
+ "--message",
375
+ self.starter_notes_message,
376
+ )
377
+
378
+ def record_identity(self) -> None:
379
+ """
380
+ Record the requested identity on the notes branch, when given one.
381
+ """
382
+ if self.request.identity is None:
383
+ return
384
+ self.run_hook_script(
385
+ PluginLocation.GIT_IDENTITY_SAVING_SCRIPT,
386
+ "--name",
387
+ self.request.identity.name,
388
+ "--email",
389
+ str(self.request.identity.email),
390
+ )
391
+
392
+ def check_labels(self) -> None:
393
+ """
394
+ Report which labels the repository lacks, and create them when asked to.
395
+
396
+ A missing label blocks nothing else in the setup, so this never stops the run.
397
+ """
398
+ if self.github is None:
399
+ logger.info("Did not check the repository's labels: no GitHub access.")
400
+ return
401
+ repository = self.github.repository.full_name
402
+ present = self.github.labels()
403
+ missing = [label for label in GitHubLabel if label not in present]
404
+ if not missing:
405
+ logger.info(f"Every label this tooling uses is on '{repository}'.")
406
+ return
407
+ logger.info(f"Labels missing on '{repository}': {', '.join(missing)}")
408
+ if not self.request.create_labels:
409
+ logger.info(
410
+ f"Not creating them; run again with {SetupOption.CREATE_LABELS}."
411
+ )
412
+ return
413
+ for label in missing:
414
+ self.github.create_label(label)
415
+ logger.info(f"Created '{label}' on '{repository}'.")
416
+
417
+ def run_check_setup(
418
+ self, setting: TransientGitSetting | None = None
419
+ ) -> subprocess.CompletedProcess[str]:
420
+ """
421
+ Run check-setup.sh, whose non-zero status means only that something still needs
422
+ setting up.
423
+
424
+ :param setting: A git setting it sees in force on top of the clone's own.
425
+ :return: The finished process, its report captured.
426
+ """
427
+ environment = dict(self.environment)
428
+ if setting is not None:
429
+ environment |= setting.variables(environment)
430
+ return SetupCheckScript(self.project_root, environment, self.plugin_root).run()
431
+
432
+ def run_hook_script(self, script: PluginLocation, *arguments: str) -> None:
433
+ """
434
+ Run one hook script, its output going to this process's own.
435
+
436
+ :param script: The script to run.
437
+ :param arguments: Its arguments.
438
+ :raises HookScriptFailedError: If it exits with a failure.
439
+ """
440
+ path = self.plugin_root.path_of(script)
441
+ completed = subprocess.run(
442
+ Bash.locate(self.environment).command(path, *arguments),
443
+ cwd=self.project_root,
444
+ env=dict(self.environment),
445
+ )
446
+ if completed.returncode != 0:
447
+ raise HookScriptFailedError(path, completed.returncode)
448
+
449
+
450
+ # %% command line
451
+
452
+
453
+ def main(arguments: Sequence[str] | None = None) -> int:
454
+ """
455
+ Set up this clone as the command line asks, and report the result.
456
+
457
+ :param arguments: The command line without the program name, defaulting to the
458
+ process's own.
459
+ :return: The process exit status.
460
+ """
461
+ request = SetupRequest.from_arguments(arguments)
462
+ project_root = Path(
463
+ os.environ.get(ClaudeCodeVariable.PROJECT_DIRECTORY, Path.cwd())
464
+ )
465
+ setup = PersonalNotesSetup.for_clone(project_root, os.environ, request)
466
+ try:
467
+ return setup.run()
468
+ except CommandFailure as failure:
469
+ logger.error(failure)
470
+ return failure.exit_code
471
+
472
+
473
+ if __name__ == "__main__":
474
+ sys.exit(main())