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/redact.py ADDED
@@ -0,0 +1,207 @@
1
+ """``aa redact``: cleaning a file or piped text with the redaction library."""
2
+
3
+ __lazy_modules__ = {
4
+ "aa_redact",
5
+ }
6
+
7
+ import contextlib
8
+ import re
9
+ import sys
10
+ from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
11
+ from pathlib import Path
12
+ from typing import BinaryIO
13
+
14
+ from aa_cli.choices import WITH_KINDS, WITHOUT_KINDS
15
+ from aa_redact import Finding, Redactor, ip_address, phone_number
16
+
17
+ type Detector = Callable[[str], Iterable[Finding]]
18
+
19
+
20
+ def with_detectors() -> dict[str, Detector]:
21
+ """Return the mapping from ``--with`` kind name to Detector."""
22
+ return {
23
+ "IP_ADDRESS": ip_address,
24
+ "PHONE": phone_number,
25
+ }
26
+
27
+
28
+ class UnknownKind(Exception):
29
+ """A kind name passed to ``--with`` or ``--without`` is not accepted by that flag."""
30
+
31
+ def __init__(self, flag: str, kind: str, allowed: Sequence[str]) -> None:
32
+ accepted = ", ".join(allowed)
33
+ super().__init__(f"unknown kind {kind!r}; choose from: {accepted}")
34
+ self.flag = flag
35
+
36
+
37
+ class FileError(Exception):
38
+ """The input file does not exist, is a folder, or cannot be read."""
39
+
40
+ def __init__(self, code: str, message: str) -> None:
41
+ super().__init__(message)
42
+ self.code = code
43
+
44
+
45
+ class DetectorFailed(Exception):
46
+ """A Detector raised while cleaning text; the message never holds the input text."""
47
+
48
+ def __init__(self, exc: Exception) -> None:
49
+ super().__init__(f"detector failed ({type(exc).__name__})")
50
+
51
+
52
+ def _parse_kinds(flag: str, values: Sequence[str], allowed: Sequence[str]) -> list[str]:
53
+ parsed: list[str] = []
54
+ for entry in values:
55
+ for raw in entry.split(","):
56
+ name = raw.strip()
57
+ kind = name.upper()
58
+ if kind not in allowed:
59
+ raise UnknownKind(flag, name, allowed)
60
+ parsed.append(kind)
61
+ return parsed
62
+
63
+
64
+ def build_redactor(with_values: Sequence[str] = (), without_values: Sequence[str] = ()) -> Redactor:
65
+ with_kinds = _parse_kinds("--with", with_values, WITH_KINDS)
66
+ without_kinds = _parse_kinds("--without", without_values, WITHOUT_KINDS)
67
+ detectors_by_kind = with_detectors()
68
+ detectors = [detectors_by_kind[kind] for kind in dict.fromkeys(with_kinds)]
69
+ return Redactor(detectors=detectors, without=without_kinds, max_length=sys.maxsize)
70
+
71
+
72
+ _KEY_LABEL = r"(?:[A-Z0-9]{1,20} ){0,4}PRIVATE KEY(?: BLOCK)?-----"
73
+ _KEY_START = re.compile(rf"-----BEGIN {_KEY_LABEL}")
74
+ _KEY_END = re.compile(rf"-----END {_KEY_LABEL}")
75
+
76
+
77
+ def _has_unclosed_key(text: str) -> bool:
78
+ starts = list(_KEY_START.finditer(text))
79
+ return bool(starts) and _KEY_END.search(text, starts[-1].end()) is None
80
+
81
+
82
+ @contextlib.contextmanager
83
+ def open_input(file: Path | None) -> Generator[BinaryIO]:
84
+ if file is None:
85
+ yield sys.stdin.buffer
86
+ return
87
+ if file.is_dir():
88
+ raise FileError("cannot_read", f"{file} is a folder")
89
+ try:
90
+ stream = file.open("rb")
91
+ except FileNotFoundError as exc:
92
+ raise FileError("file_not_found", f"{file} does not exist") from exc
93
+ except OSError as exc:
94
+ detail = exc.strerror or str(exc)
95
+ raise FileError("cannot_read", f"cannot read {file}: {detail}") from exc
96
+ with stream:
97
+ yield stream
98
+
99
+
100
+ def _clean(redact: Redactor, text: str) -> str:
101
+ try:
102
+ return redact(text)
103
+ except Exception as exc:
104
+ raise DetectorFailed(exc) from None
105
+
106
+
107
+ def _find(redact: Redactor, text: str) -> list[Finding]:
108
+ try:
109
+ return redact.find(text)
110
+ except Exception as exc:
111
+ raise DetectorFailed(exc) from None
112
+
113
+
114
+ def _read_chunks(stream: BinaryIO) -> Iterator[tuple[int, str]]:
115
+ held: list[str] = []
116
+ first_line = 1
117
+ line_no = 0
118
+ while raw := stream.readline():
119
+ line_no += 1
120
+ line = raw.decode("utf-8", errors="surrogateescape")
121
+ if not held and not _has_unclosed_key(line):
122
+ yield line_no, line
123
+ continue
124
+ if not held:
125
+ first_line = line_no
126
+ held.append(line)
127
+ if _KEY_END.search(line) and not _has_unclosed_key(line):
128
+ yield first_line, "".join(held)
129
+ held.clear()
130
+ if held:
131
+ yield first_line, "".join(held)
132
+
133
+
134
+ def clean_stream(stream: BinaryIO, redact: Redactor) -> Iterator[str]:
135
+ for _, chunk in _read_chunks(stream):
136
+ yield _clean(redact, chunk)
137
+
138
+
139
+ def _advance(text: str, start: int, end: int, line: int, line_start: int) -> tuple[int, int, int]:
140
+ newlines = text.count("\n", start, end)
141
+ if newlines:
142
+ line += newlines
143
+ line_start = text.rfind("\n", start, end) + 1
144
+ return line, end - line_start + 1, line_start
145
+
146
+
147
+ def find_stream(stream: BinaryIO, redact: Redactor) -> Iterator[dict[str, int | str]]:
148
+ for first_line, chunk in _read_chunks(stream):
149
+ cursor = 0
150
+ line = first_line
151
+ line_start = 0
152
+ for finding in _find(redact, chunk):
153
+ start_line, column, line_start = _advance(
154
+ chunk, cursor, finding.start, line, line_start
155
+ )
156
+ line, end_column, line_start = _advance(
157
+ chunk, finding.start, finding.end, start_line, line_start
158
+ )
159
+ cursor = finding.end
160
+ yield {
161
+ "line": start_line,
162
+ "column": column,
163
+ "end_line": line,
164
+ "end_column": end_column,
165
+ "kind": finding.kind,
166
+ }
167
+
168
+
169
+ def find_all(file: Path | None, redact: Redactor) -> list[dict[str, int | str]]:
170
+ with open_input(file) as stream:
171
+ return list(find_stream(stream, redact))
172
+
173
+
174
+ def check_file(file: Path | None, redact: Redactor) -> bool:
175
+ source = str(file) if file is not None else "<stdin>"
176
+ found = False
177
+ with open_input(file) as stream:
178
+ for item in find_stream(stream, redact):
179
+ found = True
180
+ sys.stdout.write(f"{source}:{item['line']}:{item['column']}: {item['kind']}\n")
181
+ sys.stdout.flush()
182
+ return found
183
+
184
+
185
+ def _as_text(chunk: str) -> str:
186
+ return chunk.encode("utf-8", errors="surrogateescape").decode("utf-8", errors="replace")
187
+
188
+
189
+ def _write_chunk(chunk: str) -> None:
190
+ if sys.stdout.isatty():
191
+ sys.stdout.write(_as_text(chunk))
192
+ sys.stdout.flush()
193
+ else:
194
+ sys.stdout.flush()
195
+ sys.stdout.buffer.write(chunk.encode("utf-8", errors="surrogateescape"))
196
+ sys.stdout.buffer.flush()
197
+
198
+
199
+ def clean_text(file: Path | None, redact: Redactor) -> str:
200
+ with open_input(file) as stream:
201
+ return _as_text("".join(clean_stream(stream, redact)))
202
+
203
+
204
+ def redact_file(file: Path | None, redact: Redactor) -> None:
205
+ with open_input(file) as stream:
206
+ for chunk in clean_stream(stream, redact):
207
+ _write_chunk(chunk)
aa_cli/secret.py ADDED
@@ -0,0 +1,67 @@
1
+ """``aa secret``: where a Secret goes and what its value is, never printed."""
2
+
3
+ __lazy_modules__ = {
4
+ "aa_settings",
5
+ "keyword",
6
+ "tomllib",
7
+ "unicodedata",
8
+ "warnings",
9
+ }
10
+
11
+ import keyword
12
+ import sys
13
+ import tomllib
14
+ import unicodedata
15
+ import warnings
16
+ from pathlib import Path
17
+
18
+ from aa_settings import BaseSettings
19
+
20
+
21
+ def field_name(name: str) -> str | None:
22
+ """``name`` as a Settings class field would spell it, or None when no field can have it.
23
+
24
+ Python reads identifiers in NFKC form, and pydantic refuses or hides some names,
25
+ such as ``_private`` or ``model_config``, so pydantic itself is asked.
26
+ """
27
+ name = unicodedata.normalize("NFKC", name)
28
+ if not name.isidentifier() or keyword.iskeyword(name):
29
+ return None
30
+ namespace = {"__annotations__": {name: str}, "__module__": __name__}
31
+ try:
32
+ with warnings.catch_warnings():
33
+ warnings.simplefilter(
34
+ "ignore"
35
+ ) # a name that shadows an inherited attribute still works
36
+ probe = type("Probe", (BaseSettings,), namespace)
37
+ except Exception:
38
+ return None
39
+ return name if name in probe.model_fields else None
40
+
41
+
42
+ def project_name(folder: Path) -> str | None:
43
+ """``[project].name`` from ``pyproject.toml`` in ``folder``, as written, or None."""
44
+ try:
45
+ data = tomllib.loads((folder / "pyproject.toml").read_text(encoding="utf-8"))
46
+ except OSError, UnicodeDecodeError, tomllib.TOMLDecodeError:
47
+ return None
48
+ project = data.get("project")
49
+ name = project.get("name") if isinstance(project, dict) else None
50
+ return name if isinstance(name, str) and name else None
51
+
52
+
53
+ class NotUtf8(Exception):
54
+ """Piped standard input isn't UTF-8. The message never holds any of it."""
55
+
56
+
57
+ def read_piped_value() -> str:
58
+ """Read standard input to the end, without one trailing line ending."""
59
+ data: bytes = sys.stdin.buffer.read()
60
+ try:
61
+ text: str = data.decode("utf-8-sig")
62
+ except UnicodeDecodeError:
63
+ raise NotUtf8("the piped value isn't UTF-8 text") from None
64
+ for ending in ("\r\n", "\n"):
65
+ if text.endswith(ending):
66
+ return text.removesuffix(ending)
67
+ return text
@@ -0,0 +1,32 @@
1
+ # {{name}}
2
+
3
+ How to work on this project. Source code is in `src/{{package}}` and tests are in `tests`.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ uv sync
9
+ ```
10
+
11
+ ## Test
12
+
13
+ ```bash
14
+ uv run pytest
15
+ ```
16
+
17
+ ## Lint and format
18
+
19
+ ```bash
20
+ uv run ruff check .
21
+ ```
22
+
23
+ ```bash
24
+ uv run ruff format .
25
+ ```
26
+
27
+ CI runs `uv run ruff check .`, `uv run ruff format --check .` and `uv run pytest` on Windows and Linux. Run them before you commit.
28
+
29
+ ## Commits and branches
30
+
31
+ - Write commit messages as Conventional Commits, for example `feat: add a config loader` or `fix: handle an empty file`.
32
+ - Work on short branches and merge them into `main`.
@@ -0,0 +1 @@
1
+ @AGENTS.md
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) {{year}} {{holder}}
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,23 @@
1
+ # {{name}}
2
+
3
+ ## Install
4
+
5
+ ```bash
6
+ uv sync
7
+ ```
8
+
9
+ ## Test
10
+
11
+ ```bash
12
+ uv run pytest
13
+ ```
14
+
15
+ ## Lint
16
+
17
+ ```bash
18
+ uv run ruff check .
19
+ ```
20
+
21
+ ```bash
22
+ uv run ruff format --check .
23
+ ```
@@ -0,0 +1,28 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ lint-and-test:
13
+ name: ${{ matrix.os }}
14
+ runs-on: ${{ matrix.os }}
15
+ strategy:
16
+ fail-fast: false
17
+ matrix:
18
+ os: [ubuntu-latest, windows-latest]
19
+ steps:
20
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
21
+ - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
22
+ with:
23
+ version: "0.13.7"
24
+ - run: uv python install
25
+ - run: uv sync --locked
26
+ - run: uv run ruff check .
27
+ - run: uv run ruff format --check .
28
+ - run: uv run pytest
@@ -0,0 +1,5 @@
1
+ """{{name}}."""
2
+
3
+
4
+ def main() -> None:
5
+ print("Hello from {{name}}!")
@@ -0,0 +1,7 @@
1
+ from {{package}} import main
2
+
3
+
4
+ def test_main_prints_a_greeting(capsys):
5
+ main()
6
+
7
+ assert capsys.readouterr().out == "Hello from {{name}}!\n"
@@ -0,0 +1,22 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+
5
+ # Virtual environments
6
+ .venv/
7
+
8
+ # Build output
9
+ /build/
10
+ /dist/
11
+ /wheels/
12
+ *.egg-info/
13
+
14
+ # Tool caches
15
+ .pytest_cache/
16
+ .ruff_cache/
17
+ .mypy_cache/
18
+ .coverage
19
+ /htmlcov/
20
+
21
+ # Local settings
22
+ .env
@@ -0,0 +1,5 @@
1
+ """{{name}}."""
2
+
3
+
4
+ def hello() -> str:
5
+ return "Hello from {{name}}!"
@@ -0,0 +1,5 @@
1
+ from {{package}} import hello
2
+
3
+
4
+ def test_hello_returns_a_greeting():
5
+ assert hello() == "Hello from {{name}}!"
@@ -0,0 +1,2 @@
1
+ # This project is its own uv workspace root, so it never joins a workspace it sits inside.
2
+ [tool.uv.workspace]
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: aa-toolkit-cli
3
+ Version: 0.1.0a1
4
+ Summary: The aa command.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Dist: aa-toolkit-redact>=0.1.0a1
8
+ Requires-Dist: aa-toolkit-settings>=0.1.0a1
9
+ Requires-Dist: typer>=0.27.3
10
+ Requires-Python: >=3.14
11
+ Description-Content-Type: text/markdown
12
+
13
+ # aa-toolkit-cli
14
+
15
+ The `aa` command. See the toolkit README for how to install and develop it.
16
+
17
+ ## Crash reports
18
+
19
+ When a command fails with an unexpected error (exit code `3`), `aa` saves a Crash report and puts its full path in the error's `fix` field (the `Fix:` line in human mode). Usage errors and Ctrl+C don't save one. Nothing is uploaded.
20
+
21
+ - **Where:** `%LOCALAPPDATA%\aa\crash\`, one Markdown file per crash, named by date and time (`2026-11-16-141205.md`). Only the newest 10 are kept.
22
+ - **What it holds:** the aa version, the Python version, the Windows build, the command name without its arguments (`aa init`, never `aa init my-app`), the error message and the traceback. Never local variables or environment variables.
23
+ - **What's taken out:** the home folder path becomes `[HOME]`, the computer name becomes `[COMPUTER]`, and the error message and traceback go through the same cleaning as `aa redact`. No tool catches everything, so read the file before you post it.
24
+
25
+ If the report can't be saved, `aa` answers as it would without one, with no `fix`.
@@ -0,0 +1,28 @@
1
+ aa_cli/__init__.py,sha256=3sB9epbBZ_kjmDssNyt3UEev_NaPnQU2ynXjB3xLe1I,23
2
+ aa_cli/add.py,sha256=vdaheeBauK627QvJqzvD_PT3hyiApwnWM-3vhyy4TSw,7710
3
+ aa_cli/choices.py,sha256=bRHpfW7wHC0xKK6HEJDh5anFTbJEM6dGBDBxdT5TCBE,575
4
+ aa_cli/cli.py,sha256=5Ll9o1RGoegzXM-sEVeftb284gd7uqC2TcEZud_viGo,21806
5
+ aa_cli/commands.py,sha256=p-ypyuNSoHRhZW5DAA94hofErtjWXCLwTKuiWWWpIs4,7243
6
+ aa_cli/crash.py,sha256=WcoEhzYPajiYQ_0URTLkyqvP0LIby6EJ4OF3TokXEOc,6255
7
+ aa_cli/git.py,sha256=st1y-rj-LfIMnstJzpe2HI5f84W2MM-kLNfUG2w_h_g,923
8
+ aa_cli/init.py,sha256=Ym_fZIlVj7Jc9tgdc9G79v2uNGyjHUHcxXXzN7RL7nc,14323
9
+ aa_cli/output.py,sha256=GGV9Wc1zOwvl5YiXlBC_aXuS7woqtCjRqoJBxyzs564,3571
10
+ aa_cli/process.py,sha256=GKLRNLy4L_KtiKzOmWtP92vTieYwgkUNyI6wntLSuFw,1415
11
+ aa_cli/redact.py,sha256=igG80C0MakLDCGaH_DByA8BOhX3IV2TgxEHzZcszZAk,6921
12
+ aa_cli/secret.py,sha256=sriqtcCZHc_B9CpWYtbp6iLP6AmI3iWuQ6e5ZpXtEsc,2260
13
+ aa_cli/templates/AGENTS.md.tmpl,sha256=udCHXXQmicfy3zDOYfDTVuajgJkkzbBvM3SCxE1aNto,624
14
+ aa_cli/templates/CLAUDE.md.tmpl,sha256=1jHYgEX3RiPVaK37R4O3Lj0bcyMw10m8bHLmZI1FgdM,12
15
+ aa_cli/templates/LICENSE.tmpl,sha256=yW20z3OL2MJ3GfLghSAt2GMuqQUaYbI-misMyEnrNvk,1092
16
+ aa_cli/templates/README.md.tmpl,sha256=xBd0TDKvKhkVs9Z0UIE1rgZzYJqXzvcrVl_ZauZ74Jk,187
17
+ aa_cli/templates/ci.yml.tmpl,sha256=x6rPVgChCcVCDPWjT6ffUbj4ZfjPy8Itenolt_o7uyg,675
18
+ aa_cli/templates/cli_init.py.tmpl,sha256=5vswBAXWPd9gyD9izK0QQPnNeXaMlhwXXPGUROqN0Ng,77
19
+ aa_cli/templates/cli_test.py.tmpl,sha256=dhT_BC8hrQBf7wlkQSfDnPVCOKoEhp0quMM3NI187s4,154
20
+ aa_cli/templates/gitignore.tmpl,sha256=l3_oEEdzcn1xkVTJFMmX3Gqg-ik1bOuLFGYX3cqtAGc,236
21
+ aa_cli/templates/lib_init.py.tmpl,sha256=l1rgpNrzaZtG_gOFRKpyqXNo8dYwBI9csWyLQRfGAwg,77
22
+ aa_cli/templates/lib_test.py.tmpl,sha256=g_cwi61-tg3S0_8gYJXaYdlABL1QB1On7jj1wdI_o7k,119
23
+ aa_cli/templates/pyproject.toml.tmpl,sha256=4YoaE5x17dFatZ2SS2JiJ0Rwo3ELwX8juM9M2qZ0Zec,113
24
+ aa_toolkit_cli-0.1.0a1.dist-info/licenses/LICENSE,sha256=S6eMY2C8HjBm-nve9yHJM84hWaY7wRNNbdNgjCf5jUQ,1087
25
+ aa_toolkit_cli-0.1.0a1.dist-info/WHEEL,sha256=MWx7psoF7KNST9G72pGtiBYuaXRXQXBk9pw5R6FzYko,80
26
+ aa_toolkit_cli-0.1.0a1.dist-info/entry_points.txt,sha256=5UDTDKVWeNUh7CAlNv2_EunXIQXNrni4QLK8FQ5oji0,40
27
+ aa_toolkit_cli-0.1.0a1.dist-info/METADATA,sha256=xwAPxry_dkyOTruLX5ALJGGWATasCEGdlUsnUBA0qyY,1389
28
+ aa_toolkit_cli-0.1.0a1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.7
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ aa = aa_cli.cli:main
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aaron Aco
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.