basstler-core 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.
basstler/bash.py ADDED
@@ -0,0 +1,122 @@
1
+ """
2
+ The bash the plugin's scripts and its shell configuration run in.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import shutil
9
+ from collections.abc import Iterator, Mapping
10
+ from dataclasses import dataclass
11
+ from enum import StrEnum
12
+ from pathlib import Path
13
+
14
+ from basstler.environment import OperatingSystemVariable
15
+ from basstler.exceptions import BashNotFoundError
16
+ from basstler.locations import ClaudeCodeVariable
17
+
18
+ # %% the programs searched for
19
+
20
+
21
+ class LocatedProgram(StrEnum):
22
+ """
23
+ The programs searched for to find bash, by the name a search finds them under.
24
+ """
25
+
26
+ BASH = "bash"
27
+ """
28
+ The shell the scripts are written for.
29
+ """
30
+
31
+ GIT = "git"
32
+ """
33
+ Git, whose Windows installation ships Git Bash beside it.
34
+ """
35
+
36
+
37
+ # %% the bash itself
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Bash:
42
+ """
43
+ A bash program, named by its full path so Windows cannot start WSL's launcher in its
44
+ place.
45
+ """
46
+
47
+ executable: Path
48
+ """
49
+ The program itself.
50
+ """
51
+
52
+ @classmethod
53
+ def locate(cls, environment: Mapping[str, str]) -> Bash:
54
+ """
55
+ Find the bash to run scripts in: the one Claude Code is configured with, else the
56
+ first on the search path, else the one installed with the git on the search
57
+ path - never one in the Windows directory, which starts WSL.
58
+
59
+ :param environment: The environment the scripts will run in.
60
+ :return: The bash found.
61
+ :raises BashNotFoundError: If every bash found is in the Windows directory, or
62
+ none is found.
63
+ """
64
+ configured = environment.get(ClaudeCodeVariable.GIT_BASH_PATH)
65
+ if configured:
66
+ return cls(Path(configured))
67
+ found = list(
68
+ cls.candidates(
69
+ environment.get(OperatingSystemVariable.EXECUTABLE_SEARCH_PATH)
70
+ )
71
+ )
72
+ windows_directory = environment.get(OperatingSystemVariable.WINDOWS_DIRECTORY)
73
+ usable = [
74
+ candidate
75
+ for candidate in found
76
+ if not cls.is_within(candidate, windows_directory)
77
+ ]
78
+ if not usable:
79
+ raise BashNotFoundError(passed_over=found)
80
+ return cls(usable[0])
81
+
82
+ @staticmethod
83
+ def candidates(search_path: str | None) -> Iterator[Path]:
84
+ """
85
+ :param search_path: The directories to search, the process's own when ``None``.
86
+ :return: Every bash found, in the order they are preferred: the first on the
87
+ search path, then those in a ``bin`` directory of an ancestor of the first
88
+ git on it.
89
+ """
90
+ on_search_path = shutil.which(LocatedProgram.BASH, path=search_path)
91
+ if on_search_path is not None:
92
+ yield Path(on_search_path)
93
+ git = shutil.which(LocatedProgram.GIT, path=search_path)
94
+ if git is None:
95
+ return
96
+ for installation in Path(git).parents:
97
+ beside_git = shutil.which(
98
+ LocatedProgram.BASH, path=str(installation / "bin")
99
+ )
100
+ if beside_git is not None:
101
+ yield Path(beside_git)
102
+
103
+ @staticmethod
104
+ def is_within(program: Path, directory: str | None) -> bool:
105
+ """
106
+ :param program: A program found.
107
+ :param directory: A directory, or ``None`` when there is none.
108
+ :return: Whether *program* is inside *directory*, compared as the platform
109
+ compares paths.
110
+ """
111
+ if directory is None:
112
+ return False
113
+ return Path(os.path.normcase(program)).is_relative_to(
114
+ os.path.normcase(directory)
115
+ )
116
+
117
+ def command(self, *arguments: str | os.PathLike[str]) -> list[str]:
118
+ """
119
+ :param arguments: The script to run and its arguments, or ``-c`` and a command.
120
+ :return: The command line running them in this bash.
121
+ """
122
+ return [str(self.executable), *(os.fspath(argument) for argument in arguments)]
basstler/class_name.py ADDED
@@ -0,0 +1,22 @@
1
+ """
2
+ A class's own name, spelled the way a command line or a document spells it.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+
9
+
10
+ class HyphenatedClassName:
11
+ """
12
+ Gives a class the hyphenated, lower-case form of its own name.
13
+ """
14
+
15
+ @classmethod
16
+ def hyphenated_class_name(cls, suffix: str = "") -> str:
17
+ """
18
+ :param suffix: A trailing part of the class name to leave out.
19
+ :return: The class name in lower case, words joined by hyphens.
20
+ """
21
+ words = cls.__name__.removesuffix(suffix)
22
+ return re.sub(r"(?<!^)(?=[A-Z])", "-", words).lower()
@@ -0,0 +1,41 @@
1
+ """
2
+ A property that answers on the class rather than on an instance.
3
+
4
+ Copied from krrood :cite:`krrood` until krrood's light core is released.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable
10
+ from typing import Any
11
+
12
+
13
+ class classproperty:
14
+ """
15
+ Reads a value off the class itself, and stays abstract until one is supplied.
16
+
17
+ ``property`` answers only on instances, and chaining ``classmethod`` with it was
18
+ removed in Python 3.13, so a value that belongs to the class rather than to any
19
+ instance needs a descriptor of its own. Written in this repository rather than taken
20
+ from ``krrood`` because this package's first version is deliberately independent of
21
+ it, which is the boundary decision 12 records for this tooling.
22
+
23
+ An abstract accessor answers with the descriptor instead of calling it, which is what
24
+ lets :class:`abc.ABCMeta` still see it as abstract on a subclass that supplied
25
+ nothing - the refusal then lands where every other missing abstract member's does.
26
+ """
27
+
28
+ def __init__(self, accessor: Callable[[type], Any]) -> None:
29
+ """:param accessor: The function answering the value, given the owning class."""
30
+ self.accessor = accessor
31
+ self.__isabstractmethod__ = getattr(accessor, "__isabstractmethod__", False)
32
+ self.__doc__ = accessor.__doc__
33
+
34
+ def __get__(self, instance: Any, owner: type | None = None) -> Any:
35
+ """:param instance: The instance read through, absent on class access.
36
+ :param owner: The class read from.
37
+ :return: The value for the owning class, or this descriptor while it is
38
+ abstract."""
39
+ if self.__isabstractmethod__:
40
+ return self
41
+ return self.accessor(owner if owner is not None else type(instance))
@@ -0,0 +1,92 @@
1
+ """
2
+ One command of a command-line tool, and how a tool finds every one of its commands.
3
+
4
+ A command owns its own name, its own flags and its own work, so adding one is writing a
5
+ subclass: :meth:`Command.every_command` finds it, and nothing else has to be told it
6
+ exists. What a command is handed to run and what it answers with differ per tool, so each
7
+ tool's own base declares ``run``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import functools
14
+ from abc import ABC, abstractmethod
15
+ from dataclasses import dataclass
16
+ from typing import TypeVar
17
+
18
+ from cyclopts import Group, validators
19
+
20
+ from basstler.class_name import HyphenatedClassName
21
+ from basstler.class_property import classproperty
22
+
23
+ # %% parameter groups
24
+
25
+ plan_item_selection = Group(
26
+ "Item selection", validator=validators.LimitedChoice(1), default_parameter=None
27
+ )
28
+ """
29
+ The two ways a command names one plan item - by id or by branch - of which exactly one
30
+ is given.
31
+ """
32
+
33
+ # %% a command
34
+
35
+
36
+ CommandType = TypeVar("CommandType", bound="Command")
37
+ """
38
+ The concrete command type one tool's commands are found as.
39
+ """
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class Command(HyphenatedClassName, ABC):
44
+ """
45
+ One operation a command-line tool offers.
46
+
47
+ The name and the description belong to the class rather than to an instance - the
48
+ parser reads them to build the command line before anything is constructed - so they
49
+ are :class:`basstler.class_property.classproperty` members. The name follows from the
50
+ class name; the description is abstract, and :meth:`every_command` builds every
51
+ subclass, so a command that cannot say what it does is refused as its tool is
52
+ imported.
53
+ """
54
+
55
+ @classmethod
56
+ @functools.cache
57
+ def every_command(cls: type[CommandType]) -> tuple[CommandType, ...]:
58
+ """
59
+ Every command of the tool whose base this is asked of, in the order they are
60
+ defined.
61
+
62
+ Asked of a tool's own base, never of :class:`Command` itself: only direct
63
+ subclasses are found.
64
+
65
+ :return: One instance of every direct subclass of the class asked.
66
+ """
67
+ return tuple(subclass() for subclass in cls.__subclasses__())
68
+
69
+ @classproperty
70
+ def invoked_as(cls) -> str:
71
+ """
72
+ The name it is invoked by on the command line: its class name in lower case,
73
+ words joined by hyphens, without a trailing ``Command``.
74
+ """
75
+ return cls.hyphenated_class_name(Command.__name__)
76
+
77
+ @classproperty
78
+ @abstractmethod
79
+ def description(cls) -> str:
80
+ """
81
+ What it does, as ``--help`` puts it.
82
+ """
83
+
84
+ def declare_arguments(self, parser: argparse.ArgumentParser) -> None:
85
+ """
86
+ Declare this command's own flags.
87
+
88
+ Concrete rather than abstract: most commands take none, and requiring an empty
89
+ override of every one of them would say nothing.
90
+
91
+ :param parser: The subparser to declare them on.
92
+ """
@@ -0,0 +1,23 @@
1
+ """
2
+ Naming where a GitHub token came from, so a refusal can say which token to renew.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+
8
+ class CredentialOrigin:
9
+ """
10
+ Where the token a GitHub request authenticates with comes from.
11
+ """
12
+
13
+ def describe_credential(self) -> str:
14
+ """
15
+ :return: The token, named by where it came from.
16
+ """
17
+ raise NotImplementedError
18
+
19
+ def suggest_renewal(self) -> str:
20
+ """
21
+ :return: How to replace the token with a valid one.
22
+ """
23
+ raise NotImplementedError
@@ -0,0 +1,54 @@
1
+ """
2
+ Removing a directory and everything in it, read-only entries included.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import shutil
9
+ import stat
10
+ from collections.abc import Callable
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+
14
+ # %% the tree
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class DirectoryTree:
19
+ """
20
+ A directory and everything in it, such as a clone whose object files git left
21
+ read-only, which Windows refuses to delete.
22
+ """
23
+
24
+ root: Path
25
+ """
26
+ The directory at the top of the tree.
27
+ """
28
+
29
+ def remove(self) -> None:
30
+ """
31
+ Delete the tree, making each entry that refuses deletion writable first; a tree
32
+ that is not there is left as it is.
33
+ """
34
+ if not self.root.exists():
35
+ return
36
+ shutil.rmtree(self.root, onexc=self.remove_writable)
37
+
38
+ @staticmethod
39
+ def remove_writable(
40
+ removal: Callable[[str], object], path: str, refusal: BaseException
41
+ ) -> None:
42
+ """
43
+ Make *path* and the directory holding it writable, then remove it again.
44
+
45
+ :param removal: The function that refused to remove *path*.
46
+ :param path: The entry it refused.
47
+ :param refusal: Why it refused, raised again when it is not a permission error.
48
+ """
49
+ if not isinstance(refusal, PermissionError):
50
+ raise refusal
51
+ writable = stat.S_IRWXU
52
+ os.chmod(os.path.dirname(path), writable)
53
+ os.chmod(path, writable)
54
+ removal(path)
@@ -0,0 +1,64 @@
1
+ """
2
+ An email address, read out of the text a user types.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass
8
+
9
+ from basstler.class_property import classproperty
10
+ from basstler.exceptions import MalformedEmailAddressError
11
+
12
+ # %% the address
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class EmailAddress:
17
+ """
18
+ An email address, written as its text wherever a string is expected.
19
+ """
20
+
21
+ local_part: str
22
+ """
23
+ The part before the last ``@``: the mailbox.
24
+ """
25
+
26
+ domain: str
27
+ """
28
+ The part after the last ``@``: the host that receives the mail.
29
+ """
30
+
31
+ @classproperty
32
+ def separator(cls) -> str:
33
+ """
34
+ What separates the local part from the domain.
35
+ """
36
+ return "@"
37
+
38
+ @classmethod
39
+ def parse(cls, text: str) -> EmailAddress:
40
+ """
41
+ Parse a ``local-part@domain`` address.
42
+
43
+ :param text: The address to parse.
44
+ :return: The parsed address.
45
+ :raises MalformedEmailAddressError: If *text* lacks a local part or a domain.
46
+ """
47
+ if not cls.is_well_formed(text):
48
+ raise MalformedEmailAddressError(text)
49
+ local_part, _, domain = text.rpartition(cls.separator)
50
+ return cls(local_part, domain)
51
+
52
+ @classmethod
53
+ def is_well_formed(cls, text: str) -> bool:
54
+ """
55
+ :param text: The text to test.
56
+ :return: Whether *text* has a local part and a domain, so :meth:`parse` accepts
57
+ it.
58
+ """
59
+ local_part, separator, domain = text.rpartition(cls.separator)
60
+ return bool(local_part and separator and domain)
61
+
62
+ def __str__(self) -> str:
63
+ """:return: The address as it is written."""
64
+ return f"{self.local_part}{self.separator}{self.domain}"
@@ -0,0 +1,177 @@
1
+ """
2
+ The environment variables this package reads, grouped by who sets them.
3
+
4
+ Every group is an :class:`EnvironmentVariable`, so reading one is the same call
5
+ whichever group it belongs to, and a variable is named once rather than typed out where
6
+ it is read.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from enum import StrEnum
13
+
14
+ from basstler.credential_origin import CredentialOrigin
15
+
16
+
17
+ class EnvironmentFlag(StrEnum):
18
+ """
19
+ The values a variable that switches something on or off is set to.
20
+ """
21
+
22
+ TRUE = "true"
23
+ """
24
+ The thing the variable stands for is on.
25
+ """
26
+
27
+
28
+ class EnvironmentVariable(StrEnum):
29
+ """
30
+ An environment variable, named by its value.
31
+
32
+ The base every group of them extends.
33
+ """
34
+
35
+ def read(self) -> str | None:
36
+ """
37
+ :return: The variable's value in this process's environment, or ``None`` when it
38
+ is not set.
39
+ """
40
+ return os.environ.get(self)
41
+
42
+ def is_true(self) -> bool:
43
+ """:return: Whether the variable is set to :attr:`EnvironmentFlag.TRUE`."""
44
+ return self.read() == EnvironmentFlag.TRUE
45
+
46
+
47
+ class OperatingSystemVariable(EnvironmentVariable):
48
+ """
49
+ The variables the operating system sets for every process.
50
+ """
51
+
52
+ EXECUTABLE_SEARCH_PATH = "PATH"
53
+ """
54
+ The directories a program is searched for in.
55
+ """
56
+
57
+ WINDOWS_DIRECTORY = "SYSTEMROOT"
58
+ """
59
+ The Windows installation's own directory, set only on Windows, spelled as Windows
60
+ lists it in a copy of the environment.
61
+ """
62
+
63
+
64
+ class GitBashVariable(EnvironmentVariable):
65
+ """
66
+ The variables Git for Windows' bash (MSYS2) reads before it starts a program.
67
+ """
68
+
69
+ ARGUMENT_CONVERSION_EXCLUSIONS = "MSYS2_ARG_CONV_EXCL"
70
+ """
71
+ The ``;``-separated prefixes of the arguments it passes on as written rather than
72
+ rewriting them as Windows paths.
73
+ """
74
+
75
+
76
+ class GitVariable(EnvironmentVariable):
77
+ """
78
+ The variables git reads that this package, or its tests, set for the commands run.
79
+ """
80
+
81
+ INDEX_FILE = "GIT_INDEX_FILE"
82
+ """
83
+ The index git stages into, in place of the clone's own.
84
+ """
85
+
86
+ CONFIGURATION_COUNT = "GIT_CONFIG_COUNT"
87
+ """
88
+ How many configuration entries the environment passes to git.
89
+ """
90
+
91
+ CONFIGURATION_KEY_PREFIX = "GIT_CONFIG_KEY_"
92
+ """
93
+ Followed by an entry's index, names the variable holding that entry's key.
94
+ """
95
+
96
+ CONFIGURATION_VALUE_PREFIX = "GIT_CONFIG_VALUE_"
97
+ """
98
+ Followed by an entry's index, names the variable holding that entry's value.
99
+ """
100
+
101
+ COMMITTER_DATE = "GIT_COMMITTER_DATE"
102
+ """
103
+ The date git records as a new commit's committer date, in place of the clock's.
104
+ """
105
+
106
+
107
+ class GitHubCredentialVariable(CredentialOrigin, EnvironmentVariable):
108
+ """
109
+ The variables a GitHub token is read from, in the order they are tried.
110
+ """
111
+
112
+ GH_TOKEN = "GH_TOKEN"
113
+ """
114
+ The token the ``gh`` CLI reads, preferred where both are set.
115
+ """
116
+
117
+ GITHUB_TOKEN = "GITHUB_TOKEN"
118
+ """
119
+ The token GitHub Actions hands a workflow.
120
+ """
121
+
122
+ def describe_credential(self) -> str:
123
+ """
124
+ :return: :meth:`CredentialOrigin.describe_credential`: the token in this
125
+ variable.
126
+ """
127
+ return f"the token in {self}"
128
+
129
+ def suggest_renewal(self) -> str:
130
+ """
131
+ :return: :meth:`CredentialOrigin.suggest_renewal`: set a valid token in this
132
+ variable.
133
+ """
134
+ return f"Set a valid token in {self}."
135
+
136
+ @classmethod
137
+ def first_set(cls) -> GitHubCredentialVariable | None:
138
+ """
139
+ :return: The first variable holding a non-empty token, in the order they are
140
+ tried, or ``None`` when none does.
141
+ """
142
+ return next((variable for variable in cls if variable.read()), None)
143
+
144
+ @classmethod
145
+ def first_token(cls) -> str | None:
146
+ """
147
+ :return: The first non-empty token, in the order the variables are tried, or
148
+ ``None`` when none is set.
149
+ """
150
+ variable = cls.first_set()
151
+ return None if variable is None else variable.read()
152
+
153
+
154
+ class GitHubActionsVariable(EnvironmentVariable):
155
+ """
156
+ The variables a GitHub Actions runner sets for the steps it runs.
157
+ """
158
+
159
+ STEP_SUMMARY = "GITHUB_STEP_SUMMARY"
160
+ """
161
+ The file a step appends its Markdown job summary to.
162
+ """
163
+
164
+ OUTPUT = "GITHUB_OUTPUT"
165
+ """
166
+ The file a step appends its ``<key>=<value>`` outputs to.
167
+ """
168
+
169
+ RUNNER_TEMPORARY_DIRECTORY = "RUNNER_TEMP"
170
+ """
171
+ A directory the runner empties for each job, which steps hand files through.
172
+ """
173
+
174
+ REPOSITORY_OWNER = "GITHUB_REPOSITORY_OWNER"
175
+ """
176
+ The owner of the repository the workflow runs in.
177
+ """