aa-toolkit-cli 0.1.0a1__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.
- aa_cli/__init__.py +1 -0
- aa_cli/add.py +221 -0
- aa_cli/choices.py +33 -0
- aa_cli/cli.py +616 -0
- aa_cli/commands.py +207 -0
- aa_cli/crash.py +175 -0
- aa_cli/git.py +24 -0
- aa_cli/init.py +383 -0
- aa_cli/output.py +101 -0
- aa_cli/process.py +42 -0
- aa_cli/redact.py +207 -0
- aa_cli/secret.py +67 -0
- aa_cli/templates/AGENTS.md.tmpl +32 -0
- aa_cli/templates/CLAUDE.md.tmpl +1 -0
- aa_cli/templates/LICENSE.tmpl +21 -0
- aa_cli/templates/README.md.tmpl +23 -0
- aa_cli/templates/ci.yml.tmpl +28 -0
- aa_cli/templates/cli_init.py.tmpl +5 -0
- aa_cli/templates/cli_test.py.tmpl +7 -0
- aa_cli/templates/gitignore.tmpl +22 -0
- aa_cli/templates/lib_init.py.tmpl +5 -0
- aa_cli/templates/lib_test.py.tmpl +5 -0
- aa_cli/templates/pyproject.toml.tmpl +2 -0
- aa_toolkit_cli-0.1.0a1.dist-info/METADATA +25 -0
- aa_toolkit_cli-0.1.0a1.dist-info/RECORD +28 -0
- aa_toolkit_cli-0.1.0a1.dist-info/WHEEL +4 -0
- aa_toolkit_cli-0.1.0a1.dist-info/entry_points.txt +3 -0
- aa_toolkit_cli-0.1.0a1.dist-info/licenses/LICENSE +21 -0
aa_cli/init.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
"""``aa init``: the steps that turn an empty folder into a project."""
|
|
2
|
+
|
|
3
|
+
__lazy_modules__ = {
|
|
4
|
+
"aa_cli.git",
|
|
5
|
+
"aa_cli.process",
|
|
6
|
+
"datetime",
|
|
7
|
+
"importlib.resources",
|
|
8
|
+
"keyword",
|
|
9
|
+
"tomllib",
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
import contextlib
|
|
13
|
+
import datetime
|
|
14
|
+
import keyword
|
|
15
|
+
import logging
|
|
16
|
+
import re
|
|
17
|
+
import tomllib
|
|
18
|
+
from collections.abc import Generator
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from enum import StrEnum
|
|
21
|
+
from importlib.resources import files
|
|
22
|
+
from pathlib import Path, PurePosixPath
|
|
23
|
+
|
|
24
|
+
from aa_cli.choices import License
|
|
25
|
+
from aa_cli.git import machine_config
|
|
26
|
+
from aa_cli.process import run
|
|
27
|
+
|
|
28
|
+
log = logging.getLogger("aa")
|
|
29
|
+
|
|
30
|
+
PYTHON_VERSION = "3.15"
|
|
31
|
+
COMMIT_MESSAGE = "chore: initial commit"
|
|
32
|
+
BRANCH = "main"
|
|
33
|
+
PYPROJECT = "pyproject.toml"
|
|
34
|
+
WRITE_FILES_STEP = "write files"
|
|
35
|
+
CI_WORKFLOW = ".github/workflows/ci.yml"
|
|
36
|
+
CI_TEMPLATE = "ci.yml.tmpl"
|
|
37
|
+
|
|
38
|
+
NAME_RULE = (
|
|
39
|
+
"a project name starts with a letter, ends with a letter or digit, holds only"
|
|
40
|
+
" letters, digits, '-' and '_', and is not a Python keyword or a name Windows reserves"
|
|
41
|
+
" (con, prn, aux, nul, com0-com9, lpt0-lpt9)"
|
|
42
|
+
)
|
|
43
|
+
_NAME = re.compile(r"[A-Za-z](?:[A-Za-z0-9_-]*[A-Za-z0-9])?")
|
|
44
|
+
# Windows can't create a folder with one of these names, in any case.
|
|
45
|
+
_WINDOWS_RESERVED = re.compile(r"con|prn|aux|nul|com\d|lpt\d", re.IGNORECASE)
|
|
46
|
+
_PLACEHOLDER = re.compile(r"\{\{(\w+)\}\}")
|
|
47
|
+
_GITHUB_URL = re.compile(r"https://\S+")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Kind(StrEnum):
|
|
51
|
+
CLI = "cli"
|
|
52
|
+
LIB = "lib"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# The package code and the starter test each kind starts with.
|
|
56
|
+
_KIND_TEMPLATES = {
|
|
57
|
+
Kind.CLI: ("cli_init.py.tmpl", "cli_test.py.tmpl"),
|
|
58
|
+
Kind.LIB: ("lib_init.py.tmpl", "lib_test.py.tmpl"),
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class StepFailed(Exception):
|
|
63
|
+
"""A step failed. The message names the step and the tool's error."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, step: str, detail: str, fix: str | None = None) -> None:
|
|
66
|
+
super().__init__(f"step '{step}' failed: {detail}" if detail else f"step '{step}' failed")
|
|
67
|
+
self.step = step
|
|
68
|
+
self.detail = detail
|
|
69
|
+
self.fix = fix
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class StepSpec:
|
|
74
|
+
"""One external command ``aa init`` runs."""
|
|
75
|
+
|
|
76
|
+
name: str
|
|
77
|
+
command: tuple[str, ...]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class InitPlan:
|
|
82
|
+
"""What ``aa init --dry-run`` would create and run."""
|
|
83
|
+
|
|
84
|
+
files: list[str]
|
|
85
|
+
steps: list[StepSpec]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True)
|
|
89
|
+
class OuterWorkspace:
|
|
90
|
+
"""A uv workspace above the target whose members would include the new project."""
|
|
91
|
+
|
|
92
|
+
root: Path
|
|
93
|
+
member: str # the target's path relative to the root, as uv's globs see it
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def fix(self) -> str:
|
|
97
|
+
pyproject = self.root / PYPROJECT
|
|
98
|
+
return (
|
|
99
|
+
f'Under [tool.uv.workspace] in {pyproject}, add exclude = ["{self.member}"]'
|
|
100
|
+
f' (or add "{self.member}" to the existing exclude list)'
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _import_name(name: str) -> str:
|
|
105
|
+
# uv lowercases the name and collapses runs of '-' and '_' into one '_' to get the import name.
|
|
106
|
+
return re.sub(r"[-_]+", "_", name).lower()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def is_valid_name(name: str) -> bool:
|
|
110
|
+
"""Whether ``name`` follows NAME_RULE, so uv can build a package from it as it is."""
|
|
111
|
+
import_name = _import_name(name)
|
|
112
|
+
return (
|
|
113
|
+
_NAME.fullmatch(name) is not None
|
|
114
|
+
# True, False and None are keywords only as typed; the import name catches the rest.
|
|
115
|
+
and not keyword.iskeyword(name)
|
|
116
|
+
and not keyword.iskeyword(import_name)
|
|
117
|
+
and _WINDOWS_RESERVED.fullmatch(name) is None
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def is_empty_folder_or_missing(target: Path) -> bool:
|
|
122
|
+
return not target.exists() or (target.is_dir() and not any(target.iterdir()))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def outer_workspace_taking_in(target: Path) -> OuterWorkspace | None:
|
|
126
|
+
"""The uv workspace above ``target`` that would take it in as a member, if any.
|
|
127
|
+
|
|
128
|
+
uv uses the nearest workspace root above a project. If that root's members
|
|
129
|
+
match the project and its excludes don't, the project joins it no matter
|
|
130
|
+
how it was created, and a project of its own there breaks the outer lock.
|
|
131
|
+
"""
|
|
132
|
+
for folder in target.parents:
|
|
133
|
+
workspace = _uv_workspace(folder / PYPROJECT)
|
|
134
|
+
if workspace is None:
|
|
135
|
+
continue
|
|
136
|
+
member = target.relative_to(folder).as_posix()
|
|
137
|
+
if _matches(member, workspace.get("members", [])) and not _matches(
|
|
138
|
+
member, workspace.get("exclude", [])
|
|
139
|
+
):
|
|
140
|
+
return OuterWorkspace(folder, member)
|
|
141
|
+
return None
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _uv_workspace(pyproject: Path) -> dict[str, list[str]] | None:
|
|
146
|
+
if not pyproject.is_file():
|
|
147
|
+
return None
|
|
148
|
+
try:
|
|
149
|
+
config = tomllib.loads(pyproject.read_text(encoding="utf-8"))
|
|
150
|
+
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as exc:
|
|
151
|
+
log.debug("Cannot read %s: %s", pyproject, exc)
|
|
152
|
+
return None
|
|
153
|
+
workspace = config.get("tool", {}).get("uv", {}).get("workspace")
|
|
154
|
+
if not isinstance(workspace, dict):
|
|
155
|
+
return None
|
|
156
|
+
table: dict[str, list[str]] = workspace # uv's only workspace keys: members and exclude
|
|
157
|
+
return table
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _matches(member: str, patterns: list[str]) -> bool:
|
|
161
|
+
path = PurePosixPath(member)
|
|
162
|
+
return any(path.full_match(pattern.removeprefix("./").rstrip("/")) for pattern in patterns)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@contextlib.contextmanager
|
|
166
|
+
def _rerun_note(target: Path) -> Generator[None]:
|
|
167
|
+
"""Add to a failure what stops ``aa init`` from running again: what it left in ``target``."""
|
|
168
|
+
|
|
169
|
+
def note() -> str:
|
|
170
|
+
if is_empty_folder_or_missing(target):
|
|
171
|
+
return ""
|
|
172
|
+
return f"The folder {target} was left as it is; delete it before running aa init again."
|
|
173
|
+
|
|
174
|
+
try:
|
|
175
|
+
yield
|
|
176
|
+
except StepFailed as exc:
|
|
177
|
+
detail = "\n".join(filter(None, [exc.detail, note()]))
|
|
178
|
+
raise StepFailed(exc.step, detail, exc.fix) from exc
|
|
179
|
+
except FileNotFoundError as exc:
|
|
180
|
+
raise FileNotFoundError(" ".join(filter(None, [f"{exc}.", note()]))) from exc
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _local_steps(kind: Kind) -> list[StepSpec]:
|
|
184
|
+
# --python wins over a UV_PYTHON set in the environment, which would
|
|
185
|
+
# otherwise override the project's pin.
|
|
186
|
+
return [
|
|
187
|
+
# aa makes the repo itself: uv init skips it inside another repo, and the
|
|
188
|
+
# branch must be main whatever the machine's default is.
|
|
189
|
+
StepSpec("git init", ("git", "init", "--quiet", f"--initial-branch={BRANCH}")),
|
|
190
|
+
StepSpec(
|
|
191
|
+
"uv init",
|
|
192
|
+
(
|
|
193
|
+
"uv",
|
|
194
|
+
"init",
|
|
195
|
+
"--lib" if kind is Kind.LIB else "--app",
|
|
196
|
+
"--package",
|
|
197
|
+
"--python",
|
|
198
|
+
PYTHON_VERSION,
|
|
199
|
+
"--no-workspace",
|
|
200
|
+
"--vcs",
|
|
201
|
+
"none",
|
|
202
|
+
),
|
|
203
|
+
),
|
|
204
|
+
StepSpec(
|
|
205
|
+
"add dev dependencies",
|
|
206
|
+
("uv", "add", "--python", PYTHON_VERSION, "--dev", "ruff", "pytest"),
|
|
207
|
+
),
|
|
208
|
+
# The folder holds only what aa just made, so global ignore rules have nothing to protect.
|
|
209
|
+
# One like *.lock would drop a file the project's CI needs, and git add wouldn't say so.
|
|
210
|
+
StepSpec("stage files", ("git", "-c", "core.excludesFile=", "add", "--all")),
|
|
211
|
+
]
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _github_steps(repo_name: str, public: bool) -> list[StepSpec]:
|
|
215
|
+
return [
|
|
216
|
+
StepSpec("initial commit", ("git", "commit", "--quiet", "--message", COMMIT_MESSAGE)),
|
|
217
|
+
StepSpec(
|
|
218
|
+
"create GitHub repo",
|
|
219
|
+
(
|
|
220
|
+
"gh",
|
|
221
|
+
"repo",
|
|
222
|
+
"create",
|
|
223
|
+
repo_name,
|
|
224
|
+
"--public" if public else "--private",
|
|
225
|
+
"--source",
|
|
226
|
+
".",
|
|
227
|
+
"--push",
|
|
228
|
+
),
|
|
229
|
+
),
|
|
230
|
+
]
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def plan_project(
|
|
234
|
+
target: Path, kind: Kind, license_choice: License, *, github: bool, public: bool
|
|
235
|
+
) -> InitPlan:
|
|
236
|
+
"""Validate and render templates in memory for ``aa init --dry-run``, writing nothing."""
|
|
237
|
+
holder = _resolve_license_holder(license_choice)
|
|
238
|
+
package = _import_name(target.name)
|
|
239
|
+
# Render every template in memory so a template bug fails the dry run like a real run.
|
|
240
|
+
render("pyproject.toml.tmpl")
|
|
241
|
+
rendered = _render_outputs(target.name, package, kind, license_choice, holder)
|
|
242
|
+
uv_files = {".python-version", PYPROJECT, "uv.lock"}
|
|
243
|
+
if kind is Kind.LIB:
|
|
244
|
+
uv_files.add(f"src/{package}/py.typed")
|
|
245
|
+
steps = _local_steps(kind)
|
|
246
|
+
if github:
|
|
247
|
+
steps.extend(_github_steps(target.name, public))
|
|
248
|
+
return InitPlan(files=sorted(uv_files | rendered.keys()), steps=steps)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def create_project(target: Path, kind: Kind, license_choice: License) -> list[str]:
|
|
252
|
+
"""Create the project in ``target`` (missing or empty) and return the files it holds."""
|
|
253
|
+
with _rerun_note(target):
|
|
254
|
+
holder = _resolve_license_holder(license_choice)
|
|
255
|
+
return _build_project(target, kind, license_choice, holder)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _build_project(target: Path, kind: Kind, license_choice: License, holder: str) -> list[str]:
|
|
259
|
+
target.mkdir(exist_ok=True)
|
|
260
|
+
git_init, uv_init, add_deps, stage_files = _local_steps(kind)
|
|
261
|
+
step(git_init.name, target, *git_init.command)
|
|
262
|
+
step(uv_init.name, target, *uv_init.command)
|
|
263
|
+
_add_uv_workspace(target)
|
|
264
|
+
step(add_deps.name, target, *add_deps.command)
|
|
265
|
+
_write_files(target, kind, license_choice, holder)
|
|
266
|
+
step(stage_files.name, target, *stage_files.command)
|
|
267
|
+
listed = step("list files", target, "git", "ls-files")
|
|
268
|
+
return sorted(listed.splitlines())
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def commit_and_push_to_github(target: Path, public: bool) -> str:
|
|
272
|
+
"""Commit the project in ``target``, create its GitHub repo, push and return the repo's URL."""
|
|
273
|
+
commit_step, repo_step = _github_steps(target.name, public)
|
|
274
|
+
with _rerun_note(target):
|
|
275
|
+
step(commit_step.name, target, *commit_step.command)
|
|
276
|
+
kept = f"The project at {target} is kept; run the fix from inside it."
|
|
277
|
+
try:
|
|
278
|
+
stdout = step(repo_step.name, target, *repo_step.command)
|
|
279
|
+
except FileNotFoundError as exc:
|
|
280
|
+
raise FileNotFoundError(f"{exc}. The project at {target} is kept.") from exc
|
|
281
|
+
except StepFailed as exc:
|
|
282
|
+
# gh adds the new repo as origin before it pushes. Once origin is there,
|
|
283
|
+
# rerunning gh repo create fails on the taken name; only the push is left.
|
|
284
|
+
has_origin = run("git", "remote", "get-url", "origin", cwd=target).returncode == 0
|
|
285
|
+
fix = (
|
|
286
|
+
f"git push --set-upstream origin {BRANCH}"
|
|
287
|
+
if has_origin
|
|
288
|
+
else " ".join(repo_step.command)
|
|
289
|
+
)
|
|
290
|
+
raise StepFailed(exc.step, f"{exc.detail}\n{kept}".lstrip("\n"), fix) from exc
|
|
291
|
+
# Without a terminal, gh prints the new repo's URL on stdout.
|
|
292
|
+
url = _GITHUB_URL.search(stdout)
|
|
293
|
+
if url:
|
|
294
|
+
return url.group(0)
|
|
295
|
+
view = ["repo", "view", "--json", "url", "--jq", ".url"]
|
|
296
|
+
fix = " ".join(["gh", *view])
|
|
297
|
+
return step("read GitHub repo URL", target, "gh", *view, fix=fix).strip()
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def step(step_name: str, cwd: Path, tool: str, *args: str, fix: str | None = None) -> str:
|
|
301
|
+
log.debug("Step: %s", step_name)
|
|
302
|
+
result = run(tool, *args, cwd=cwd)
|
|
303
|
+
if result.returncode != 0:
|
|
304
|
+
raise StepFailed(step_name, (result.stderr or result.stdout).strip(), fix)
|
|
305
|
+
return result.stdout
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
@contextlib.contextmanager
|
|
309
|
+
def file_step(step_name: str) -> Generator[None]:
|
|
310
|
+
"""Report a file read or write that fails as the failure of ``step_name``."""
|
|
311
|
+
try:
|
|
312
|
+
yield
|
|
313
|
+
except OSError as exc:
|
|
314
|
+
raise StepFailed(step_name, str(exc)) from exc
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _add_uv_workspace(target: Path) -> None:
|
|
318
|
+
pyproject = target / PYPROJECT
|
|
319
|
+
with file_step("add uv workspace"):
|
|
320
|
+
text = pyproject.read_text(encoding="utf-8")
|
|
321
|
+
write(pyproject, text.rstrip("\n") + "\n\n" + render("pyproject.toml.tmpl"))
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _resolve_license_holder(license_choice: License) -> str:
|
|
325
|
+
if license_choice is not License.MIT:
|
|
326
|
+
return ""
|
|
327
|
+
holder = machine_config("user.name")
|
|
328
|
+
# Nothing else stops a blank holder: git can make up an author for a commit.
|
|
329
|
+
if not holder:
|
|
330
|
+
detail = "the LICENSE needs a holder, but git's user.name is not set"
|
|
331
|
+
raise StepFailed(WRITE_FILES_STEP, detail, 'git config --global user.name "Your Name"')
|
|
332
|
+
return holder
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _render_outputs(
|
|
336
|
+
name: str, package: str, kind: Kind, license_choice: License, holder: str
|
|
337
|
+
) -> dict[str, str]:
|
|
338
|
+
values = {
|
|
339
|
+
"name": name,
|
|
340
|
+
"package": package,
|
|
341
|
+
"year": str(datetime.date.today().year),
|
|
342
|
+
"holder": holder,
|
|
343
|
+
}
|
|
344
|
+
package_template, test_template = _KIND_TEMPLATES[kind]
|
|
345
|
+
templates = {
|
|
346
|
+
f"src/{package}/__init__.py": package_template,
|
|
347
|
+
f"tests/test_{package}.py": test_template,
|
|
348
|
+
"AGENTS.md": "AGENTS.md.tmpl",
|
|
349
|
+
"CLAUDE.md": "CLAUDE.md.tmpl",
|
|
350
|
+
"README.md": "README.md.tmpl",
|
|
351
|
+
".gitignore": "gitignore.tmpl",
|
|
352
|
+
CI_WORKFLOW: CI_TEMPLATE,
|
|
353
|
+
}
|
|
354
|
+
if license_choice is License.MIT:
|
|
355
|
+
templates["LICENSE"] = "LICENSE.tmpl"
|
|
356
|
+
return {path: render(template, **values) for path, template in templates.items()}
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _write_files(target: Path, kind: Kind, license_choice: License, holder: str) -> None:
|
|
360
|
+
package = _package_name(target)
|
|
361
|
+
rendered = _render_outputs(target.name, package, kind, license_choice, holder)
|
|
362
|
+
with file_step(WRITE_FILES_STEP):
|
|
363
|
+
for path, text in rendered.items():
|
|
364
|
+
write(target / path, text)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _package_name(target: Path) -> str:
|
|
368
|
+
"""The import name uv init chose: the one package folder under ``src``."""
|
|
369
|
+
packages = [path.name for path in (target / "src").iterdir() if path.is_dir()]
|
|
370
|
+
if len(packages) != 1:
|
|
371
|
+
raise StepFailed(WRITE_FILES_STEP, f"expected one package under src, found {packages}")
|
|
372
|
+
return packages[0]
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def render(template: str, **values: str) -> str:
|
|
376
|
+
"""Fill ``{{key}}`` placeholders. A placeholder without a value is a bug, so it raises."""
|
|
377
|
+
text = (files("aa_cli") / "templates" / template).read_text(encoding="utf-8")
|
|
378
|
+
return _PLACEHOLDER.sub(lambda match: values[match.group(1)], text)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def write(path: Path, text: str) -> None:
|
|
382
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
383
|
+
path.write_text(text, encoding="utf-8", newline="\n")
|
aa_cli/output.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""The output contract every aa command follows.
|
|
2
|
+
|
|
3
|
+
Human mode writes readable text. JSON mode writes exactly one envelope on
|
|
4
|
+
stdout: ``{"ok": true, "data": ...}`` on success and
|
|
5
|
+
``{"ok": false, "error": {"code", "message", "fix"}}`` on failure.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__lazy_modules__ = {"json"}
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
import sys
|
|
13
|
+
from collections.abc import Mapping, Sequence
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from enum import IntEnum
|
|
16
|
+
from typing import Annotated, Any, Self, TextIO
|
|
17
|
+
|
|
18
|
+
import typer
|
|
19
|
+
|
|
20
|
+
JsonFlag = Annotated[
|
|
21
|
+
bool, typer.Option("--json", help="Print one JSON object on stdout. Same as AA_JSON=1.")
|
|
22
|
+
]
|
|
23
|
+
VerboseFlag = Annotated[bool, typer.Option("--verbose", help="Log debug details to stderr.")]
|
|
24
|
+
"""Every command declares both flags, so they work before or after the subcommand."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ExitCode(IntEnum):
|
|
28
|
+
meaning: str
|
|
29
|
+
|
|
30
|
+
def __new__(cls, value: int, meaning: str) -> Self:
|
|
31
|
+
member = int.__new__(cls, value)
|
|
32
|
+
member._value_ = value
|
|
33
|
+
member.meaning = meaning
|
|
34
|
+
return member
|
|
35
|
+
|
|
36
|
+
OK = (0, "ok")
|
|
37
|
+
PROBLEMS = (1, "problems found")
|
|
38
|
+
USAGE = (2, "usage error")
|
|
39
|
+
UNEXPECTED = (3, "unexpected error")
|
|
40
|
+
ABORTED = (130, "stopped with Ctrl+C") # the shell convention for a command stopped by Ctrl+C
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Aborted(Exception):
|
|
44
|
+
"""The user stopped aa with Ctrl+C. The message says what was left behind."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, message: str = "Aborted") -> None:
|
|
47
|
+
super().__init__(message)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Output:
|
|
52
|
+
json: bool
|
|
53
|
+
verbose: bool
|
|
54
|
+
help: bool = False
|
|
55
|
+
# The stdout aa started with. Envelopes always go here, so capturing help
|
|
56
|
+
# text never captures an envelope too.
|
|
57
|
+
stdout: TextIO = field(default_factory=lambda: sys.stdout, repr=False, compare=False)
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def from_args(cls, args: Sequence[str], environ: Mapping[str, str]) -> Output:
|
|
61
|
+
"""Read the global flags straight from the raw arguments.
|
|
62
|
+
|
|
63
|
+
The flags are accepted before or after a subcommand, and they must
|
|
64
|
+
still apply when parsing fails, so they are read before the parser runs.
|
|
65
|
+
"""
|
|
66
|
+
flags = list(args)
|
|
67
|
+
if "--" in flags:
|
|
68
|
+
flags = flags[: flags.index("--")]
|
|
69
|
+
return cls(
|
|
70
|
+
json="--json" in flags or environ.get("AA_JSON") == "1",
|
|
71
|
+
verbose="--verbose" in flags,
|
|
72
|
+
help="--help" in flags,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def success(self, data: dict[str, Any], human: str) -> None:
|
|
76
|
+
if self.json:
|
|
77
|
+
self._write_json({"ok": True, "data": data})
|
|
78
|
+
else:
|
|
79
|
+
typer.echo(human)
|
|
80
|
+
|
|
81
|
+
def failure(self, code: str, message: str, fix: str | None = None) -> None:
|
|
82
|
+
if self.json:
|
|
83
|
+
self._write_json({"ok": False, "error": {"code": code, "message": message, "fix": fix}})
|
|
84
|
+
else:
|
|
85
|
+
typer.echo(f"Error: {message}", err=True)
|
|
86
|
+
if fix:
|
|
87
|
+
typer.echo(f"Fix: {fix}", err=True)
|
|
88
|
+
|
|
89
|
+
def _write_json(self, envelope: dict[str, Any]) -> None:
|
|
90
|
+
typer.echo(json.dumps(envelope), file=self.stdout)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def configure_logging(verbose: bool) -> None:
|
|
94
|
+
"""Send aa's logs to stderr: debug with --verbose, warnings otherwise."""
|
|
95
|
+
logger = logging.getLogger("aa")
|
|
96
|
+
logger.handlers.clear()
|
|
97
|
+
handler = logging.StreamHandler(sys.stderr)
|
|
98
|
+
handler.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))
|
|
99
|
+
logger.addHandler(handler)
|
|
100
|
+
logger.setLevel(logging.DEBUG if verbose else logging.WARNING)
|
|
101
|
+
logger.propagate = False
|
aa_cli/process.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Running the external tools aa wraps (uv, git, gh)."""
|
|
2
|
+
|
|
3
|
+
__lazy_modules__ = {"shutil", "subprocess"}
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
log = logging.getLogger("aa")
|
|
12
|
+
|
|
13
|
+
# Git sets these while it runs a hook, for example. They point at that repo, so a tool
|
|
14
|
+
# aa runs would change it instead of the project in the folder aa asked for.
|
|
15
|
+
_REPO_VARIABLES = {
|
|
16
|
+
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
|
17
|
+
"GIT_COMMON_DIR",
|
|
18
|
+
"GIT_DIR",
|
|
19
|
+
"GIT_INDEX_FILE",
|
|
20
|
+
"GIT_OBJECT_DIRECTORY",
|
|
21
|
+
"GIT_WORK_TREE",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def run(tool: str, *args: str, cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
|
|
26
|
+
"""Run a tool found on PATH, capture its output and log the command and exit code."""
|
|
27
|
+
command_line = " ".join([tool, *args])
|
|
28
|
+
executable = shutil.which(tool)
|
|
29
|
+
if executable is None:
|
|
30
|
+
raise FileNotFoundError(f"{tool} not found on PATH")
|
|
31
|
+
log.debug("Running %s (%s)", command_line, executable)
|
|
32
|
+
result = subprocess.run( # noqa: S603 # argument list, no shell, full tool path
|
|
33
|
+
[executable, *args],
|
|
34
|
+
cwd=cwd,
|
|
35
|
+
env={key: value for key, value in os.environ.items() if key not in _REPO_VARIABLES},
|
|
36
|
+
capture_output=True,
|
|
37
|
+
text=True,
|
|
38
|
+
encoding="utf-8",
|
|
39
|
+
errors="replace",
|
|
40
|
+
)
|
|
41
|
+
log.debug("%s: exit %d", command_line, result.returncode)
|
|
42
|
+
return result
|