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,790 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Prints the setup steps that live outside this clone, filled in for the fork the
4
+ clone actually points at.
5
+
6
+ check-setup.sh reports on everything a shell can inspect - the notes branch, the
7
+ recorded git identity, the package dependencies. What it cannot reach is
8
+ everything held by a service rather than a file: labels in a GitHub repository,
9
+ Claude's access to that repository, and the variables a fresh-clone environment
10
+ has to carry. Those are the steps a first-time user is left holding, so they are
11
+ printed here as a short list with the values already substituted, rather than
12
+ described in prose the reader has to translate.
13
+
14
+ It also performs the one step a script can that check-setup.sh reports on but
15
+ session start cannot fill in for itself: naming the project's upstream in the user's
16
+ personal ``stack.toml``, which only the user knows.
17
+
18
+ It also installs ``/upstream-reviews``' Action on the fork's own branch, which a
19
+ script can do once the user has asked for it - everything but switching a fork's
20
+ Actions on, which is printed here.
21
+
22
+ Usage:
23
+ "${BASSTLER_PYTHON}" -m basstler.setup.steps
24
+ "${BASSTLER_PYTHON}" -m basstler.setup.steps configure-upstream --repository <owner>/<name>
25
+ "${BASSTLER_PYTHON}" -m basstler.setup.steps install-upstream-reviews-action --branch-or-tag <branch or tag>
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import dataclasses
32
+ import os
33
+ import re
34
+ import subprocess
35
+ import sys
36
+ import tempfile
37
+ from abc import ABC, abstractmethod
38
+ from collections.abc import Mapping
39
+ from dataclasses import dataclass
40
+ from enum import Enum, StrEnum
41
+ from pathlib import Path
42
+
43
+ from basstler.git.remote_branch import RemoteBranch
44
+ from basstler.bash import Bash
45
+ from basstler.class_property import classproperty
46
+ from basstler.git.commands import GitCommandFailed, GitCommandRunner
47
+ from basstler.github.remote import GitHubRemote
48
+ from basstler.github.repository import HasRepository, Repository
49
+ from basstler.github.stack_configuration import StackSetting
50
+ from basstler.github.tooling_labels import GitHubLabel
51
+ from basstler.locations import ClaudeCodeVariable, PluginLocation, ProjectLocation
52
+ from basstler.plugin_root import PluginRoot
53
+ from basstler.shell_configuration import (
54
+ FetchedBranchReference,
55
+ ShellConfigurationFunction,
56
+ )
57
+ from basstler.standard_streams import StandardStreamHandler
58
+ from basstler.text_file import TextFile
59
+ from basstler.upstream_reviews.action.branch import ActionBranch, ActionInstallation
60
+
61
+ logger = StandardStreamHandler.logger_for(__name__)
62
+ """
63
+ This module's logger, which is also what its command prints through.
64
+ """
65
+
66
+
67
+ class Host(StrEnum):
68
+ """
69
+ The services the printed steps send a reader to, each named once.
70
+
71
+ A member is the bare host, which is how a remote URL carries it; :attr:`url` is
72
+ the same host addressed over HTTPS, which is how a link carries it.
73
+ """
74
+
75
+ CLAUDE = "claude.ai"
76
+ """
77
+ Where Claude's own settings and cloud sessions live.
78
+ """
79
+
80
+ CLAUDE_DOCUMENTATION = "code.claude.com"
81
+ """
82
+ Where Claude Code's documentation lives.
83
+ """
84
+
85
+ GITHUB = "github.com"
86
+ """
87
+ Where the fork, its labels and its pull requests live.
88
+ """
89
+
90
+ @property
91
+ def url(self) -> str:
92
+ """
93
+ This host addressed the way every link in this module addresses it.
94
+ """
95
+ return f"https://{self}"
96
+
97
+
98
+ class SetupLink(StrEnum):
99
+ """
100
+ Every fixed page the printed steps link to, composed from the host serving it.
101
+
102
+ A link that varies with the repository is built by the step that shows it instead -
103
+ see :attr:`ForkLabels.labels_url`.
104
+ """
105
+
106
+ GITHUB_AUTHORIZATION = (
107
+ f"{Host.CLAUDE.url}/customize/connectors?auth_start=github&auth_start_force=1"
108
+ )
109
+ """
110
+ Where a user grants Claude access to their own GitHub repositories.
111
+
112
+ The query opens the GitHub authorization directly rather than the connector list.
113
+ """
114
+
115
+ ORGANIZATION_CONNECTORS = f"{Host.CLAUDE.url}/admin-settings/connectors"
116
+ """
117
+ Where an owner enables the GitHub connector for a Team or Enterprise Claude plan.
118
+
119
+ Until they do, the authorization above offers no sign-in button at all.
120
+ """
121
+
122
+ ENVIRONMENT_SELECTOR = f"{Host.CLAUDE.url}/code"
123
+ """
124
+ Where an environment is edited, which is the selector rather than a settings page.
125
+ """
126
+
127
+ ENVIRONMENT_VARIABLES = (
128
+ f"{Host.CLAUDE_DOCUMENTATION.url}/docs/en/cloud-environments"
129
+ "#set-environment-variables"
130
+ )
131
+ """
132
+ Where the environment-level variable list for cloud sessions is documented.
133
+
134
+ The section rather than the page: the overview only mentions that an environment
135
+ carries variables, and points here for the list itself.
136
+ """
137
+
138
+
139
+ # %% reading a value out of the clone
140
+
141
+
142
+ def git_value(project_root: Path, *arguments: str) -> str | None:
143
+ """
144
+ Read a value git can answer for a clone, or nothing when it has no answer.
145
+
146
+ An absent answer is an ordinary outcome here - an unset configuration key, a remote
147
+ the clone never added - so it is reported rather than raised, and every caller in
148
+ this module falls through to the next thing it knows.
149
+
150
+ :param project_root: The clone to run in.
151
+ :param arguments: The git subcommand and its arguments.
152
+ :return: The trimmed output, or ``None`` when the command failed or said nothing.
153
+ """
154
+ completed = subprocess.run(
155
+ ["git", *arguments],
156
+ cwd=project_root,
157
+ capture_output=True,
158
+ encoding="utf-8",
159
+ )
160
+ if completed.returncode != 0:
161
+ return None
162
+ return completed.stdout.strip() or None
163
+
164
+
165
+ # %% the settings whose values the printed steps depend on
166
+
167
+
168
+ @dataclass(frozen=True)
169
+ class PersonalNotesSettingSpecification:
170
+ """
171
+ Where one personal-notes setting is read from, and what it falls back to.
172
+
173
+ resolve-personal-notes-config.sh is the definition of both the precedence and the
174
+ defaults; this mirrors them because the shell file exports nothing a child process
175
+ could read them from.
176
+ """
177
+
178
+ git_config_key: str
179
+ """
180
+ The git config key that takes precedence over everything else.
181
+ """
182
+
183
+ environment_variable: str
184
+ """
185
+ The environment variable read when no git config value is set.
186
+ """
187
+
188
+ default: str
189
+ """
190
+ The value in force when neither of the two above is set.
191
+ """
192
+
193
+ def resolve(self, project_root: Path, environment: Mapping[str, str]) -> str:
194
+ """
195
+ Read this setting's value as the hooks themselves would.
196
+
197
+ :param project_root: The clone whose git config to read.
198
+ :param environment: The environment to read the variable from.
199
+ :return: The value in force.
200
+ """
201
+ configured = git_value(project_root, "config", "--get", self.git_config_key)
202
+ if configured is not None:
203
+ return configured
204
+ return environment.get(self.environment_variable) or self.default
205
+
206
+
207
+ class PersonalNotesSetting(PersonalNotesSettingSpecification, Enum):
208
+ """
209
+ The three settings that decide where personal notes live, in the order the printed
210
+ variable list uses them.
211
+
212
+ Each member *is* a specification, so a setting's own key, variable and default are
213
+ reached directly and no caller holds a parallel list of them.
214
+
215
+ .. note::
216
+ Both :meth:`__new__` and :meth:`__init__` are needed: the enum machinery builds a
217
+ member's value by calling the mixed-in type with the member's value as arguments,
218
+ which a specification with no defaulted field cannot survive.
219
+ """
220
+
221
+ def __new__(
222
+ cls, specification: PersonalNotesSettingSpecification
223
+ ) -> PersonalNotesSetting:
224
+ """
225
+ Make the member without letting the enum rebuild the specification from it.
226
+
227
+ :param specification: Where this setting is read from.
228
+ :return: The member, carrying that specification as its value.
229
+ """
230
+ member = object.__new__(cls)
231
+ member._value_ = specification
232
+ return member
233
+
234
+ def __init__(self, specification: PersonalNotesSettingSpecification) -> None:
235
+ """
236
+ Carry the specification's values on the member itself.
237
+
238
+ :param specification: Where this setting is read from.
239
+ """
240
+ for field in dataclasses.fields(PersonalNotesSettingSpecification):
241
+ object.__setattr__(self, field.name, getattr(specification, field.name))
242
+
243
+ REMOTE = PersonalNotesSettingSpecification(
244
+ git_config_key="claude.personalNotesRemote",
245
+ environment_variable="CLAUDE_PERSONAL_NOTES_REMOTE",
246
+ default="origin",
247
+ )
248
+ """
249
+ The remote, or raw URL, the notes branch lives on.
250
+ """
251
+
252
+ BRANCH = PersonalNotesSettingSpecification(
253
+ git_config_key="claude.personalNotesBranch",
254
+ environment_variable="CLAUDE_PERSONAL_NOTES_BRANCH",
255
+ default="claude/personal-notes",
256
+ )
257
+ """
258
+ The branch the notes are stored on.
259
+ """
260
+
261
+ PATH = PersonalNotesSettingSpecification(
262
+ git_config_key="claude.personalNotesPath",
263
+ environment_variable="CLAUDE_PERSONAL_NOTES_PATH",
264
+ default=ProjectLocation.PERSONAL_NOTES_DOCUMENT.as_posix(),
265
+ )
266
+ """
267
+ Where on that branch the notes file sits.
268
+ """
269
+
270
+
271
+ # %% the repository the steps are about
272
+
273
+
274
+ def resolve_repository(project_root: Path, notes_remote: str) -> Repository | None:
275
+ """
276
+ Find the repository a user's pull requests and notes go to.
277
+
278
+ :param project_root: The clone to read remotes from.
279
+ :param notes_remote: The resolved notes remote, either a remote name or a URL.
280
+ :return: The repository, or ``None`` when no remote resolves to a GitHub URL, so
281
+ nothing is guessed from another host's path.
282
+ """
283
+ remote_url = git_value(project_root, "remote", "get-url", notes_remote)
284
+ for candidate in (remote_url, notes_remote):
285
+ if candidate is None:
286
+ continue
287
+ if Host.GITHUB in candidate and Repository.names_a_repository(candidate):
288
+ return Repository.from_remote_url(candidate)
289
+ return None
290
+
291
+
292
+ # %% the steps themselves
293
+
294
+
295
+ @dataclass(frozen=True)
296
+ class SetupStep(ABC):
297
+ """
298
+ One setup step that no script can perform or verify, because it changes a setting
299
+ held by GitHub or by Claude rather than a file in this clone.
300
+ """
301
+
302
+ @property
303
+ @abstractmethod
304
+ def title(self) -> str:
305
+ """
306
+ What the step changes, in a few words.
307
+ """
308
+
309
+ @property
310
+ @abstractmethod
311
+ def reason(self) -> str:
312
+ """
313
+ What stops working until it is done.
314
+ """
315
+
316
+ @abstractmethod
317
+ def instructions(self) -> list[str]:
318
+ """
319
+ What to do, one line per action.
320
+
321
+ :return: The lines, printed under the title.
322
+ """
323
+
324
+ def render(self, number: int) -> str:
325
+ """
326
+ Render this step as the numbered block the reader sees.
327
+
328
+ :param number: The step's position in the printed list.
329
+ :return: The block, without a trailing newline.
330
+ """
331
+ lines = [f"{number}. {self.title}", f" {self.reason}", ""]
332
+ lines.extend(f" {instruction}" for instruction in self.instructions())
333
+ return "\n".join(lines)
334
+
335
+
336
+ @dataclass(frozen=True)
337
+ class ForkLabels(HasRepository, SetupStep):
338
+ """
339
+ Creating the labels this tooling reads and applies, in the user's fork.
340
+ """
341
+
342
+ @property
343
+ def title(self) -> str:
344
+ """See :attr:`SetupStep.title`."""
345
+ return f"Add {len(GitHubLabel)} labels to {self.repository.full_name}"
346
+
347
+ @property
348
+ def reason(self) -> str:
349
+ """See :attr:`SetupStep.reason`."""
350
+ return (
351
+ "A fresh fork has none of them: the plan site misreads landed work, and "
352
+ "applying a label a repository lacks fails mid-pull-request."
353
+ )
354
+
355
+ @property
356
+ def labels_url(self) -> str:
357
+ """
358
+ The page where the fork's labels are created by hand.
359
+ """
360
+ return f"{Host.GITHUB.url}/{self.repository.full_name}/labels"
361
+
362
+ def instructions(self) -> list[str]:
363
+ """See :meth:`SetupStep.instructions`."""
364
+ commands = [label.creation_command(self.repository) for label in GitHubLabel]
365
+ return [
366
+ f"By hand: {self.labels_url}",
367
+ "Or, if you have the gh CLI:",
368
+ *commands,
369
+ ]
370
+
371
+
372
+ @dataclass(frozen=True)
373
+ class RepositoryAccess(HasRepository, SetupStep):
374
+ """
375
+ Giving Claude access to the repository sessions read and open pull requests
376
+ against.
377
+ """
378
+
379
+ @property
380
+ def title(self) -> str:
381
+ """See :attr:`SetupStep.title`."""
382
+ return f"Connect GitHub, so Claude can work in {self.repository.full_name}"
383
+
384
+ @property
385
+ def reason(self) -> str:
386
+ """See :attr:`SetupStep.reason`."""
387
+ return (
388
+ "This is what lets a session clone the fork, push a branch, open a pull "
389
+ "request and comment on one - and read the state the plan site is built from."
390
+ )
391
+
392
+ def instructions(self) -> list[str]:
393
+ """See :meth:`SetupStep.instructions`."""
394
+ return [
395
+ f"Authorize GitHub: {SetupLink.GITHUB_AUTHORIZATION}",
396
+ "One authorization covers every repository your GitHub account can see.",
397
+ "If your Claude plan is Team or Enterprise, an owner enables the GitHub "
398
+ f"connector first or no sign-in appears: "
399
+ f"{SetupLink.ORGANIZATION_CONNECTORS}",
400
+ "The Claude GitHub App is separate and optional: it adds auto-fix on pull "
401
+ "requests, and is not what grants access.",
402
+ ]
403
+
404
+
405
+ @dataclass(frozen=True)
406
+ class ForkActions(HasRepository, SetupStep):
407
+ """
408
+ Switching Actions on in a fork, where ``/upstream-reviews``' Action runs.
409
+ """
410
+
411
+ @property
412
+ def title(self) -> str:
413
+ """See :attr:`SetupStep.title`."""
414
+ return f"Enable Actions on {self.repository.full_name}, if it is a fork"
415
+
416
+ @property
417
+ def reason(self) -> str:
418
+ """See :attr:`SetupStep.reason`."""
419
+ return (
420
+ "GitHub starts every fork with Actions off, and /upstream-reviews reads "
421
+ f"the upstream from a run on the fork's {ActionBranch.NAME} branch."
422
+ )
423
+
424
+ def instructions(self) -> list[str]:
425
+ """See :meth:`SetupStep.instructions`."""
426
+ return [
427
+ f"Open {Host.GITHUB.url}/{self.repository.full_name}/actions and press "
428
+ '"I understand my workflows, go ahead and enable them".',
429
+ "Nothing to do if that page lists workflows already, or the repository "
430
+ "is not a fork.",
431
+ ]
432
+
433
+
434
+ @dataclass(frozen=True)
435
+ class PersistentVariables(SetupStep):
436
+ """
437
+ Carrying the personal-notes settings into environments that clone fresh every
438
+ session.
439
+ """
440
+
441
+ variable_lines: tuple[str, ...]
442
+ """
443
+ The ``NAME=value`` lines to paste, empty when every setting is still its default.
444
+ """
445
+
446
+ @classproperty
447
+ def comment_marker(cls) -> str:
448
+ """
449
+ What starts a comment in the ``.env`` format an environment's variable list uses.
450
+ """
451
+ return "#"
452
+
453
+ @classmethod
454
+ def quoted_if_needed(cls, value: str) -> str:
455
+ """
456
+ Quote a variable's value when leaving it bare would truncate it.
457
+
458
+ An unquoted value is read to the first comment marker and the rest of the line
459
+ is dropped, which is silent - the variable is set, to a prefix of what was
460
+ pasted.
461
+
462
+ :param value: The value to write after the ``=``.
463
+ :return: The value, quoted only when it carries a comment marker.
464
+ """
465
+ if cls.comment_marker not in value:
466
+ return value
467
+ return f'"{value}"'
468
+
469
+ @classmethod
470
+ def resolve(
471
+ cls, project_root: Path, environment: Mapping[str, str]
472
+ ) -> PersistentVariables:
473
+ """
474
+ Work out which settings this clone has moved off their defaults.
475
+
476
+ :param project_root: The clone to read settings from.
477
+ :param environment: The environment to read them from.
478
+ :return: The step, carrying only the lines that differ from the defaults.
479
+ """
480
+ lines = []
481
+ for setting in PersonalNotesSetting:
482
+ value = setting.resolve(project_root, environment)
483
+ if value != setting.default:
484
+ lines.append(
485
+ f"{setting.environment_variable}={cls.quoted_if_needed(value)}"
486
+ )
487
+ return cls(variable_lines=tuple(lines))
488
+
489
+ @property
490
+ def title(self) -> str:
491
+ """See :attr:`SetupStep.title`."""
492
+ return "Carry your settings into environments that clone fresh"
493
+
494
+ @property
495
+ def reason(self) -> str:
496
+ """See :attr:`SetupStep.reason`."""
497
+ return (
498
+ "Claude Code on the web starts from a new clone every session, so git "
499
+ "config set inside one is gone by the next."
500
+ )
501
+
502
+ def instructions(self) -> list[str]:
503
+ """See :meth:`SetupStep.instructions`."""
504
+ if not self.variable_lines:
505
+ return ["Nothing to paste: every setting is still its default."]
506
+ return [
507
+ f"Open your environment at {SetupLink.ENVIRONMENT_SELECTOR} and paste these into "
508
+ f"its variable list ({SetupLink.ENVIRONMENT_VARIABLES}):",
509
+ *self.variable_lines,
510
+ ]
511
+
512
+
513
+ # %% the checklist they add up to
514
+
515
+
516
+ @dataclass(frozen=True)
517
+ class SetupChecklist:
518
+ """
519
+ The steps one clone leaves to its user, in the order they should be done.
520
+ """
521
+
522
+ steps: tuple[SetupStep, ...]
523
+ """
524
+ The steps that apply to this clone.
525
+ """
526
+
527
+ @classproperty
528
+ def heading(cls) -> str:
529
+ """
530
+ The line introducing the printed list.
531
+ """
532
+ return "These steps are yours - no script can do them:"
533
+
534
+ @classmethod
535
+ def for_clone(
536
+ cls, project_root: Path, environment: Mapping[str, str]
537
+ ) -> SetupChecklist:
538
+ """
539
+ Work out which steps a clone leaves to its user, and fill them in from it.
540
+
541
+ The repository-specific steps are omitted when no GitHub repository can be
542
+ resolved from the clone's remotes, since neither can be acted on without one.
543
+
544
+ :param project_root: The clone the steps are about.
545
+ :param environment: The environment its settings resolve from.
546
+ :return: The checklist.
547
+ """
548
+ notes_remote = PersonalNotesSetting.REMOTE.resolve(project_root, environment)
549
+ repository = resolve_repository(project_root, notes_remote)
550
+ steps: list[SetupStep] = []
551
+ if repository is not None:
552
+ steps.extend(
553
+ [
554
+ ForkLabels(repository),
555
+ RepositoryAccess(repository),
556
+ ForkActions(repository),
557
+ ]
558
+ )
559
+ steps.append(PersistentVariables.resolve(project_root, environment))
560
+ return cls(steps=tuple(steps))
561
+
562
+ def render(self) -> str:
563
+ """
564
+ Render the whole checklist as it is printed.
565
+
566
+ :return: The full output.
567
+ """
568
+ blocks = [
569
+ step.render(number) for number, step in enumerate(self.steps, start=1)
570
+ ]
571
+ return "\n\n".join([self.heading, *blocks])
572
+
573
+
574
+ # %% the steps a script performs
575
+
576
+
577
+ @dataclass
578
+ class PersonalNotesWriteRefusedError(RuntimeError):
579
+ """
580
+ Raised when the personal-notes writer would not push a file.
581
+ """
582
+
583
+ detail: str
584
+ """
585
+ What the writer said.
586
+ """
587
+
588
+ def __str__(self) -> str:
589
+ """:return: Why nothing was saved."""
590
+ return f"could not save to the personal-notes branch: {self.detail}"
591
+
592
+
593
+ @dataclass(frozen=True)
594
+ class PersonalUpstream(HasRepository):
595
+ """
596
+ Naming the project's upstream in the user's personal ``stack.toml``, so a project
597
+ that commits nothing of basstler's still has one.
598
+ """
599
+
600
+ @classproperty
601
+ def setting_line(cls) -> re.Pattern[str]:
602
+ """
603
+ A ``stack.toml`` line naming the upstream, wherever it sits in the file.
604
+ """
605
+ return re.compile(
606
+ rf"^[ \t]*{StackSetting.UPSTREAM_REPOSITORY}[ \t]*=.*(?:\n|$)", re.MULTILINE
607
+ )
608
+
609
+ def written_over(self, existing: str) -> str:
610
+ """
611
+ Name the upstream in a personal ``stack.toml``, keeping every other setting.
612
+
613
+ :param existing: The file as it is, empty when there is none yet.
614
+ :return: The file with any earlier upstream replaced by this one.
615
+ """
616
+ kept = self.setting_line.sub("", existing)
617
+ if kept and not kept.endswith("\n"):
618
+ kept += "\n"
619
+ return (
620
+ f"{kept}{StackSetting.UPSTREAM_REPOSITORY} = "
621
+ f'"{self.repository.full_name}"\n'
622
+ )
623
+
624
+ @staticmethod
625
+ def existing(project_root: Path) -> str:
626
+ """
627
+ :param project_root: The clone to fetch the personal-notes branch from.
628
+ :return: The personal ``stack.toml`` on that branch, empty when there is none.
629
+ """
630
+ fetched = ShellConfigurationFunction.FETCH_PERSONAL_NOTES_BRANCH.run(
631
+ project_root
632
+ )
633
+ if fetched.returncode != 0:
634
+ return ""
635
+ shown = subprocess.run(
636
+ [
637
+ "git",
638
+ "show",
639
+ FetchedBranchReference.PERSONAL_NOTES.file_at(
640
+ ProjectLocation.PERSONAL_STACK_CONFIGURATION
641
+ ),
642
+ ],
643
+ cwd=project_root,
644
+ capture_output=True,
645
+ encoding="utf-8",
646
+ )
647
+ return shown.stdout if shown.returncode == 0 else ""
648
+
649
+ def save(self, project_root: Path) -> None:
650
+ """
651
+ Push the personal ``stack.toml`` naming this upstream to the notes branch.
652
+
653
+ :param project_root: The clone to save from.
654
+ :raises PersonalNotesWriteRefusedError: If the writer would not push it.
655
+ """
656
+ with tempfile.TemporaryDirectory() as scratch_directory:
657
+ scratch_file = Path(scratch_directory) / "stack.toml"
658
+ TextFile(scratch_file).write(self.written_over(self.existing(project_root)))
659
+ written = subprocess.run(
660
+ Bash.locate(os.environ).command(
661
+ PluginRoot.locate(os.environ).path_of(
662
+ PluginLocation.PERSONAL_NOTES_WRITER_SCRIPT
663
+ ),
664
+ "--source",
665
+ str(scratch_file),
666
+ "--destination",
667
+ ProjectLocation.PERSONAL_STACK_CONFIGURATION,
668
+ "--message",
669
+ f"Name {self.repository.full_name} as the upstream",
670
+ ),
671
+ cwd=project_root,
672
+ capture_output=True,
673
+ encoding="utf-8",
674
+ )
675
+ if written.returncode != 0:
676
+ raise PersonalNotesWriteRefusedError(
677
+ written.stderr.strip() or "the notes writer reported no detail"
678
+ )
679
+
680
+
681
+ # %% command line
682
+
683
+
684
+ class SetupCommand(StrEnum):
685
+ """
686
+ The steps this module performs rather than prints.
687
+ """
688
+
689
+ CONFIGURE_UPSTREAM = "configure-upstream"
690
+ """
691
+ Name the project's upstream in the personal ``stack.toml``.
692
+ """
693
+
694
+ INSTALL_UPSTREAM_REVIEWS_ACTION = "install-upstream-reviews-action"
695
+ """
696
+ Write ``/upstream-reviews``' Action onto the fork's own branch, or update it.
697
+ """
698
+
699
+
700
+ class SetupCommandOption(StrEnum):
701
+ """
702
+ Every option a command takes, named once so no caller spells one out.
703
+ """
704
+
705
+ REPOSITORY = "--repository"
706
+ """
707
+ The ``owner/name`` a command is about.
708
+ """
709
+
710
+ BRANCH_OR_TAG = "--branch-or-tag"
711
+ """
712
+ The basstler branch or release tag an installed workflow runs.
713
+ """
714
+
715
+
716
+ def _parse_arguments(argv: list[str] | None) -> argparse.Namespace:
717
+ """
718
+ Parse the command line.
719
+
720
+ :param argv: The arguments to parse, defaulting to the process's own.
721
+ :return: The parsed arguments, with no command when the checklist is wanted.
722
+ """
723
+ parser = argparse.ArgumentParser(description=__doc__)
724
+ commands = parser.add_subparsers(dest="command")
725
+ configure_upstream = commands.add_parser(
726
+ SetupCommand.CONFIGURE_UPSTREAM,
727
+ help="name the project's upstream in your personal stack.toml",
728
+ )
729
+ configure_upstream.add_argument(
730
+ SetupCommandOption.REPOSITORY,
731
+ type=Repository.parse,
732
+ required=True,
733
+ help="the owner/name repository the project's pull requests are reviewed on",
734
+ )
735
+ install_action = commands.add_parser(
736
+ SetupCommand.INSTALL_UPSTREAM_REVIEWS_ACTION,
737
+ help="write /upstream-reviews' Action onto the fork's own branch",
738
+ )
739
+ install_action.add_argument(
740
+ SetupCommandOption.BRANCH_OR_TAG,
741
+ required=True,
742
+ help="the basstler branch or release tag it runs, the one the session installed",
743
+ )
744
+ return parser.parse_args(argv)
745
+
746
+
747
+ def main(argv: list[str] | None = None) -> int:
748
+ """
749
+ Print the checklist for this clone, or perform the step a command names.
750
+
751
+ :param argv: The arguments to parse, defaulting to the process's own.
752
+ :return: The process exit status.
753
+ """
754
+ arguments = _parse_arguments(argv)
755
+ project_root = Path(
756
+ os.environ.get(ClaudeCodeVariable.PROJECT_DIRECTORY, Path.cwd())
757
+ )
758
+ if arguments.command == SetupCommand.CONFIGURE_UPSTREAM:
759
+ try:
760
+ PersonalUpstream(arguments.repository).save(project_root)
761
+ except PersonalNotesWriteRefusedError as failure:
762
+ logger.error(failure)
763
+ return 1
764
+ logger.info(
765
+ f"{StackSetting.UPSTREAM_REPOSITORY} = {arguments.repository.full_name} "
766
+ f"saved to {ProjectLocation.PERSONAL_STACK_CONFIGURATION} on the "
767
+ "personal-notes branch"
768
+ )
769
+ return 0
770
+ if arguments.command == SetupCommand.INSTALL_UPSTREAM_REVIEWS_ACTION:
771
+ remote = PersonalNotesSetting.REMOTE.resolve(project_root, os.environ)
772
+ branch = RemoteBranch(
773
+ GitHubRemote(GitCommandRunner(project_root), remote), ActionBranch.NAME
774
+ )
775
+ try:
776
+ changed = ActionInstallation(arguments.branch_or_tag).install(branch)
777
+ except GitCommandFailed as failure:
778
+ logger.error(failure)
779
+ return 1
780
+ logger.info(
781
+ f"{ActionBranch.NAME} on {branch.repository.description} "
782
+ f"{'now runs' if changed else 'already runs'} basstler {arguments.branch_or_tag}"
783
+ )
784
+ return 0
785
+ logger.info(SetupChecklist.for_clone(project_root, os.environ).render())
786
+ return 0
787
+
788
+
789
+ if __name__ == "__main__":
790
+ sys.exit(main())