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 ADDED
@@ -0,0 +1 @@
1
+ """The aa command."""
aa_cli/add.py ADDED
@@ -0,0 +1,221 @@
1
+ """``aa add``: setting up one piece in an existing project."""
2
+
3
+ __lazy_modules__ = {
4
+ "aa_cli.init",
5
+ "tomllib",
6
+ }
7
+
8
+ import re
9
+ import tomllib
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from aa_cli.choices import Piece
15
+ from aa_cli.init import (
16
+ CI_TEMPLATE,
17
+ CI_WORKFLOW,
18
+ PYPROJECT,
19
+ WRITE_FILES_STEP,
20
+ file_step,
21
+ render,
22
+ step,
23
+ write,
24
+ )
25
+
26
+ UV_LOCK = "uv.lock"
27
+ NOT_A_PROJECT_FIX = "Run aa add from the project's root folder (where pyproject.toml is)."
28
+ _CI_TOOLS = ("ruff", "pytest")
29
+ LOG_PACKAGE = "aa-toolkit-log"
30
+ LOG_TAG = "log-v0.1.0"
31
+ LOG_REQUIREMENT = (
32
+ f"{LOG_PACKAGE} @ git+https://github.com/aaronaco/aa-toolkit@{LOG_TAG}"
33
+ "#subdirectory=packages/aa-toolkit-log"
34
+ )
35
+ _LOG_START_STEP = (
36
+ "Add 'from aa_log import configure_logging' and call 'configure_logging()' where the app"
37
+ " starts (only apps call it; a library should skip it)."
38
+ )
39
+ _LOG_GITIGNORE_LINES = ("*.log", "*.log.[1-3]")
40
+ _REQ_NAME = re.compile(r"\s*([A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)")
41
+ _NORMALIZE = re.compile(r"[-_.]+")
42
+
43
+
44
+ class AddError(Exception):
45
+ """Adding a piece cannot proceed because of the target folder or an existing file."""
46
+
47
+ def __init__(self, code: str, message: str, fix: str | None = None) -> None:
48
+ super().__init__(message)
49
+ self.code = code
50
+ self.fix = fix
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class Added:
55
+ """What ``add_piece`` changed or wrote in the project."""
56
+
57
+ files: list[str]
58
+ next_steps: list[str]
59
+
60
+
61
+ def add_piece(target: Path, piece: Piece) -> Added:
62
+ """Add ``piece`` to the project in ``target``."""
63
+ pyproject = target / PYPROJECT
64
+ if not pyproject.is_file():
65
+ raise AddError("not_a_project", f"{target} has no {PYPROJECT}", fix=NOT_A_PROJECT_FIX)
66
+ return _PIECES[piece](target, pyproject)
67
+
68
+
69
+ def _add_ci(target: Path, pyproject: Path) -> Added:
70
+ workflow = target / CI_WORKFLOW
71
+ expected = render(CI_TEMPLATE)
72
+ workflow_already_there = _check_workflow_path(target, workflow, expected)
73
+ existing = _declared_dependencies(pyproject)
74
+ missing = [tool for tool in _CI_TOOLS if tool not in existing]
75
+ if workflow_already_there and not missing and (target / UV_LOCK).is_file():
76
+ return Added(files=[], next_steps=[])
77
+ if missing:
78
+ changed = _uv_step("add dev dependencies", target, "add", "--dev", *missing)
79
+ else:
80
+ changed = _uv_step("lock dependencies", target, "lock")
81
+ if not workflow_already_there:
82
+ with file_step(WRITE_FILES_STEP):
83
+ write(workflow, expected)
84
+ changed.append(CI_WORKFLOW)
85
+ return Added(files=sorted(changed), next_steps=[])
86
+
87
+
88
+ def _add_log(target: Path, pyproject: Path) -> Added:
89
+ next_steps = _log_next_steps(target)
90
+ if LOG_PACKAGE in _declared_dependencies(pyproject, include_groups=False):
91
+ return Added(files=[], next_steps=next_steps)
92
+ changed = _uv_step("add log dependency", target, "add", LOG_REQUIREMENT)
93
+ return Added(files=sorted(changed), next_steps=next_steps)
94
+
95
+
96
+ def _log_next_steps(target: Path) -> list[str]:
97
+ steps = [_LOG_START_STEP]
98
+ missing = _missing_gitignore_lines(target / ".gitignore")
99
+ if missing:
100
+ steps.append(f"Add {', '.join(missing)} to .gitignore.")
101
+ return steps
102
+
103
+
104
+ def _missing_gitignore_lines(gitignore: Path) -> list[str]:
105
+ existing: set[str] = set()
106
+ if gitignore.is_file():
107
+ try:
108
+ existing = {line.strip() for line in gitignore.read_text(encoding="utf-8").splitlines()}
109
+ except OSError, UnicodeDecodeError:
110
+ existing = set()
111
+ return [line for line in _LOG_GITIGNORE_LINES if line not in existing]
112
+
113
+
114
+ def _uv_step(step_name: str, target: Path, *args: str) -> list[str]:
115
+ before = _read_uv_files(target)
116
+ step(step_name, target, "uv", *args)
117
+ return [name for name, content in _read_uv_files(target).items() if before.get(name) != content]
118
+
119
+
120
+ _PIECES = {Piece.CI: _add_ci, Piece.LOG: _add_log}
121
+
122
+
123
+ def _check_workflow_path(target: Path, workflow: Path, expected: str) -> bool:
124
+ for parent in (workflow.parent, *workflow.parent.parents):
125
+ if parent == target:
126
+ break
127
+ if parent.exists() and not parent.is_dir():
128
+ rel = parent.relative_to(target).as_posix()
129
+ raise AddError("file_exists", f"{rel} already exists and is not a folder")
130
+ if _has_content(workflow, expected):
131
+ return True
132
+ if workflow.exists():
133
+ raise AddError("file_exists", f"{CI_WORKFLOW} already exists with different content")
134
+ return False
135
+
136
+
137
+ def _has_content(path: Path, expected: str) -> bool:
138
+ if not path.is_file():
139
+ return False
140
+ try:
141
+ return path.read_text(encoding="utf-8") == expected
142
+ except OSError, UnicodeDecodeError:
143
+ return False
144
+
145
+
146
+ def _declared_dependencies(pyproject: Path, *, include_groups: bool = True) -> set[str]:
147
+ try:
148
+ config = tomllib.loads(pyproject.read_text(encoding="utf-8"))
149
+ except OSError, UnicodeDecodeError, tomllib.TOMLDecodeError:
150
+ return set()
151
+ project = _as_dict(config.get("project"))
152
+ items: list[object] = []
153
+ project_deps = project.get("dependencies", [])
154
+ if isinstance(project_deps, list):
155
+ items.extend(project_deps)
156
+ if include_groups:
157
+ dep_groups = _as_dict(config.get("dependency-groups"))
158
+ uv_config = _as_dict(_as_dict(config.get("tool")).get("uv"))
159
+ groups = _groups_with_legacy_dev(dep_groups, uv_config)
160
+ seen: set[str] = set()
161
+ for group_name in _default_group_names(uv_config, groups):
162
+ items.extend(_expand_group(groups, group_name, seen))
163
+ names: set[str] = set()
164
+ for item in items:
165
+ if isinstance(item, str) and (match := _REQ_NAME.match(item)):
166
+ names.add(_NORMALIZE.sub("-", match.group(1)).lower())
167
+ return names
168
+
169
+
170
+ def _groups_with_legacy_dev(
171
+ dep_groups: dict[str, Any], uv_config: dict[str, Any]
172
+ ) -> dict[str, Any]:
173
+ groups = dict(dep_groups)
174
+ legacy_dev = uv_config.get("dev-dependencies")
175
+ if isinstance(legacy_dev, list):
176
+ dev_group = groups.get("dev")
177
+ existing_dev = dev_group if isinstance(dev_group, list) else []
178
+ groups["dev"] = [*existing_dev, *legacy_dev]
179
+ return groups
180
+
181
+
182
+ def _default_group_names(uv_config: dict[str, Any], dep_groups: dict[str, Any]) -> list[str]:
183
+ default_groups = uv_config.get("default-groups")
184
+ if default_groups is None:
185
+ return ["dev"]
186
+ if default_groups == "all":
187
+ return list(dep_groups)
188
+ if isinstance(default_groups, list):
189
+ return [name for name in default_groups if isinstance(name, str)]
190
+ return []
191
+
192
+
193
+ def _expand_group(dep_groups: dict[str, Any], name: str, seen: set[str]) -> list[object]:
194
+ if name in seen:
195
+ return []
196
+ seen.add(name)
197
+ group = dep_groups.get(name)
198
+ if not isinstance(group, list):
199
+ return []
200
+ expanded: list[object] = []
201
+ for item in group:
202
+ if isinstance(item, dict) and isinstance(inc := item.get("include-group"), str):
203
+ expanded.extend(_expand_group(dep_groups, inc, seen))
204
+ else:
205
+ expanded.append(item)
206
+ return expanded
207
+
208
+
209
+ def _as_dict(value: object) -> dict[str, Any]:
210
+ if not isinstance(value, dict):
211
+ return {}
212
+ mapping: dict[str, Any] = value
213
+ return mapping
214
+
215
+
216
+ def _read_uv_files(target: Path) -> dict[str, bytes]:
217
+ return {
218
+ name: (target / name).read_bytes()
219
+ for name in (PYPROJECT, UV_LOCK)
220
+ if (target / name).is_file()
221
+ }
aa_cli/choices.py ADDED
@@ -0,0 +1,33 @@
1
+ """Cheap command choices and option values, kept free of heavy imports."""
2
+
3
+ from enum import StrEnum
4
+
5
+
6
+ class Piece(StrEnum):
7
+ CI = "ci"
8
+ LOG = "log"
9
+
10
+
11
+ class License(StrEnum):
12
+ MIT = "MIT"
13
+ NONE = "none"
14
+
15
+
16
+ class Effect(StrEnum):
17
+ READ = "read"
18
+ WRITE = "write"
19
+
20
+
21
+ WITH_KINDS: tuple[str, ...] = ("IP_ADDRESS", "PHONE")
22
+ WITHOUT_KINDS: tuple[str, ...] = (
23
+ "AWS_ACCESS_KEY",
24
+ "GITHUB_TOKEN",
25
+ "API_KEY",
26
+ "SLACK_TOKEN",
27
+ "JWT",
28
+ "BEARER_TOKEN",
29
+ "PRIVATE_KEY",
30
+ "URL_PASSWORD",
31
+ "EMAIL",
32
+ "CARD",
33
+ )