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/commands.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""``aa commands``: machine-readable and human description of aa commands."""
|
|
2
|
+
|
|
3
|
+
__lazy_modules__ = {
|
|
4
|
+
"inspect",
|
|
5
|
+
"typer.core",
|
|
6
|
+
"types",
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
import inspect
|
|
10
|
+
import types
|
|
11
|
+
from collections.abc import Callable, Iterator, Mapping, Sequence
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from enum import StrEnum
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, Union, get_args, get_origin, get_type_hints
|
|
16
|
+
|
|
17
|
+
import typer
|
|
18
|
+
from typer.core import TyperArgument, TyperCommand, TyperGroup, TyperOption
|
|
19
|
+
|
|
20
|
+
from aa_cli.choices import Effect
|
|
21
|
+
from aa_cli.output import ExitCode
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class _TypeInfo:
|
|
26
|
+
kind: str
|
|
27
|
+
allows_none: bool = False
|
|
28
|
+
items: str | None = None
|
|
29
|
+
choices: list[str] | None = None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_SCALAR_TYPES: dict[object, str] = {
|
|
33
|
+
bool: "boolean",
|
|
34
|
+
int: "integer",
|
|
35
|
+
float: "number",
|
|
36
|
+
str: "string",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _scalar_kind(annotation: object) -> tuple[str, list[str] | None]:
|
|
41
|
+
if annotation in _SCALAR_TYPES:
|
|
42
|
+
return _SCALAR_TYPES[annotation], None
|
|
43
|
+
if isinstance(annotation, type):
|
|
44
|
+
if issubclass(annotation, StrEnum):
|
|
45
|
+
return "string", [str(member.value) for member in annotation]
|
|
46
|
+
if issubclass(annotation, Path):
|
|
47
|
+
return "string", None
|
|
48
|
+
raise TypeError(f"Unsupported parameter type annotation: {annotation!r}")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _resolve_type(annotation: object) -> _TypeInfo:
|
|
52
|
+
origin = get_origin(annotation)
|
|
53
|
+
allows_none = False
|
|
54
|
+
target = annotation
|
|
55
|
+
if origin in (types.UnionType, Union):
|
|
56
|
+
args = get_args(annotation)
|
|
57
|
+
non_none = [arg for arg in args if arg is not type(None)]
|
|
58
|
+
allows_none = len(non_none) < len(args)
|
|
59
|
+
if len(non_none) != 1:
|
|
60
|
+
raise TypeError(f"Unsupported union type annotation: {annotation!r}")
|
|
61
|
+
target = non_none[0]
|
|
62
|
+
origin = get_origin(target)
|
|
63
|
+
if origin is list:
|
|
64
|
+
item_args = get_args(target)
|
|
65
|
+
item_kind, _ = _scalar_kind(item_args[0] if item_args else str)
|
|
66
|
+
return _TypeInfo(kind="array", allows_none=allows_none, items=item_kind)
|
|
67
|
+
kind, choices = _scalar_kind(target)
|
|
68
|
+
return _TypeInfo(kind=kind, allows_none=allows_none, choices=choices)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _callback_info(
|
|
72
|
+
callback: Callable[..., object] | None,
|
|
73
|
+
) -> tuple[dict[str, Any], inspect.Signature]:
|
|
74
|
+
if callback is None:
|
|
75
|
+
return {}, inspect.Signature()
|
|
76
|
+
return get_type_hints(callback), inspect.signature(callback)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _param_details(
|
|
80
|
+
param_name: str,
|
|
81
|
+
required_by_parser: bool,
|
|
82
|
+
hints: Mapping[str, Any],
|
|
83
|
+
sig: inspect.Signature,
|
|
84
|
+
) -> tuple[_TypeInfo, bool, Any]:
|
|
85
|
+
if param_name not in hints:
|
|
86
|
+
raise TypeError(f"Missing type hint for parameter {param_name!r}")
|
|
87
|
+
type_info = _resolve_type(hints[param_name])
|
|
88
|
+
sig_param = sig.parameters[param_name]
|
|
89
|
+
default = None if sig_param.default is inspect.Parameter.empty else sig_param.default
|
|
90
|
+
if isinstance(default, StrEnum):
|
|
91
|
+
default = str(default.value)
|
|
92
|
+
required = (
|
|
93
|
+
bool(required_by_parser)
|
|
94
|
+
and not type_info.allows_none
|
|
95
|
+
and sig_param.default is inspect.Parameter.empty
|
|
96
|
+
)
|
|
97
|
+
return type_info, required, default
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _describe_argument(
|
|
101
|
+
param: TyperArgument, hints: Mapping[str, Any], sig: inspect.Signature
|
|
102
|
+
) -> dict[str, Any]:
|
|
103
|
+
param_name = param.name or ""
|
|
104
|
+
type_info, required, _ = _param_details(param_name, bool(param.required), hints, sig)
|
|
105
|
+
entry: dict[str, Any] = {
|
|
106
|
+
"name": param.metavar or param_name.upper(),
|
|
107
|
+
"type": type_info.kind,
|
|
108
|
+
"required": required,
|
|
109
|
+
"help": param.help or "",
|
|
110
|
+
}
|
|
111
|
+
if type_info.items is not None:
|
|
112
|
+
entry["items"] = type_info.items
|
|
113
|
+
if type_info.choices is not None:
|
|
114
|
+
entry["choices"] = type_info.choices
|
|
115
|
+
return entry
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _describe_option(
|
|
119
|
+
param: TyperOption, hints: Mapping[str, Any], sig: inspect.Signature
|
|
120
|
+
) -> dict[str, Any]:
|
|
121
|
+
param_name = param.name or ""
|
|
122
|
+
type_info, required, default = _param_details(param_name, bool(param.required), hints, sig)
|
|
123
|
+
entry: dict[str, Any] = {
|
|
124
|
+
"flag": param.opts[0],
|
|
125
|
+
"type": type_info.kind,
|
|
126
|
+
}
|
|
127
|
+
if type_info.items is not None:
|
|
128
|
+
entry["items"] = type_info.items
|
|
129
|
+
entry.update(
|
|
130
|
+
{
|
|
131
|
+
"default": default,
|
|
132
|
+
"choices": type_info.choices,
|
|
133
|
+
"required": required,
|
|
134
|
+
"repeatable": bool(param.multiple),
|
|
135
|
+
"help": param.help or "",
|
|
136
|
+
}
|
|
137
|
+
)
|
|
138
|
+
return entry
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _visible_commands(group: TyperGroup, prefix: str = "") -> Iterator[tuple[str, TyperCommand]]:
|
|
142
|
+
"""Each visible command by its full name; a group gives its commands, not itself."""
|
|
143
|
+
for name, cmd in group.commands.items():
|
|
144
|
+
if cmd.hidden:
|
|
145
|
+
continue
|
|
146
|
+
full_name = f"{prefix}{name}"
|
|
147
|
+
if isinstance(cmd, TyperGroup):
|
|
148
|
+
yield from _visible_commands(cmd, f"{full_name} ")
|
|
149
|
+
elif isinstance(cmd, TyperCommand):
|
|
150
|
+
yield full_name, cmd
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _describe_command(
|
|
154
|
+
name: str, cmd: TyperCommand, effects: Mapping[str, Effect], global_flags: set[str]
|
|
155
|
+
) -> dict[str, Any]:
|
|
156
|
+
if name not in effects:
|
|
157
|
+
raise KeyError(f"Missing effect declaration for command {name!r}")
|
|
158
|
+
cmd_hints, cmd_sig = _callback_info(cmd.callback)
|
|
159
|
+
arguments = [
|
|
160
|
+
_describe_argument(param, cmd_hints, cmd_sig)
|
|
161
|
+
for param in cmd.params
|
|
162
|
+
if isinstance(param, TyperArgument)
|
|
163
|
+
]
|
|
164
|
+
options = [
|
|
165
|
+
_describe_option(param, cmd_hints, cmd_sig)
|
|
166
|
+
for param in cmd.params
|
|
167
|
+
if isinstance(param, TyperOption) and not param.hidden and param.opts[0] not in global_flags
|
|
168
|
+
]
|
|
169
|
+
summary = cmd.help.splitlines()[0] if cmd.help else ""
|
|
170
|
+
return {
|
|
171
|
+
"name": name,
|
|
172
|
+
"summary": summary,
|
|
173
|
+
"effect": str(effects[name]),
|
|
174
|
+
"arguments": arguments,
|
|
175
|
+
"options": options,
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def describe_cli(app: typer.Typer, effects: Mapping[str, Effect]) -> dict[str, Any]:
|
|
180
|
+
"""Return the exit codes, global flags and visible commands of ``app``."""
|
|
181
|
+
group = typer.main.get_command(app)
|
|
182
|
+
if not isinstance(group, TyperGroup):
|
|
183
|
+
raise TypeError(f"Expected root TyperGroup, got {type(group).__name__}")
|
|
184
|
+
root_hints, root_sig = _callback_info(group.callback)
|
|
185
|
+
global_options = [
|
|
186
|
+
_describe_option(param, root_hints, root_sig)
|
|
187
|
+
for param in group.params
|
|
188
|
+
if isinstance(param, TyperOption) and not param.hidden
|
|
189
|
+
]
|
|
190
|
+
global_flags = {opt["flag"] for opt in global_options}
|
|
191
|
+
commands = [
|
|
192
|
+
_describe_command(full_name, cmd, effects, global_flags)
|
|
193
|
+
for full_name, cmd in _visible_commands(group)
|
|
194
|
+
]
|
|
195
|
+
return {
|
|
196
|
+
"exit_codes": [{"code": int(code), "meaning": code.meaning} for code in ExitCode],
|
|
197
|
+
"global_options": global_options,
|
|
198
|
+
"commands": commands,
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def format_commands(commands: Sequence[Mapping[str, Any]]) -> str:
|
|
203
|
+
"""Format visible commands and their summaries as a human-readable list."""
|
|
204
|
+
if not commands:
|
|
205
|
+
return ""
|
|
206
|
+
width = max(len(str(cmd["name"])) for cmd in commands)
|
|
207
|
+
return "\n".join(f"{cmd['name']:<{width}} {cmd['summary']}" for cmd in commands)
|
aa_cli/crash.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Crash reports: the cleaned Markdown file an app saves when it fails with an unexpected error.
|
|
2
|
+
|
|
3
|
+
This module uses only the standard library. It never imports the redaction library, Typer or the
|
|
4
|
+
rest of ``aa_cli`` (an import-linter rule checks it), so it can move into the CLIs ``aa init``
|
|
5
|
+
creates, or into a library of its own, unchanged. The caller passes the cleaning step as a plain
|
|
6
|
+
function, like the log library's ``redact=`` (ADR 0005).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
__lazy_modules__ = {
|
|
10
|
+
"contextlib",
|
|
11
|
+
"datetime",
|
|
12
|
+
"platform",
|
|
13
|
+
"traceback",
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
import contextlib
|
|
17
|
+
import os
|
|
18
|
+
import platform
|
|
19
|
+
import re
|
|
20
|
+
import traceback
|
|
21
|
+
from collections.abc import Callable, Mapping
|
|
22
|
+
from datetime import datetime
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
REVIEW_LINE = (
|
|
26
|
+
"Review this before you post it."
|
|
27
|
+
" Sensitive values were replaced, but no tool catches everything."
|
|
28
|
+
)
|
|
29
|
+
REDACTION_FAILED = "[REDACTION FAILED]"
|
|
30
|
+
KEEP_REPORTS = 10
|
|
31
|
+
|
|
32
|
+
_SLASHES = r"[\\/]+"
|
|
33
|
+
_REPORT_NAME = re.compile(r"^(\d{4}-\d{2}-\d{2}-\d{6})(?:-(\d+))?\.md$")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def crash_folder(app: str, environ: Mapping[str, str] = os.environ) -> Path:
|
|
37
|
+
"""``%LOCALAPPDATA%\\<app>\\crash``, or ``AppData\\Local`` under the home folder without it.
|
|
38
|
+
|
|
39
|
+
A relative LOCALAPPDATA is ignored too, so a report never lands in the current folder.
|
|
40
|
+
"""
|
|
41
|
+
local = Path(environ.get("LOCALAPPDATA") or "")
|
|
42
|
+
if not local.is_absolute():
|
|
43
|
+
local = Path.home() / "AppData" / "Local"
|
|
44
|
+
return local / app / "crash"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def save_report(
|
|
48
|
+
exc: BaseException,
|
|
49
|
+
*,
|
|
50
|
+
folder: Path,
|
|
51
|
+
app: str,
|
|
52
|
+
version: str,
|
|
53
|
+
command: str | None,
|
|
54
|
+
message: str,
|
|
55
|
+
redact: Callable[[str], str],
|
|
56
|
+
now: datetime | None = None,
|
|
57
|
+
) -> Path:
|
|
58
|
+
"""Write a Crash report for ``exc`` into ``folder`` and return its path.
|
|
59
|
+
|
|
60
|
+
``command`` is the subcommand's name only, never its arguments. ``message`` and the
|
|
61
|
+
traceback go through ``redact`` each on its own, after the home folder and computer name
|
|
62
|
+
are replaced. Only the newest ``KEEP_REPORTS`` reports stay.
|
|
63
|
+
"""
|
|
64
|
+
hide = _home_and_computer()
|
|
65
|
+
details = traceback.format_exception(exc)
|
|
66
|
+
lines = [
|
|
67
|
+
f"# {app} crash report",
|
|
68
|
+
REVIEW_LINE,
|
|
69
|
+
"",
|
|
70
|
+
f"{app} {version} · Python {platform.python_version()} · "
|
|
71
|
+
f"{platform.system()} {platform.version()}",
|
|
72
|
+
f"Command: {app} {command}" if command else f"Command: {app}",
|
|
73
|
+
f"Error: {_clean(message, hide, redact)}",
|
|
74
|
+
"",
|
|
75
|
+
"```",
|
|
76
|
+
_clean("".join(details).rstrip("\n"), hide, redact),
|
|
77
|
+
"```",
|
|
78
|
+
"",
|
|
79
|
+
]
|
|
80
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
81
|
+
path = _write_new(folder, (now or datetime.now()).strftime("%Y-%m-%d-%H%M%S"), "\n".join(lines))
|
|
82
|
+
_keep_newest(folder, path)
|
|
83
|
+
return path
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _home_and_computer() -> Callable[[str], str]:
|
|
87
|
+
"""Replace the home folder path with ``[HOME]`` and the computer name with ``[COMPUTER]``.
|
|
88
|
+
|
|
89
|
+
Both match any letter case, and the home path matches with either slash. The whole home
|
|
90
|
+
path is replaced, never the bare user name, which would break ordinary words if short.
|
|
91
|
+
"""
|
|
92
|
+
home_path = str(Path.home())
|
|
93
|
+
parts = [re.escape(part) for part in re.split(_SLASHES, home_path) if part]
|
|
94
|
+
lead = _SLASHES if home_path[:1] in ("\\", "/") else ""
|
|
95
|
+
home = re.compile(lead + _SLASHES.join(parts) + r"(?![\w-])", re.IGNORECASE) if parts else None
|
|
96
|
+
names = {name for name in (os.environ.get("COMPUTERNAME"), platform.node()) if name}
|
|
97
|
+
computer = (
|
|
98
|
+
re.compile(
|
|
99
|
+
r"(?<![\w-])(?:"
|
|
100
|
+
+ "|".join(map(re.escape, sorted(names, key=len, reverse=True)))
|
|
101
|
+
+ r")(?![\w-])",
|
|
102
|
+
re.IGNORECASE,
|
|
103
|
+
)
|
|
104
|
+
if names
|
|
105
|
+
else None
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
def hide(text: str) -> str:
|
|
109
|
+
if home is not None:
|
|
110
|
+
text = home.sub("[HOME]", text)
|
|
111
|
+
if computer is not None:
|
|
112
|
+
text = computer.sub("[COMPUTER]", text)
|
|
113
|
+
return text
|
|
114
|
+
|
|
115
|
+
return hide
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _clean(text: str, hide: Callable[[str], str], redact: Callable[[str], str]) -> str:
|
|
119
|
+
try:
|
|
120
|
+
cleaned = redact(hide(text))
|
|
121
|
+
except Exception:
|
|
122
|
+
return REDACTION_FAILED
|
|
123
|
+
return cleaned if isinstance(cleaned, str) else REDACTION_FAILED
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _write_new(folder: Path, stamp: str, text: str) -> Path:
|
|
127
|
+
"""Write ``text`` to a new file named by ``stamp``, adding -2, -3 and so on after the last one.
|
|
128
|
+
|
|
129
|
+
Text that isn't valid Unicode, such as a file name read with surrogate escapes, is written
|
|
130
|
+
with backslash escapes. A file that fails partway is removed.
|
|
131
|
+
"""
|
|
132
|
+
for count in range(_next_count(folder, stamp), 1000):
|
|
133
|
+
path = folder / (f"{stamp}.md" if count == 1 else f"{stamp}-{count}.md")
|
|
134
|
+
try:
|
|
135
|
+
file = path.open("x", encoding="utf-8", errors="backslashreplace")
|
|
136
|
+
except FileExistsError:
|
|
137
|
+
continue
|
|
138
|
+
try:
|
|
139
|
+
with file:
|
|
140
|
+
file.write(text)
|
|
141
|
+
except BaseException:
|
|
142
|
+
path.unlink(missing_ok=True)
|
|
143
|
+
raise
|
|
144
|
+
return path
|
|
145
|
+
raise FileExistsError(f"too many crash reports named {stamp}")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _reports(folder: Path) -> list[tuple[str, int, Path]]:
|
|
149
|
+
"""Every Crash report in ``folder`` as (stamp, count, path), oldest first."""
|
|
150
|
+
reports: list[tuple[str, int, Path]] = []
|
|
151
|
+
for path in folder.iterdir():
|
|
152
|
+
match = _REPORT_NAME.match(path.name)
|
|
153
|
+
if match and path.is_file():
|
|
154
|
+
reports.append((match[1], int(match[2] or 1), path))
|
|
155
|
+
return sorted(reports)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _next_count(folder: Path, stamp: str) -> int:
|
|
159
|
+
try:
|
|
160
|
+
counts = [count for name, count, _ in _reports(folder) if name == stamp]
|
|
161
|
+
except OSError:
|
|
162
|
+
return 1
|
|
163
|
+
return max(counts, default=0) + 1
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _keep_newest(folder: Path, saved: Path) -> None:
|
|
167
|
+
"""Remove all but the newest ``KEEP_REPORTS``, never ``saved``, and never fail."""
|
|
168
|
+
try:
|
|
169
|
+
others = [path for *_, path in _reports(folder) if path != saved]
|
|
170
|
+
except OSError:
|
|
171
|
+
return
|
|
172
|
+
for path in others[: max(len(others) - (KEEP_REPORTS - 1), 0)]:
|
|
173
|
+
# An old report that can't be removed is left behind.
|
|
174
|
+
with contextlib.suppress(OSError):
|
|
175
|
+
path.unlink()
|
aa_cli/git.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Reading git's own configuration."""
|
|
2
|
+
|
|
3
|
+
__lazy_modules__ = {"aa_cli.process"}
|
|
4
|
+
|
|
5
|
+
from aa_cli.process import run
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def machine_config(key: str) -> str:
|
|
9
|
+
"""The value of ``key`` for the machine, ignoring the current repo's own config.
|
|
10
|
+
|
|
11
|
+
A new project only sees machine-wide config, so a name set in the repo
|
|
12
|
+
aa happens to run in must not count.
|
|
13
|
+
"""
|
|
14
|
+
scoped = run("git", "config", "--get-all", "--show-scope", key)
|
|
15
|
+
if scoped.returncode not in (0, 1):
|
|
16
|
+
# Git before 2.26 has no --show-scope (exit 1 only means "not set").
|
|
17
|
+
# Read the value as git would use it, repo config included.
|
|
18
|
+
return run("git", "config", "--get", key).stdout.strip()
|
|
19
|
+
values = [
|
|
20
|
+
value
|
|
21
|
+
for scope, _, value in (line.partition("\t") for line in scoped.stdout.splitlines())
|
|
22
|
+
if scope not in ("local", "worktree")
|
|
23
|
+
]
|
|
24
|
+
return values[-1].strip() if values else ""
|