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/cli.py
ADDED
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
"""The aa command."""
|
|
2
|
+
|
|
3
|
+
__lazy_modules__ = {
|
|
4
|
+
"aa_cli.add",
|
|
5
|
+
"aa_cli.commands",
|
|
6
|
+
"aa_cli.crash",
|
|
7
|
+
"aa_cli.init",
|
|
8
|
+
"aa_cli.redact",
|
|
9
|
+
"aa_cli.secret",
|
|
10
|
+
"aa_settings",
|
|
11
|
+
"io",
|
|
12
|
+
"shlex",
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
import contextlib
|
|
16
|
+
import io
|
|
17
|
+
import logging
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import shlex
|
|
21
|
+
import sys
|
|
22
|
+
from collections.abc import Callable, Generator, Sequence
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Annotated, Any
|
|
25
|
+
|
|
26
|
+
import typer
|
|
27
|
+
from typer.core import TyperGroup
|
|
28
|
+
|
|
29
|
+
from aa_cli.add import AddError, add_piece
|
|
30
|
+
from aa_cli.choices import WITH_KINDS, WITHOUT_KINDS, Effect, License, Piece
|
|
31
|
+
from aa_cli.commands import describe_cli, format_commands
|
|
32
|
+
from aa_cli.crash import REDACTION_FAILED, crash_folder, save_report
|
|
33
|
+
from aa_cli.init import (
|
|
34
|
+
NAME_RULE,
|
|
35
|
+
Kind,
|
|
36
|
+
StepFailed,
|
|
37
|
+
commit_and_push_to_github,
|
|
38
|
+
create_project,
|
|
39
|
+
is_empty_folder_or_missing,
|
|
40
|
+
is_valid_name,
|
|
41
|
+
outer_workspace_taking_in,
|
|
42
|
+
plan_project,
|
|
43
|
+
)
|
|
44
|
+
from aa_cli.output import (
|
|
45
|
+
Aborted,
|
|
46
|
+
ExitCode,
|
|
47
|
+
JsonFlag,
|
|
48
|
+
Output,
|
|
49
|
+
VerboseFlag,
|
|
50
|
+
configure_logging,
|
|
51
|
+
)
|
|
52
|
+
from aa_cli.redact import (
|
|
53
|
+
FileError,
|
|
54
|
+
UnknownKind,
|
|
55
|
+
build_redactor,
|
|
56
|
+
check_file,
|
|
57
|
+
clean_text,
|
|
58
|
+
find_all,
|
|
59
|
+
redact_file,
|
|
60
|
+
)
|
|
61
|
+
from aa_cli.secret import NotUtf8, field_name, project_name, read_piped_value
|
|
62
|
+
from aa_settings import SecretStoreError, delete_secret, save_secret
|
|
63
|
+
|
|
64
|
+
log = logging.getLogger("aa")
|
|
65
|
+
|
|
66
|
+
# ANSI escape sequences: CSI (colors, styles) and OSC (hyperlinks).
|
|
67
|
+
_TERMINAL_ESCAPE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class AaGroup(TyperGroup):
|
|
71
|
+
"""Root group that applies the output contract to every invocation."""
|
|
72
|
+
|
|
73
|
+
def main(
|
|
74
|
+
self,
|
|
75
|
+
args: Sequence[str] | None = None,
|
|
76
|
+
prog_name: str | None = None,
|
|
77
|
+
complete_var: str | None = None,
|
|
78
|
+
standalone_mode: bool = True,
|
|
79
|
+
windows_expand_args: bool = True,
|
|
80
|
+
**extra: Any, # noqa: ANN401 # mirrors TyperGroup.main
|
|
81
|
+
) -> Any: # noqa: ANN401 # mirrors TyperGroup.main
|
|
82
|
+
raw_args = sys.argv[1:] if args is None else list(args)
|
|
83
|
+
out = Output.from_args(raw_args, os.environ)
|
|
84
|
+
command = self._command_name(raw_args)
|
|
85
|
+
configure_logging(out.verbose)
|
|
86
|
+
if log.isEnabledFor(logging.DEBUG):
|
|
87
|
+
log.debug("aa %s on Python %s", _package_version(), sys.version.split()[0])
|
|
88
|
+
try:
|
|
89
|
+
with _help_as_envelope(out):
|
|
90
|
+
code = super().main(
|
|
91
|
+
args,
|
|
92
|
+
prog_name,
|
|
93
|
+
complete_var,
|
|
94
|
+
standalone_mode=False,
|
|
95
|
+
windows_expand_args=windows_expand_args,
|
|
96
|
+
obj=out,
|
|
97
|
+
**extra,
|
|
98
|
+
)
|
|
99
|
+
except typer.TyperException as exc:
|
|
100
|
+
# Typer gives every usage error (bad flag, missing argument) exit code 2.
|
|
101
|
+
if exc.exit_code != ExitCode.USAGE:
|
|
102
|
+
code = _report_unexpected_error(out, exc, command)
|
|
103
|
+
else:
|
|
104
|
+
code = _report_usage_error(out, exc)
|
|
105
|
+
except Aborted as exc:
|
|
106
|
+
code = _report_aborted(out, exc)
|
|
107
|
+
except Exception as exc:
|
|
108
|
+
code = _report_unexpected_error(out, exc, command)
|
|
109
|
+
sys.exit(code if isinstance(code, int) else ExitCode.OK)
|
|
110
|
+
|
|
111
|
+
def _command_name(self, args: Sequence[str]) -> str | None:
|
|
112
|
+
"""The subcommand's name, never its arguments, for a Crash report.
|
|
113
|
+
|
|
114
|
+
The root takes only flags, so the first word that isn't a flag names the subcommand.
|
|
115
|
+
Anything that isn't a known command name gives None.
|
|
116
|
+
"""
|
|
117
|
+
first = next((arg for arg in args if not arg.startswith("-")), None)
|
|
118
|
+
return first if first in self.commands else None
|
|
119
|
+
|
|
120
|
+
# TyperGroup.invoke takes a Context type that Typer doesn't export; typer.Context subclasses it.
|
|
121
|
+
def invoke(self, ctx: typer.Context) -> Any: # noqa: ANN401 # ty: ignore[invalid-method-override]
|
|
122
|
+
# Typer turns KeyboardInterrupt into a bare exit 130 with nothing on
|
|
123
|
+
# stdout; catch it first so it is reported like any other failure.
|
|
124
|
+
try:
|
|
125
|
+
return super().invoke(ctx)
|
|
126
|
+
except KeyboardInterrupt as exc:
|
|
127
|
+
raise Aborted() from exc
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@contextlib.contextmanager
|
|
131
|
+
def _help_as_envelope(out: Output) -> Generator[None]:
|
|
132
|
+
"""In JSON mode, wrap the help text in a success envelope.
|
|
133
|
+
|
|
134
|
+
Envelopes bypass the capture (see ``Output.stdout``), so only help text
|
|
135
|
+
lands in it. Nothing captured means help was never shown, for example
|
|
136
|
+
because an earlier ``--version`` already answered. If the command fails,
|
|
137
|
+
the captured text is dropped and the error handlers write their own envelope.
|
|
138
|
+
"""
|
|
139
|
+
if not (out.json and out.help):
|
|
140
|
+
yield
|
|
141
|
+
return
|
|
142
|
+
captured = io.StringIO()
|
|
143
|
+
with contextlib.redirect_stdout(captured):
|
|
144
|
+
yield
|
|
145
|
+
if not captured.getvalue():
|
|
146
|
+
return
|
|
147
|
+
# Typer colors help when FORCE_COLOR, PY_COLORS or GITHUB_ACTIONS is set, even
|
|
148
|
+
# into a buffer; JSON consumers get plain text.
|
|
149
|
+
plain = _TERMINAL_ESCAPE.sub("", captured.getvalue())
|
|
150
|
+
text = "\n".join(line.rstrip() for line in plain.splitlines()).strip("\n")
|
|
151
|
+
out.success({"help": text}, human="")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _report_usage_error(out: Output, exc: typer.TyperException) -> ExitCode:
|
|
155
|
+
ctx = getattr(exc, "ctx", None)
|
|
156
|
+
help_command = f"{ctx.command_path} --help" if ctx is not None else "aa --help"
|
|
157
|
+
if out.json:
|
|
158
|
+
out.failure("usage", exc.format_message(), fix=help_command)
|
|
159
|
+
else:
|
|
160
|
+
# Usage errors carry show(), but Typer exports no type that declares it.
|
|
161
|
+
exc.show() # ty: ignore[unresolved-attribute]
|
|
162
|
+
return ExitCode.USAGE
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _report_aborted(out: Output, exc: Aborted) -> ExitCode:
|
|
166
|
+
out.failure("aborted", str(exc))
|
|
167
|
+
return ExitCode.ABORTED
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _report_unexpected_error(out: Output, exc: Exception, command: str | None) -> ExitCode:
|
|
171
|
+
log.debug("Unexpected error", exc_info=exc)
|
|
172
|
+
detail = str(exc).splitlines()[0] if str(exc) else ""
|
|
173
|
+
message = f"{type(exc).__name__}: {detail}" if detail else type(exc).__name__
|
|
174
|
+
redact = _default_redactor()
|
|
175
|
+
out.failure(
|
|
176
|
+
"unexpected",
|
|
177
|
+
_redact_message(redact, message),
|
|
178
|
+
fix=_save_crash_report(exc, command, message, redact),
|
|
179
|
+
)
|
|
180
|
+
return ExitCode.UNEXPECTED
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _default_redactor() -> Callable[[str], str]:
|
|
184
|
+
"""The Redactor ``aa redact`` uses with its default kinds, or one that hides everything."""
|
|
185
|
+
try:
|
|
186
|
+
return build_redactor()
|
|
187
|
+
except Exception:
|
|
188
|
+
log.debug("Could not build the Redactor", exc_info=True)
|
|
189
|
+
return _redaction_failed
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _redaction_failed(text: str) -> str:
|
|
193
|
+
return REDACTION_FAILED
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _redact_message(redact: Callable[[str], str], message: str) -> str:
|
|
197
|
+
try:
|
|
198
|
+
return redact(message)
|
|
199
|
+
except Exception:
|
|
200
|
+
log.debug("Could not redact the error message", exc_info=True)
|
|
201
|
+
return REDACTION_FAILED
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _save_crash_report(
|
|
205
|
+
exc: Exception, command: str | None, message: str, redact: Callable[[str], str]
|
|
206
|
+
) -> str | None:
|
|
207
|
+
"""Save a Crash report and say where it is, or give None when it can't be saved."""
|
|
208
|
+
try:
|
|
209
|
+
path = save_report(
|
|
210
|
+
exc,
|
|
211
|
+
folder=crash_folder("aa"),
|
|
212
|
+
app="aa",
|
|
213
|
+
version=_package_version(),
|
|
214
|
+
command=command,
|
|
215
|
+
message=message,
|
|
216
|
+
redact=redact,
|
|
217
|
+
)
|
|
218
|
+
except Exception:
|
|
219
|
+
log.debug("Could not save a crash report", exc_info=True)
|
|
220
|
+
return None
|
|
221
|
+
return f"Attach {path} to a bug report"
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
app = typer.Typer(cls=AaGroup, add_completion=False, pretty_exceptions_enable=False)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _package_version() -> str:
|
|
228
|
+
from importlib.metadata import version
|
|
229
|
+
|
|
230
|
+
return version("aa-toolkit-cli")
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _show_version(ctx: typer.Context, value: bool) -> None:
|
|
234
|
+
if value:
|
|
235
|
+
current = _package_version()
|
|
236
|
+
ctx.obj.success({"version": current}, human=current)
|
|
237
|
+
raise typer.Exit()
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
@app.callback()
|
|
241
|
+
def root(
|
|
242
|
+
json_output: JsonFlag = False,
|
|
243
|
+
verbose: VerboseFlag = False,
|
|
244
|
+
show_version: Annotated[
|
|
245
|
+
bool,
|
|
246
|
+
typer.Option(
|
|
247
|
+
"--version", callback=_show_version, is_eager=True, help="Show the version and exit."
|
|
248
|
+
),
|
|
249
|
+
] = False,
|
|
250
|
+
) -> None:
|
|
251
|
+
"""A personal developer toolkit."""
|
|
252
|
+
# The global flags are declared so the parser accepts them and --help
|
|
253
|
+
# lists them; AaGroup.main reads them from the raw arguments.
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
@app.command()
|
|
257
|
+
def add(
|
|
258
|
+
ctx: typer.Context,
|
|
259
|
+
piece: Annotated[
|
|
260
|
+
Piece,
|
|
261
|
+
typer.Argument(help=f"The piece to add ({', '.join(Piece)})."),
|
|
262
|
+
],
|
|
263
|
+
json_output: JsonFlag = False,
|
|
264
|
+
verbose: VerboseFlag = False,
|
|
265
|
+
) -> None:
|
|
266
|
+
"""Add a piece to the project in the current folder."""
|
|
267
|
+
out: Output = ctx.obj
|
|
268
|
+
target = Path.cwd().resolve()
|
|
269
|
+
try:
|
|
270
|
+
added = add_piece(target, piece)
|
|
271
|
+
except AddError as exc:
|
|
272
|
+
out.failure(exc.code, str(exc), fix=exc.fix)
|
|
273
|
+
raise typer.Exit(ExitCode.PROBLEMS) from exc
|
|
274
|
+
except StepFailed as exc:
|
|
275
|
+
out.failure("step_failed", str(exc), fix=exc.fix)
|
|
276
|
+
raise typer.Exit(ExitCode.PROBLEMS) from exc
|
|
277
|
+
data = {"piece": str(piece), "files": added.files, "next_steps": added.next_steps}
|
|
278
|
+
if added.files:
|
|
279
|
+
lines = [f"Added {piece} to {target}", *(f" {f}" for f in added.files)]
|
|
280
|
+
else:
|
|
281
|
+
lines = [f"{piece} is already there in {target}"]
|
|
282
|
+
if added.next_steps:
|
|
283
|
+
lines.extend(["", "Next steps:", *(f" {item}" for item in added.next_steps)])
|
|
284
|
+
out.success(data, human="\n".join(lines))
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
@app.command()
|
|
288
|
+
def init(
|
|
289
|
+
ctx: typer.Context,
|
|
290
|
+
name: Annotated[str, typer.Argument(help="The project name, also the folder it goes in.")],
|
|
291
|
+
cli: Annotated[bool, typer.Option("--cli", help="Create a CLI project (the default).")] = False,
|
|
292
|
+
lib: Annotated[bool, typer.Option("--lib", help="Create a typed library project.")] = False,
|
|
293
|
+
license_choice: Annotated[
|
|
294
|
+
License, typer.Option("--license", case_sensitive=False, help="The license to add.")
|
|
295
|
+
] = License.MIT,
|
|
296
|
+
github: Annotated[
|
|
297
|
+
bool, typer.Option("--github", help="Also create a private GitHub repo and push to it.")
|
|
298
|
+
] = False,
|
|
299
|
+
public: Annotated[
|
|
300
|
+
bool, typer.Option("--public", help="Make the GitHub repo public. Needs --github.")
|
|
301
|
+
] = False,
|
|
302
|
+
dry_run: Annotated[
|
|
303
|
+
bool,
|
|
304
|
+
typer.Option(
|
|
305
|
+
"--dry-run",
|
|
306
|
+
help=(
|
|
307
|
+
"Show what would be created and run, without writing files or running setup"
|
|
308
|
+
" commands (reads git config for MIT)."
|
|
309
|
+
),
|
|
310
|
+
),
|
|
311
|
+
] = False,
|
|
312
|
+
json_output: JsonFlag = False,
|
|
313
|
+
verbose: VerboseFlag = False,
|
|
314
|
+
) -> None:
|
|
315
|
+
"""Create a project in a new or empty folder."""
|
|
316
|
+
out: Output = ctx.obj
|
|
317
|
+
if cli and lib:
|
|
318
|
+
raise typer.BadParameter("use only one of them", ctx=ctx, param_hint="'--cli' / '--lib'")
|
|
319
|
+
if public and not github:
|
|
320
|
+
raise typer.BadParameter("only works with '--github'", ctx=ctx, param_hint="'--public'")
|
|
321
|
+
_refuse_bad_name(ctx, name)
|
|
322
|
+
kind = Kind.LIB if lib else Kind.CLI
|
|
323
|
+
target = (Path.cwd() / name).resolve()
|
|
324
|
+
if not is_empty_folder_or_missing(target):
|
|
325
|
+
out.failure("target_not_empty", f"{target} already exists and is not an empty folder")
|
|
326
|
+
raise typer.Exit(ExitCode.PROBLEMS)
|
|
327
|
+
outer = outer_workspace_taking_in(target)
|
|
328
|
+
if outer is not None:
|
|
329
|
+
message = f"{target} would become a member of the uv workspace at {outer.root}"
|
|
330
|
+
out.failure("target_in_workspace", message, fix=outer.fix)
|
|
331
|
+
raise typer.Exit(ExitCode.PROBLEMS)
|
|
332
|
+
if dry_run:
|
|
333
|
+
try:
|
|
334
|
+
plan = plan_project(target, kind, license_choice, github=github, public=public)
|
|
335
|
+
except StepFailed as exc:
|
|
336
|
+
out.failure("step_failed", str(exc), fix=exc.fix)
|
|
337
|
+
raise typer.Exit(ExitCode.PROBLEMS) from exc
|
|
338
|
+
steps = [{"step": s.name, "command": list(s.command)} for s in plan.steps]
|
|
339
|
+
data = {
|
|
340
|
+
"dry_run": True,
|
|
341
|
+
"path": str(target),
|
|
342
|
+
"kind": str(kind),
|
|
343
|
+
"files": plan.files,
|
|
344
|
+
"github_url": None,
|
|
345
|
+
"steps": steps,
|
|
346
|
+
}
|
|
347
|
+
lines = [
|
|
348
|
+
f"Would create a {kind} project at {target}",
|
|
349
|
+
*(f" {f}" for f in plan.files),
|
|
350
|
+
"Would run:",
|
|
351
|
+
*(f" {shlex.join(s['command'])}" for s in steps),
|
|
352
|
+
]
|
|
353
|
+
out.success(data, human="\n".join(lines))
|
|
354
|
+
return
|
|
355
|
+
try:
|
|
356
|
+
created = create_project(target, kind, license_choice)
|
|
357
|
+
github_url = commit_and_push_to_github(target, public) if github else None
|
|
358
|
+
except StepFailed as exc:
|
|
359
|
+
out.failure("step_failed", str(exc), fix=exc.fix)
|
|
360
|
+
raise typer.Exit(ExitCode.PROBLEMS) from exc
|
|
361
|
+
except KeyboardInterrupt as exc:
|
|
362
|
+
raise Aborted(f"Aborted; the folder {target} was left as it is") from exc
|
|
363
|
+
data = {"path": str(target), "kind": str(kind), "files": created, "github_url": github_url}
|
|
364
|
+
lines = [f"Created a {kind} project at {target}", *(f" {f}" for f in created)]
|
|
365
|
+
if github_url:
|
|
366
|
+
lines.append(f"GitHub repo: {github_url}")
|
|
367
|
+
out.success(data, human="\n".join(lines))
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _refuse_bad_name(ctx: typer.Context, name: str) -> None:
|
|
371
|
+
"""Refuse a name uv can't build a project from, before anything is written.
|
|
372
|
+
|
|
373
|
+
``.`` means the current folder, so its own name must follow the rule.
|
|
374
|
+
"""
|
|
375
|
+
project_name = Path.cwd().name if name == "." else name
|
|
376
|
+
if is_valid_name(project_name):
|
|
377
|
+
return
|
|
378
|
+
label = f"the current folder's name '{project_name}'" if name == "." else f"'{name}'"
|
|
379
|
+
raise typer.BadParameter(f"{label} breaks the rule: {NAME_RULE}", ctx=ctx, param_hint="'NAME'")
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
@app.command()
|
|
383
|
+
def redact(
|
|
384
|
+
ctx: typer.Context,
|
|
385
|
+
file: Annotated[
|
|
386
|
+
Path | None,
|
|
387
|
+
typer.Argument(metavar="FILE", help="The file to clean, or standard input when omitted."),
|
|
388
|
+
] = None,
|
|
389
|
+
with_kinds: Annotated[
|
|
390
|
+
list[str] | None,
|
|
391
|
+
typer.Option(
|
|
392
|
+
"--with",
|
|
393
|
+
metavar="KIND",
|
|
394
|
+
help=f"Also hide these off-by-default kinds: {', '.join(WITH_KINDS)}.",
|
|
395
|
+
),
|
|
396
|
+
] = None,
|
|
397
|
+
without_kinds: Annotated[
|
|
398
|
+
list[str] | None,
|
|
399
|
+
typer.Option(
|
|
400
|
+
"--without",
|
|
401
|
+
metavar="KIND",
|
|
402
|
+
help=f"Leave these built-in kinds visible: {', '.join(WITHOUT_KINDS)}.",
|
|
403
|
+
),
|
|
404
|
+
] = None,
|
|
405
|
+
check: Annotated[
|
|
406
|
+
bool,
|
|
407
|
+
typer.Option(
|
|
408
|
+
"--check",
|
|
409
|
+
help="Report every Finding and exit 1 when any is found, without printing the text.",
|
|
410
|
+
),
|
|
411
|
+
] = False,
|
|
412
|
+
json_output: JsonFlag = False,
|
|
413
|
+
verbose: VerboseFlag = False,
|
|
414
|
+
) -> None:
|
|
415
|
+
"""Print a cleaned copy of a file or piped text."""
|
|
416
|
+
out: Output = ctx.obj
|
|
417
|
+
try:
|
|
418
|
+
redactor = build_redactor(with_kinds or (), without_kinds or ())
|
|
419
|
+
except UnknownKind as exc:
|
|
420
|
+
raise typer.BadParameter(str(exc), ctx=ctx, param_hint=f"'{exc.flag}'") from exc
|
|
421
|
+
if file is None and sys.stdin.isatty():
|
|
422
|
+
raise typer.BadParameter(
|
|
423
|
+
"give a file or pipe text in, e.g. 'aa redact app.log' or 'cmd | aa redact'",
|
|
424
|
+
ctx=ctx,
|
|
425
|
+
param_hint="'FILE'",
|
|
426
|
+
)
|
|
427
|
+
try:
|
|
428
|
+
if check:
|
|
429
|
+
if out.json:
|
|
430
|
+
findings = find_all(file, redactor)
|
|
431
|
+
out.success({"findings": findings}, human="")
|
|
432
|
+
found = bool(findings)
|
|
433
|
+
else:
|
|
434
|
+
found = check_file(file, redactor)
|
|
435
|
+
if found:
|
|
436
|
+
raise typer.Exit(ExitCode.PROBLEMS)
|
|
437
|
+
elif out.json:
|
|
438
|
+
out.success({"text": clean_text(file, redactor)}, human="")
|
|
439
|
+
else:
|
|
440
|
+
redact_file(file, redactor)
|
|
441
|
+
except FileError as exc:
|
|
442
|
+
out.failure(exc.code, str(exc))
|
|
443
|
+
raise typer.Exit(ExitCode.PROBLEMS) from exc
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
secret_app = typer.Typer(no_args_is_help=True)
|
|
447
|
+
app.add_typer(secret_app, name="secret")
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
@secret_app.callback()
|
|
451
|
+
def secret(json_output: JsonFlag = False, verbose: VerboseFlag = False) -> None:
|
|
452
|
+
"""Save or delete a Secret in the Secret store. No command prints one back."""
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
SecretName = Annotated[
|
|
456
|
+
str,
|
|
457
|
+
typer.Argument(
|
|
458
|
+
metavar="NAME",
|
|
459
|
+
help="The field name in the app's Settings class, such as api_key.",
|
|
460
|
+
show_default=False,
|
|
461
|
+
),
|
|
462
|
+
]
|
|
463
|
+
AppOption = Annotated[
|
|
464
|
+
str | None,
|
|
465
|
+
typer.Option(
|
|
466
|
+
"--app",
|
|
467
|
+
help="The app name. Default: [project].name in pyproject.toml in the current folder.",
|
|
468
|
+
),
|
|
469
|
+
]
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def _secret_target(ctx: typer.Context, name: str, app_name: str | None) -> tuple[str, str]:
|
|
473
|
+
"""Return the app name and the field name, or raise a usage error."""
|
|
474
|
+
field = field_name(name)
|
|
475
|
+
if field is None:
|
|
476
|
+
# NAME isn't echoed: it may be a value given by mistake.
|
|
477
|
+
raise typer.BadParameter(
|
|
478
|
+
"not a name a Settings field can have, such as api_key", ctx=ctx, param_hint="'NAME'"
|
|
479
|
+
)
|
|
480
|
+
if app_name is not None:
|
|
481
|
+
if not app_name:
|
|
482
|
+
raise typer.BadParameter("must not be empty", ctx=ctx, param_hint="'--app'")
|
|
483
|
+
return app_name, field
|
|
484
|
+
found = project_name(Path.cwd())
|
|
485
|
+
if found is None:
|
|
486
|
+
raise typer.BadParameter(
|
|
487
|
+
"give the app name, because no pyproject.toml here has a [project] name",
|
|
488
|
+
ctx=ctx,
|
|
489
|
+
param_hint="'--app'",
|
|
490
|
+
)
|
|
491
|
+
return found, field
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
_STDIN_HINT = "'standard input'"
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def _secret_value(ctx: typer.Context, out: Output, name: str) -> str:
|
|
498
|
+
"""Read the value from a hidden prompt or from piped standard input."""
|
|
499
|
+
if sys.stdin.isatty():
|
|
500
|
+
if out.json:
|
|
501
|
+
raise typer.BadParameter(
|
|
502
|
+
"with --json, pipe the value in, e.g. 'cmd | aa secret set NAME --json'",
|
|
503
|
+
ctx=ctx,
|
|
504
|
+
param_hint=_STDIN_HINT,
|
|
505
|
+
)
|
|
506
|
+
try:
|
|
507
|
+
value: str = typer.prompt(
|
|
508
|
+
f"Value for {name}", default="", show_default=False, hide_input=True, err=True
|
|
509
|
+
)
|
|
510
|
+
except typer.Abort as exc:
|
|
511
|
+
raise Aborted() from exc
|
|
512
|
+
else:
|
|
513
|
+
try:
|
|
514
|
+
value = read_piped_value()
|
|
515
|
+
except NotUtf8 as exc:
|
|
516
|
+
raise typer.BadParameter(str(exc), ctx=ctx, param_hint=_STDIN_HINT) from None
|
|
517
|
+
if not value:
|
|
518
|
+
raise typer.BadParameter(
|
|
519
|
+
"the value is empty, so nothing was saved", ctx=ctx, param_hint=_STDIN_HINT
|
|
520
|
+
)
|
|
521
|
+
return value
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _no_secret_store(out: Output, exc: SecretStoreError) -> typer.Exit:
|
|
525
|
+
"""Report a missing Secret store; any other store failure stays unexpected."""
|
|
526
|
+
if not exc.no_store:
|
|
527
|
+
raise exc
|
|
528
|
+
out.failure("no_secret_store", str(exc))
|
|
529
|
+
return typer.Exit(ExitCode.PROBLEMS)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
@secret_app.command("set")
|
|
533
|
+
def secret_set(
|
|
534
|
+
ctx: typer.Context,
|
|
535
|
+
name: SecretName,
|
|
536
|
+
app_name: AppOption = None,
|
|
537
|
+
json_output: JsonFlag = False,
|
|
538
|
+
verbose: VerboseFlag = False,
|
|
539
|
+
) -> None:
|
|
540
|
+
"""Save a Secret in the Secret store.
|
|
541
|
+
|
|
542
|
+
The value comes from a hidden prompt, or from piped standard input without
|
|
543
|
+
one trailing line ending. It's never an argument and never printed.
|
|
544
|
+
"""
|
|
545
|
+
out: Output = ctx.obj
|
|
546
|
+
target, name = _secret_target(ctx, name, app_name)
|
|
547
|
+
value = _secret_value(ctx, out, name)
|
|
548
|
+
try:
|
|
549
|
+
replaced = save_secret(target, name, value)
|
|
550
|
+
except SecretStoreError as exc:
|
|
551
|
+
raise _no_secret_store(out, exc) from None
|
|
552
|
+
except ValueError as exc:
|
|
553
|
+
# NAME, the app name and the value are checked above, so only the size is left.
|
|
554
|
+
out.failure("secret_too_large", str(exc))
|
|
555
|
+
raise typer.Exit(ExitCode.PROBLEMS) from None
|
|
556
|
+
verb = "Replaced" if replaced else "Saved"
|
|
557
|
+
out.success(
|
|
558
|
+
{"app": target, "name": name, "replaced": replaced},
|
|
559
|
+
human=f"{verb} {name} for {target} in the Secret store.",
|
|
560
|
+
)
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
@secret_app.command("delete")
|
|
564
|
+
def secret_delete(
|
|
565
|
+
ctx: typer.Context,
|
|
566
|
+
name: SecretName,
|
|
567
|
+
app_name: AppOption = None,
|
|
568
|
+
json_output: JsonFlag = False,
|
|
569
|
+
verbose: VerboseFlag = False,
|
|
570
|
+
) -> None:
|
|
571
|
+
"""Delete a Secret from the Secret store."""
|
|
572
|
+
out: Output = ctx.obj
|
|
573
|
+
target, name = _secret_target(ctx, name, app_name)
|
|
574
|
+
try:
|
|
575
|
+
existed = delete_secret(target, name)
|
|
576
|
+
except SecretStoreError as exc:
|
|
577
|
+
raise _no_secret_store(out, exc) from None
|
|
578
|
+
if not existed:
|
|
579
|
+
out.failure("secret_not_found", f"No Secret {name} is saved for {target}; nothing changed")
|
|
580
|
+
raise typer.Exit(ExitCode.PROBLEMS)
|
|
581
|
+
out.success(
|
|
582
|
+
{"app": target, "name": name},
|
|
583
|
+
human=f"Deleted {name} for {target} from the Secret store.",
|
|
584
|
+
)
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
COMMAND_EFFECTS: dict[str, Effect] = {
|
|
588
|
+
"add": Effect.WRITE,
|
|
589
|
+
"init": Effect.WRITE,
|
|
590
|
+
"redact": Effect.READ,
|
|
591
|
+
"commands": Effect.READ,
|
|
592
|
+
"secret set": Effect.WRITE,
|
|
593
|
+
"secret delete": Effect.WRITE,
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
@app.command()
|
|
598
|
+
def commands(
|
|
599
|
+
ctx: typer.Context,
|
|
600
|
+
json_output: JsonFlag = False,
|
|
601
|
+
verbose: VerboseFlag = False,
|
|
602
|
+
) -> None:
|
|
603
|
+
"""List every command, its arguments, flags and exit codes."""
|
|
604
|
+
out: Output = ctx.obj
|
|
605
|
+
data = describe_cli(app, COMMAND_EFFECTS)
|
|
606
|
+
out.success(data, human=format_commands(data["commands"]))
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
@app.command(hidden=True)
|
|
610
|
+
def crash(json_output: JsonFlag = False, verbose: VerboseFlag = False) -> None:
|
|
611
|
+
"""Fail on purpose, to show how aa reports an unexpected error."""
|
|
612
|
+
raise RuntimeError("aa crash was asked to fail")
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def main() -> None:
|
|
616
|
+
app()
|