moarch-py 0.1.0__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.
- moarch_py/__init__.py +7 -0
- moarch_py/__main__.py +5 -0
- moarch_py/catalog.py +223 -0
- moarch_py/cli.py +136 -0
- moarch_py/commands.py +253 -0
- moarch_py/dependencies.py +43 -0
- moarch_py/file_plan.py +101 -0
- moarch_py/manifest.py +121 -0
- moarch_py/naming.py +134 -0
- moarch_py/options.py +105 -0
- moarch_py/pyproject_file.py +112 -0
- moarch_py/render.py +41 -0
- moarch_py/scaffold.py +139 -0
- moarch_py/templates/ai/AGENTS.md.j2 +134 -0
- moarch_py/templates/ai/CLAUDE.md.j2 +6 -0
- moarch_py/templates/ai/claude-settings.json.j2 +25 -0
- moarch_py/templates/ai/claude_skill.md.j2 +11 -0
- moarch_py/templates/ai/skills/_done.md.j2 +10 -0
- moarch_py/templates/ai/skills/_header.md.j2 +9 -0
- moarch_py/templates/ai/skills/add-feature.md.j2 +73 -0
- moarch_py/templates/ai/skills/explain.md.j2 +101 -0
- moarch_py/templates/ai/skills/fix-bug.md.j2 +45 -0
- moarch_py/templates/ai/skills/make-readable.md.j2 +104 -0
- moarch_py/templates/ai/skills/review.md.j2 +47 -0
- moarch_py/templates/ai/skills/write-tests.md.j2 +57 -0
- moarch_py/templates/app/api/health.py.j2 +25 -0
- moarch_py/templates/app/api/v1/router.py.j2 +13 -0
- moarch_py/templates/app/core/config.py.j2 +46 -0
- moarch_py/templates/app/core/errors.py.j2 +56 -0
- moarch_py/templates/app/core/logging.py.j2 +32 -0
- moarch_py/templates/app/db/base.py.j2 +35 -0
- moarch_py/templates/app/db/models.py.j2 +12 -0
- moarch_py/templates/app/db/repository.py.j2 +54 -0
- moarch_py/templates/app/db/session.py.j2 +59 -0
- moarch_py/templates/app/empty_init.py.j2 +0 -0
- moarch_py/templates/app/features_init.py.j2 +12 -0
- moarch_py/templates/app/main.py.j2 +58 -0
- moarch_py/templates/app/package_init.py.j2 +1 -0
- moarch_py/templates/app/py.typed.j2 +0 -0
- moarch_py/templates/ci/ci.yml.j2 +87 -0
- moarch_py/templates/ci/pre-commit-config.yaml.j2 +24 -0
- moarch_py/templates/docker/Dockerfile.j2 +59 -0
- moarch_py/templates/docker/docker-compose.yml.j2 +68 -0
- moarch_py/templates/docker/dockerignore.j2 +19 -0
- moarch_py/templates/editor/vscode-extensions.json.j2 +8 -0
- moarch_py/templates/editor/vscode-settings.json.j2 +20 -0
- moarch_py/templates/feature/dependencies.py.j2 +17 -0
- moarch_py/templates/feature/models.py.j2 +15 -0
- moarch_py/templates/feature/package_init.py.j2 +1 -0
- moarch_py/templates/feature/repository.py.j2 +10 -0
- moarch_py/templates/feature/router.py.j2 +52 -0
- moarch_py/templates/feature/schemas.py.j2 +38 -0
- moarch_py/templates/feature/service.py.j2 +60 -0
- moarch_py/templates/feature/test_api.py.j2 +52 -0
- moarch_py/templates/migrations/alembic.ini.j2 +54 -0
- moarch_py/templates/migrations/env.py.j2 +62 -0
- moarch_py/templates/migrations/script.py.mako.j2 +26 -0
- moarch_py/templates/project/ARCHITECTURE.md.j2 +74 -0
- moarch_py/templates/project/README.md.j2 +57 -0
- moarch_py/templates/project/env.example.j2 +12 -0
- moarch_py/templates/project/gitignore.j2 +31 -0
- moarch_py/templates/project/python-version.j2 +1 -0
- moarch_py/templates/tests/conftest.py.j2 +44 -0
- moarch_py/templates/tests/test_health.py.j2 +15 -0
- moarch_py/terminal.py +35 -0
- moarch_py/uv_runner.py +41 -0
- moarch_py/wizard.py +38 -0
- moarch_py-0.1.0.dist-info/METADATA +147 -0
- moarch_py-0.1.0.dist-info/RECORD +72 -0
- moarch_py-0.1.0.dist-info/WHEEL +4 -0
- moarch_py-0.1.0.dist-info/entry_points.txt +2 -0
- moarch_py-0.1.0.dist-info/licenses/LICENSE +21 -0
moarch_py/__init__.py
ADDED
moarch_py/__main__.py
ADDED
moarch_py/catalog.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""The registry of every file `moarch-py init` generates.
|
|
2
|
+
|
|
3
|
+
A new generated file is a template under `templates/` plus one entry here.
|
|
4
|
+
Miss the entry and `init` never writes it and `update` can never refresh it.
|
|
5
|
+
`when` decides from the project's options whether the file belongs.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
|
|
13
|
+
from moarch_py.options import ProjectOptions
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _always(_: ProjectOptions) -> bool:
|
|
17
|
+
return True
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class ScaffoldSpec:
|
|
22
|
+
"""One generated file: where it goes, what renders it, and when it exists."""
|
|
23
|
+
|
|
24
|
+
slug: str
|
|
25
|
+
"""The name `moarch-py update <slug>` takes; unique across the catalog."""
|
|
26
|
+
|
|
27
|
+
path: str
|
|
28
|
+
"""The project-relative path; `{package}` is replaced by the package name."""
|
|
29
|
+
|
|
30
|
+
template: str
|
|
31
|
+
"""The template under `moarch_py/templates/`."""
|
|
32
|
+
|
|
33
|
+
group: str
|
|
34
|
+
"""The group `moarch-py update <group>` refreshes together."""
|
|
35
|
+
|
|
36
|
+
when: Callable[[ProjectOptions], bool] = _always
|
|
37
|
+
|
|
38
|
+
extra: dict[str, str] = field(default_factory=dict)
|
|
39
|
+
"""Template variables only this file needs (a skill's name and description)."""
|
|
40
|
+
|
|
41
|
+
def path_for(self, package: str) -> str:
|
|
42
|
+
"""The path in a project whose package is [package]."""
|
|
43
|
+
return self.path.format(package=package)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# Skills the generated project ships: (slug, description). The description is
|
|
47
|
+
# what an agent matches a task against, so it says when to use the skill.
|
|
48
|
+
PROJECT_SKILLS: tuple[tuple[str, str], ...] = (
|
|
49
|
+
(
|
|
50
|
+
"add-feature",
|
|
51
|
+
"Add a new feature to this moarch-py FastAPI project — a resource with its own "
|
|
52
|
+
"table, endpoints and rules. Scaffolds every layer with `moarch-py create feature`, "
|
|
53
|
+
"then fills in the model, schemas, repository, service, router, migration and "
|
|
54
|
+
"tests. Use when asked to add a feature, resource, entity, module or endpoints "
|
|
55
|
+
"for a new kind of data.",
|
|
56
|
+
),
|
|
57
|
+
(
|
|
58
|
+
"write-tests",
|
|
59
|
+
"Write or update tests in this moarch-py FastAPI project: API tests through the "
|
|
60
|
+
"async client and service tests against the in-memory database. Use when asked "
|
|
61
|
+
"for tests, after adding an endpoint or a service rule, or when a test fails.",
|
|
62
|
+
),
|
|
63
|
+
(
|
|
64
|
+
"fix-bug",
|
|
65
|
+
"Find and fix a bug in this moarch-py FastAPI project by reproducing it first: "
|
|
66
|
+
"find the layer that owns the symptom, write a test that fails because of it, "
|
|
67
|
+
"fix the cause there and keep the test. Use when something is broken, returns "
|
|
68
|
+
"the wrong status or data, raises, or fails for a reason that is not obvious.",
|
|
69
|
+
),
|
|
70
|
+
(
|
|
71
|
+
"review",
|
|
72
|
+
"Review a change in this moarch-py FastAPI project against its architecture rules "
|
|
73
|
+
"(layers, transactions, schemas, errors, settings, migrations) and report every "
|
|
74
|
+
"violation with file and line. Use when asked to review a diff, a branch or a "
|
|
75
|
+
"PR, and before calling your own change done.",
|
|
76
|
+
),
|
|
77
|
+
(
|
|
78
|
+
"make-readable",
|
|
79
|
+
"Make code in this moarch-py FastAPI project easier to read without changing what "
|
|
80
|
+
"it does: names that say what a variable, function or class is, functions that "
|
|
81
|
+
"do one thing, and comments that explain why wherever the logic is not obvious. "
|
|
82
|
+
"Use when asked to clean up, clarify, rename, document or comment code, or when "
|
|
83
|
+
"code is hard to follow.",
|
|
84
|
+
),
|
|
85
|
+
(
|
|
86
|
+
"explain",
|
|
87
|
+
"Explain what code in this moarch-py FastAPI project does, step by step, and teach "
|
|
88
|
+
"the Python, FastAPI, SQLAlchemy and Pydantic behind it with the project's own "
|
|
89
|
+
"code as the example: traces a request through every layer, names each concept "
|
|
90
|
+
"with a short explanation and a link to the official docs, and ends with a way "
|
|
91
|
+
"to see it happen. Use when asked how something works, why it is written that "
|
|
92
|
+
"way, what happens when…, or to learn the stack.",
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _migrations(options: ProjectOptions) -> bool:
|
|
98
|
+
return options.migrations
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _docker(options: ProjectOptions) -> bool:
|
|
102
|
+
return options.docker
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _ci(options: ProjectOptions) -> bool:
|
|
106
|
+
return options.ci
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _pre_commit(options: ProjectOptions) -> bool:
|
|
110
|
+
return options.pre_commit
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _ai(options: ProjectOptions) -> bool:
|
|
114
|
+
return options.ai
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _skill_context(slug: str, description: str) -> dict[str, str]:
|
|
118
|
+
return {"skill_name": f"moarch-{slug}", "skill_description": description}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
_PKG = "src/{package}"
|
|
122
|
+
|
|
123
|
+
CATALOG: tuple[ScaffoldSpec, ...] = (
|
|
124
|
+
# ── project root ──────────────────────────────────────────────────────
|
|
125
|
+
ScaffoldSpec("readme", "README.md", "project/README.md.j2", "docs"),
|
|
126
|
+
ScaffoldSpec("gitignore", ".gitignore", "project/gitignore.j2", "config"),
|
|
127
|
+
ScaffoldSpec("python-version", ".python-version", "project/python-version.j2", "config"),
|
|
128
|
+
ScaffoldSpec("env-example", ".env.example", "project/env.example.j2", "config"),
|
|
129
|
+
ScaffoldSpec("architecture", "docs/ARCHITECTURE.md", "project/ARCHITECTURE.md.j2", "docs"),
|
|
130
|
+
# ── application package ───────────────────────────────────────────────
|
|
131
|
+
ScaffoldSpec("package", f"{_PKG}/__init__.py", "app/package_init.py.j2", "core"),
|
|
132
|
+
ScaffoldSpec("main", f"{_PKG}/main.py", "app/main.py.j2", "core"),
|
|
133
|
+
ScaffoldSpec("core", f"{_PKG}/core/__init__.py", "app/empty_init.py.j2", "core"),
|
|
134
|
+
ScaffoldSpec("config", f"{_PKG}/core/config.py", "app/core/config.py.j2", "core"),
|
|
135
|
+
ScaffoldSpec("logging", f"{_PKG}/core/logging.py", "app/core/logging.py.j2", "core"),
|
|
136
|
+
ScaffoldSpec("errors", f"{_PKG}/core/errors.py", "app/core/errors.py.j2", "core"),
|
|
137
|
+
ScaffoldSpec("db", f"{_PKG}/db/__init__.py", "app/empty_init.py.j2", "db"),
|
|
138
|
+
ScaffoldSpec("db-base", f"{_PKG}/db/base.py", "app/db/base.py.j2", "db"),
|
|
139
|
+
ScaffoldSpec("db-session", f"{_PKG}/db/session.py", "app/db/session.py.j2", "db"),
|
|
140
|
+
ScaffoldSpec("db-repository", f"{_PKG}/db/repository.py", "app/db/repository.py.j2", "db"),
|
|
141
|
+
ScaffoldSpec("db-models", f"{_PKG}/db/models.py", "app/db/models.py.j2", "db"),
|
|
142
|
+
ScaffoldSpec("api", f"{_PKG}/api/__init__.py", "app/empty_init.py.j2", "api"),
|
|
143
|
+
ScaffoldSpec("health", f"{_PKG}/api/health.py", "app/api/health.py.j2", "api"),
|
|
144
|
+
ScaffoldSpec("api-v1", f"{_PKG}/api/v1/__init__.py", "app/empty_init.py.j2", "api"),
|
|
145
|
+
ScaffoldSpec("api-v1-router", f"{_PKG}/api/v1/router.py", "app/api/v1/router.py.j2", "api"),
|
|
146
|
+
ScaffoldSpec("features", f"{_PKG}/features/__init__.py", "app/features_init.py.j2", "api"),
|
|
147
|
+
ScaffoldSpec("py-typed", f"{_PKG}/py.typed", "app/py.typed.j2", "core"),
|
|
148
|
+
# ── tests ─────────────────────────────────────────────────────────────
|
|
149
|
+
ScaffoldSpec("conftest", "tests/conftest.py", "tests/conftest.py.j2", "tests"),
|
|
150
|
+
ScaffoldSpec("test-health", "tests/test_health.py", "tests/test_health.py.j2", "tests"),
|
|
151
|
+
# ── migrations ────────────────────────────────────────────────────────
|
|
152
|
+
ScaffoldSpec(
|
|
153
|
+
"alembic-ini", "alembic.ini", "migrations/alembic.ini.j2", "migrations", _migrations
|
|
154
|
+
),
|
|
155
|
+
ScaffoldSpec(
|
|
156
|
+
"alembic-env", "migrations/env.py", "migrations/env.py.j2", "migrations", _migrations
|
|
157
|
+
),
|
|
158
|
+
ScaffoldSpec(
|
|
159
|
+
"alembic-script",
|
|
160
|
+
"migrations/script.py.mako",
|
|
161
|
+
"migrations/script.py.mako.j2",
|
|
162
|
+
"migrations",
|
|
163
|
+
_migrations,
|
|
164
|
+
),
|
|
165
|
+
ScaffoldSpec(
|
|
166
|
+
"alembic-versions",
|
|
167
|
+
"migrations/versions/.gitkeep",
|
|
168
|
+
"app/py.typed.j2",
|
|
169
|
+
"migrations",
|
|
170
|
+
_migrations,
|
|
171
|
+
),
|
|
172
|
+
# ── docker ────────────────────────────────────────────────────────────
|
|
173
|
+
ScaffoldSpec("dockerfile", "Dockerfile", "docker/Dockerfile.j2", "docker", _docker),
|
|
174
|
+
ScaffoldSpec("dockerignore", ".dockerignore", "docker/dockerignore.j2", "docker", _docker),
|
|
175
|
+
ScaffoldSpec(
|
|
176
|
+
"compose", "docker-compose.yml", "docker/docker-compose.yml.j2", "docker", _docker
|
|
177
|
+
),
|
|
178
|
+
# ── quality ───────────────────────────────────────────────────────────
|
|
179
|
+
ScaffoldSpec("ci", ".github/workflows/ci.yml", "ci/ci.yml.j2", "ci", _ci),
|
|
180
|
+
ScaffoldSpec(
|
|
181
|
+
"pre-commit", ".pre-commit-config.yaml", "ci/pre-commit-config.yaml.j2", "ci", _pre_commit
|
|
182
|
+
),
|
|
183
|
+
# ── editor: ruff as the formatter and linter on save ──────────────────
|
|
184
|
+
ScaffoldSpec(
|
|
185
|
+
"vscode-settings", ".vscode/settings.json", "editor/vscode-settings.json.j2", "editor"
|
|
186
|
+
),
|
|
187
|
+
ScaffoldSpec(
|
|
188
|
+
"vscode-extensions", ".vscode/extensions.json", "editor/vscode-extensions.json.j2", "editor"
|
|
189
|
+
),
|
|
190
|
+
# ── AI agent guide ────────────────────────────────────────────────────
|
|
191
|
+
ScaffoldSpec("agents", "AGENTS.md", "ai/AGENTS.md.j2", "ai", _ai),
|
|
192
|
+
ScaffoldSpec("claude-md", "CLAUDE.md", "ai/CLAUDE.md.j2", "ai", _ai),
|
|
193
|
+
ScaffoldSpec(
|
|
194
|
+
"claude-settings", ".claude/settings.json", "ai/claude-settings.json.j2", "ai", _ai
|
|
195
|
+
),
|
|
196
|
+
*(
|
|
197
|
+
ScaffoldSpec(
|
|
198
|
+
f"skill-{slug}",
|
|
199
|
+
f".agents/skills/moarch-{slug}/SKILL.md",
|
|
200
|
+
f"ai/skills/{slug}.md.j2",
|
|
201
|
+
"ai",
|
|
202
|
+
_ai,
|
|
203
|
+
_skill_context(slug, description),
|
|
204
|
+
)
|
|
205
|
+
for slug, description in PROJECT_SKILLS
|
|
206
|
+
),
|
|
207
|
+
*(
|
|
208
|
+
ScaffoldSpec(
|
|
209
|
+
f"claude-skill-{slug}",
|
|
210
|
+
f".claude/skills/moarch-{slug}/SKILL.md",
|
|
211
|
+
"ai/claude_skill.md.j2",
|
|
212
|
+
"ai",
|
|
213
|
+
_ai,
|
|
214
|
+
_skill_context(slug, description),
|
|
215
|
+
)
|
|
216
|
+
for slug, description in PROJECT_SKILLS
|
|
217
|
+
),
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def specs_for(options: ProjectOptions) -> list[ScaffoldSpec]:
|
|
222
|
+
"""The catalog entries that belong in a project with [options]."""
|
|
223
|
+
return [spec for spec in CATALOG if spec.when(options)]
|
moarch_py/cli.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""The `moarch-py` command line. Same grammar as the Flutter moarch: init, create <thing>, ..."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Annotated
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
|
|
11
|
+
from moarch_py import __version__
|
|
12
|
+
from moarch_py.commands import (
|
|
13
|
+
CreateFeatureRequest,
|
|
14
|
+
InitRequest,
|
|
15
|
+
UsageError,
|
|
16
|
+
run_create_feature,
|
|
17
|
+
run_init,
|
|
18
|
+
)
|
|
19
|
+
from moarch_py.file_plan import AnchorNotFoundError, FileConflictError
|
|
20
|
+
from moarch_py.naming import InvalidNameError
|
|
21
|
+
from moarch_py.options import Database
|
|
22
|
+
from moarch_py.scaffold import NotAMoarchProjectError
|
|
23
|
+
from moarch_py.terminal import FAILED, error_console, make_output_safe
|
|
24
|
+
from moarch_py.uv_runner import ToolMissingError
|
|
25
|
+
from moarch_py.wizard import WizardCancelledError
|
|
26
|
+
|
|
27
|
+
app = typer.Typer(
|
|
28
|
+
name="moarch-py",
|
|
29
|
+
help="Scaffold and grow feature-first FastAPI projects on uv.",
|
|
30
|
+
no_args_is_help=True,
|
|
31
|
+
add_completion=False,
|
|
32
|
+
)
|
|
33
|
+
create_app = typer.Typer(help="Add a piece to an existing moarch-py project.", no_args_is_help=True)
|
|
34
|
+
app.add_typer(create_app, name="create")
|
|
35
|
+
|
|
36
|
+
# Errors that mean "the command could not do what was asked", shown as one
|
|
37
|
+
# message rather than a traceback.
|
|
38
|
+
_EXPECTED_ERRORS = (
|
|
39
|
+
UsageError,
|
|
40
|
+
InvalidNameError,
|
|
41
|
+
FileConflictError,
|
|
42
|
+
AnchorNotFoundError,
|
|
43
|
+
NotAMoarchProjectError,
|
|
44
|
+
ToolMissingError,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _show_version(requested: bool) -> None:
|
|
49
|
+
if requested:
|
|
50
|
+
typer.echo(f"moarch-py {__version__}")
|
|
51
|
+
raise typer.Exit
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@app.callback()
|
|
55
|
+
def _root(
|
|
56
|
+
version: Annotated[
|
|
57
|
+
bool,
|
|
58
|
+
typer.Option("--version", callback=_show_version, is_eager=True, help="Show the version."),
|
|
59
|
+
] = False,
|
|
60
|
+
) -> None:
|
|
61
|
+
"""Scaffold and grow feature-first FastAPI projects on uv."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@app.command()
|
|
65
|
+
def init(
|
|
66
|
+
name: Annotated[
|
|
67
|
+
str | None,
|
|
68
|
+
typer.Argument(help="Create this folder. Leave out to scaffold the current folder."),
|
|
69
|
+
] = None,
|
|
70
|
+
take_defaults: Annotated[
|
|
71
|
+
bool, typer.Option("--all", help="Generate the default structure without prompts.")
|
|
72
|
+
] = False,
|
|
73
|
+
database: Annotated[
|
|
74
|
+
Database | None, typer.Option("--db", help="Database engine, skipping that question.")
|
|
75
|
+
] = None,
|
|
76
|
+
dry_run: Annotated[
|
|
77
|
+
bool, typer.Option("--dry-run", help="List what would be written; write nothing.")
|
|
78
|
+
] = False,
|
|
79
|
+
force: Annotated[bool, typer.Option("--force", help="Overwrite existing files.")] = False,
|
|
80
|
+
install: Annotated[
|
|
81
|
+
bool,
|
|
82
|
+
typer.Option("--install/--no-install", help="Install packages with uv after writing."),
|
|
83
|
+
] = True,
|
|
84
|
+
) -> None:
|
|
85
|
+
"""Scaffold a FastAPI project: app, database, tests, Docker, CI and the AI agent guide."""
|
|
86
|
+
_run(
|
|
87
|
+
lambda: run_init(
|
|
88
|
+
InitRequest(
|
|
89
|
+
name=name,
|
|
90
|
+
take_defaults=take_defaults,
|
|
91
|
+
database=database,
|
|
92
|
+
dry_run=dry_run,
|
|
93
|
+
force=force,
|
|
94
|
+
install=install,
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@create_app.command("feature")
|
|
101
|
+
def create_feature(
|
|
102
|
+
name: Annotated[str, typer.Argument(help="The feature, as a plural: orders, order_items.")],
|
|
103
|
+
project: Annotated[Path, typer.Option("--project", "-p", help="The project folder.")] = Path(
|
|
104
|
+
"."
|
|
105
|
+
),
|
|
106
|
+
dry_run: Annotated[
|
|
107
|
+
bool, typer.Option("--dry-run", help="List what would be written; write nothing.")
|
|
108
|
+
] = False,
|
|
109
|
+
force: Annotated[
|
|
110
|
+
bool, typer.Option("--force", help="Overwrite the feature's files if they exist.")
|
|
111
|
+
] = False,
|
|
112
|
+
) -> None:
|
|
113
|
+
"""All layers of a feature (model, schemas, repository, service, router), registered."""
|
|
114
|
+
_run(
|
|
115
|
+
lambda: run_create_feature(
|
|
116
|
+
CreateFeatureRequest(name=name, project_root=project, dry_run=dry_run, force=force)
|
|
117
|
+
)
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _run(command: Callable[[], None]) -> None:
|
|
122
|
+
"""Runs [command], turning an expected failure into a message and exit code 1."""
|
|
123
|
+
try:
|
|
124
|
+
command()
|
|
125
|
+
except _EXPECTED_ERRORS as error:
|
|
126
|
+
error_console.print(f"{FAILED} {error}")
|
|
127
|
+
raise typer.Exit(code=1) from error
|
|
128
|
+
except WizardCancelledError:
|
|
129
|
+
error_console.print("Cancelled; nothing was written.")
|
|
130
|
+
raise typer.Exit(code=1) from None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def main() -> None:
|
|
134
|
+
"""The `moarch-py` console script."""
|
|
135
|
+
make_output_safe()
|
|
136
|
+
app()
|
moarch_py/commands.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""What `moarch-py init` and `moarch-py create feature` do, step by step, including disk and uv."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
import sys
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from moarch_py.dependencies import dependencies_for
|
|
11
|
+
from moarch_py.file_plan import FilePlan
|
|
12
|
+
from moarch_py.manifest import MANIFEST_FILE, ProjectManifest, hash_content
|
|
13
|
+
from moarch_py.naming import FeatureName, ProjectName
|
|
14
|
+
from moarch_py.options import Database, ProjectOptions
|
|
15
|
+
from moarch_py.pyproject_file import build_pyproject, read_project_name
|
|
16
|
+
from moarch_py.scaffold import PYTHON_VERSION, load_manifest, plan_feature, plan_project
|
|
17
|
+
from moarch_py.terminal import FAILED, OK, WARNING, console
|
|
18
|
+
from moarch_py.uv_runner import CommandFailedError, run, uv_version
|
|
19
|
+
from moarch_py.wizard import ask_checklist, ask_database
|
|
20
|
+
|
|
21
|
+
# `python -m ruff`, not the `.venv/Scripts/ruff.exe` launcher: antivirus
|
|
22
|
+
# heuristics (AVG/Avast Auto-Sandbox) treat every new launcher in a fresh venv
|
|
23
|
+
# as an unknown program and sandbox it, which can freeze a Windows machine.
|
|
24
|
+
# python.exe is a known, signed binary, so running tools through it is not flagged.
|
|
25
|
+
RUFF = ["uv", "run", "python", "-m", "ruff"]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class UsageError(Exception):
|
|
29
|
+
"""A problem with how the command was called; shown without a traceback."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class InitRequest:
|
|
34
|
+
"""Everything `moarch-py init` was called with."""
|
|
35
|
+
|
|
36
|
+
name: str | None
|
|
37
|
+
take_defaults: bool
|
|
38
|
+
database: Database | None
|
|
39
|
+
dry_run: bool
|
|
40
|
+
force: bool
|
|
41
|
+
install: bool
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def resolve_project_root(name: str | None) -> tuple[Path, ProjectName]:
|
|
45
|
+
"""Where the project goes and what it is called.
|
|
46
|
+
|
|
47
|
+
With a name, a new folder of that name. Without one, the current folder,
|
|
48
|
+
named by its existing pyproject.toml (after `uv init`) or by the folder.
|
|
49
|
+
"""
|
|
50
|
+
if name:
|
|
51
|
+
project_name = ProjectName.parse(name)
|
|
52
|
+
root = Path.cwd() / project_name.distribution
|
|
53
|
+
if root.exists() and any(root.iterdir()):
|
|
54
|
+
raise UsageError(
|
|
55
|
+
f"{root} already exists and is not empty. Run `moarch-py init` inside it "
|
|
56
|
+
"to scaffold it in place, or pick another name."
|
|
57
|
+
)
|
|
58
|
+
return root, project_name
|
|
59
|
+
root = Path.cwd()
|
|
60
|
+
if (root / MANIFEST_FILE).exists():
|
|
61
|
+
raise UsageError(f"{root} is already a moarch-py project ({MANIFEST_FILE} exists).")
|
|
62
|
+
existing_name = read_project_name(root)
|
|
63
|
+
return root, ProjectName.parse(existing_name or root.name)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def collect_options(project_name: ProjectName, request: InitRequest) -> ProjectOptions:
|
|
67
|
+
"""The answers: from flags with `--all`, otherwise from the wizard."""
|
|
68
|
+
if request.take_defaults:
|
|
69
|
+
return ProjectOptions.with_defaults(project_name, request.database or Database.POSTGRES)
|
|
70
|
+
if not sys.stdin.isatty():
|
|
71
|
+
raise UsageError("No terminal to ask questions in. Pass --all to take the defaults.")
|
|
72
|
+
database = request.database or ask_database()
|
|
73
|
+
return ProjectOptions.from_checklist(project_name, database, ask_checklist())
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def run_init(request: InitRequest) -> None:
|
|
77
|
+
"""`moarch-py init`: plans every file, writes them, installs, formats, records."""
|
|
78
|
+
root, project_name = resolve_project_root(request.name)
|
|
79
|
+
options = collect_options(project_name, request)
|
|
80
|
+
detected_uv = uv_version()
|
|
81
|
+
if request.install and detected_uv is None:
|
|
82
|
+
raise UsageError(
|
|
83
|
+
"uv is not installed: https://docs.astral.sh/uv/getting-started/installation/ "
|
|
84
|
+
"(or pass --no-install to only write the files)."
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
plan, manifest = plan_project(root, options, uv_version=detected_uv)
|
|
88
|
+
dependencies = dependencies_for(options)
|
|
89
|
+
pyproject_path = root / "pyproject.toml"
|
|
90
|
+
existing_pyproject = (
|
|
91
|
+
pyproject_path.read_text(encoding="utf-8") if pyproject_path.exists() else None
|
|
92
|
+
)
|
|
93
|
+
plan.edit(
|
|
94
|
+
"pyproject.toml",
|
|
95
|
+
build_pyproject(
|
|
96
|
+
existing_pyproject,
|
|
97
|
+
options,
|
|
98
|
+
python_version=PYTHON_VERSION,
|
|
99
|
+
# Without `uv add`, list the names so the file still says what to install.
|
|
100
|
+
unpinned_dependencies=None
|
|
101
|
+
if request.install
|
|
102
|
+
else (dependencies.runtime, dependencies.development),
|
|
103
|
+
),
|
|
104
|
+
)
|
|
105
|
+
if not (root / ".env").exists():
|
|
106
|
+
plan.add(".env", plan.files[".env.example"])
|
|
107
|
+
|
|
108
|
+
if request.dry_run:
|
|
109
|
+
_print_plan(plan, title=f"Would create {project_name.distribution} in {root}")
|
|
110
|
+
console.print(f"Runtime packages: {', '.join(dependencies.runtime)}")
|
|
111
|
+
console.print(f"Dev packages: {', '.join(dependencies.development)}")
|
|
112
|
+
return
|
|
113
|
+
|
|
114
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
115
|
+
plan.write(force=request.force)
|
|
116
|
+
console.print(f"{OK} Wrote {len(plan.files)} files in {root}")
|
|
117
|
+
|
|
118
|
+
if request.install:
|
|
119
|
+
_install(root, dependencies.runtime, dependencies.development)
|
|
120
|
+
_init_git(root)
|
|
121
|
+
|
|
122
|
+
# Hash what is on disk *after* formatting, so `moarch-py update` does not
|
|
123
|
+
# mistake ruff's reflow for a user's edit.
|
|
124
|
+
on_disk = {path: (root / path).read_text(encoding="utf-8") for path in manifest.files}
|
|
125
|
+
manifest.record(on_disk)
|
|
126
|
+
(root / MANIFEST_FILE).write_text(manifest.render(), encoding="utf-8", newline="\n")
|
|
127
|
+
_print_next_steps(root, options, installed=request.install, named=request.name is not None)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _install(root: Path, runtime: list[str], development: list[str]) -> None:
|
|
131
|
+
"""Adds the packages with uv (newest compatible versions), then formats the code."""
|
|
132
|
+
try:
|
|
133
|
+
with console.status("Resolving and installing packages with uv..."):
|
|
134
|
+
run(["uv", "add", *runtime], cwd=root)
|
|
135
|
+
run(["uv", "add", "--dev", *development], cwd=root)
|
|
136
|
+
console.print(f"{OK} Installed packages, wrote uv.lock")
|
|
137
|
+
# Templates are readable at any line length; ruff makes them match
|
|
138
|
+
# the project's own style, so `ruff format --check` passes from day one.
|
|
139
|
+
run([*RUFF, "format", "."], cwd=root)
|
|
140
|
+
run([*RUFF, "check", "--fix", "--quiet", "."], cwd=root)
|
|
141
|
+
console.print(f"{OK} Formatted with ruff")
|
|
142
|
+
except CommandFailedError as error:
|
|
143
|
+
console.print(f"{FAILED} {error}")
|
|
144
|
+
console.print(
|
|
145
|
+
"The files are written. Fix the problem above, then run in the project:\n"
|
|
146
|
+
f" uv add {' '.join(runtime)}\n uv add --dev {' '.join(development)}"
|
|
147
|
+
)
|
|
148
|
+
raise SystemExit(1) from error
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _init_git(root: Path) -> None:
|
|
152
|
+
"""Starts a git repository unless the folder is already inside one."""
|
|
153
|
+
if shutil.which("git") is None:
|
|
154
|
+
return
|
|
155
|
+
try:
|
|
156
|
+
run(["git", "rev-parse", "--is-inside-work-tree"], cwd=root)
|
|
157
|
+
except CommandFailedError:
|
|
158
|
+
run(["git", "init", "--quiet"], cwd=root)
|
|
159
|
+
console.print(f"{OK} Started a git repository")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _print_plan(plan: FilePlan, *, title: str) -> None:
|
|
163
|
+
console.print(f"[bold]{title}[/]")
|
|
164
|
+
for path in sorted(plan.files):
|
|
165
|
+
marker = "~" if path in plan.edits and (plan.root / path).exists() else "+"
|
|
166
|
+
console.print(f" {marker} {path}")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _print_next_steps(root: Path, options: ProjectOptions, *, installed: bool, named: bool) -> None:
|
|
170
|
+
steps = []
|
|
171
|
+
if named:
|
|
172
|
+
steps.append(f"cd {root.name}")
|
|
173
|
+
if not installed:
|
|
174
|
+
steps.append("uv sync")
|
|
175
|
+
if options.migrations and options.database.runs_in_container:
|
|
176
|
+
steps.append("docker compose up -d db # or point DATABASE_URL in .env at yours")
|
|
177
|
+
if options.migrations:
|
|
178
|
+
steps.append("uv run alembic upgrade head")
|
|
179
|
+
steps.append(f"uv run fastapi dev src/{options.name.package}/main.py")
|
|
180
|
+
steps.append("moarch-py create feature orders # your first feature")
|
|
181
|
+
console.print("\n[bold]Next:[/]")
|
|
182
|
+
for step in steps:
|
|
183
|
+
console.print(f" {step}")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@dataclass(frozen=True)
|
|
187
|
+
class CreateFeatureRequest:
|
|
188
|
+
"""Everything `moarch-py create feature` was called with."""
|
|
189
|
+
|
|
190
|
+
name: str
|
|
191
|
+
project_root: Path
|
|
192
|
+
dry_run: bool
|
|
193
|
+
force: bool
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def run_create_feature(request: CreateFeatureRequest) -> None:
|
|
197
|
+
"""`moarch-py create feature <name>`: six layers and a test, registered at the anchors."""
|
|
198
|
+
root = request.project_root.resolve()
|
|
199
|
+
manifest = load_manifest(root)
|
|
200
|
+
feature = FeatureName.parse(request.name)
|
|
201
|
+
if feature.module in manifest.features and not request.force:
|
|
202
|
+
raise UsageError(f"Feature '{feature.module}' already exists (--force to regenerate it).")
|
|
203
|
+
|
|
204
|
+
plan = plan_feature(root, manifest, feature)
|
|
205
|
+
if request.dry_run:
|
|
206
|
+
_print_plan(plan, title=f"Would create feature {feature.module}")
|
|
207
|
+
return
|
|
208
|
+
# Decided before writing: an anchor file still exactly as moarch-py left it
|
|
209
|
+
# stays "untouched" after this edit; one the user changed stays "edited".
|
|
210
|
+
untouched_edits = {
|
|
211
|
+
path
|
|
212
|
+
for path in plan.edits
|
|
213
|
+
if manifest.files.get(path) == hash_content((root / path).read_text(encoding="utf-8"))
|
|
214
|
+
}
|
|
215
|
+
plan.write(force=request.force)
|
|
216
|
+
_format_if_possible(root, list(plan.files))
|
|
217
|
+
|
|
218
|
+
_record_feature(root, manifest, feature, plan, untouched_edits)
|
|
219
|
+
console.print(f"{OK} Created feature [bold]{feature.module}[/] ({len(plan.files)} files)")
|
|
220
|
+
console.print(f" route: /api/v1/{feature.url_path} model: {feature.model_class}")
|
|
221
|
+
console.print("\n[bold]Next:[/]")
|
|
222
|
+
models_path = f"src/{manifest.package}/features/{feature.module}/models.py"
|
|
223
|
+
console.print(f" edit the columns in {models_path}")
|
|
224
|
+
if "migrations" in manifest.stack:
|
|
225
|
+
console.print(f' uv run alembic revision --autogenerate -m "create {feature.table}"')
|
|
226
|
+
console.print(" uv run alembic upgrade head")
|
|
227
|
+
console.print(" uv run pytest")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _format_if_possible(root: Path, paths: list[str]) -> None:
|
|
231
|
+
"""Formats [paths] with the project's ruff when its environment exists."""
|
|
232
|
+
if not (root / ".venv").exists():
|
|
233
|
+
return
|
|
234
|
+
try:
|
|
235
|
+
run([*RUFF, "format", *paths], cwd=root)
|
|
236
|
+
run([*RUFF, "check", "--fix", "--quiet", *paths], cwd=root)
|
|
237
|
+
except CommandFailedError as error:
|
|
238
|
+
console.print(f"{WARNING} Could not format the new files: {error}")
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _record_feature(
|
|
242
|
+
root: Path,
|
|
243
|
+
manifest: ProjectManifest,
|
|
244
|
+
feature: FeatureName,
|
|
245
|
+
plan: FilePlan,
|
|
246
|
+
untouched_edits: set[str],
|
|
247
|
+
) -> None:
|
|
248
|
+
"""Adds the feature and the hashes of what was written to `.moarch-py.yaml`."""
|
|
249
|
+
if feature.module not in manifest.features:
|
|
250
|
+
manifest.features.append(feature.module)
|
|
251
|
+
recorded = [path for path in plan.files if path not in plan.edits or path in untouched_edits]
|
|
252
|
+
manifest.record({path: (root / path).read_text(encoding="utf-8") for path in recorded})
|
|
253
|
+
(root / MANIFEST_FILE).write_text(manifest.render(), encoding="utf-8", newline="\n")
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""The packages a generated project depends on, decided by its options.
|
|
2
|
+
|
|
3
|
+
Versions are not pinned here on purpose: `init` hands these names to
|
|
4
|
+
`uv add`, which resolves the newest compatible release and writes it to
|
|
5
|
+
`pyproject.toml` as a lower bound and to `uv.lock` exactly. Every new
|
|
6
|
+
project therefore starts current, and stays reproducible from its lock.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
|
|
13
|
+
from moarch_py.options import ProjectOptions
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class ProjectDependencies:
|
|
18
|
+
"""The runtime and development packages for one project."""
|
|
19
|
+
|
|
20
|
+
runtime: list[str]
|
|
21
|
+
development: list[str]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def dependencies_for(options: ProjectOptions) -> ProjectDependencies:
|
|
25
|
+
"""Returns what `uv add` and `uv add --dev` install for [options]."""
|
|
26
|
+
runtime = [
|
|
27
|
+
# `standard` brings uvicorn, the `fastapi` CLI and email validation.
|
|
28
|
+
"fastapi[standard]",
|
|
29
|
+
"pydantic-settings",
|
|
30
|
+
"sqlalchemy[asyncio]",
|
|
31
|
+
options.database.driver_package,
|
|
32
|
+
]
|
|
33
|
+
if options.migrations:
|
|
34
|
+
runtime.append("alembic")
|
|
35
|
+
|
|
36
|
+
development = ["pytest", "pytest-asyncio", "ruff", "mypy"]
|
|
37
|
+
# The test suite always runs on in-memory SQLite, whatever the app uses,
|
|
38
|
+
# so `uv run pytest` needs no database server.
|
|
39
|
+
if options.database.driver_package != "aiosqlite":
|
|
40
|
+
development.append("aiosqlite")
|
|
41
|
+
if options.pre_commit:
|
|
42
|
+
development.append("pre-commit")
|
|
43
|
+
return ProjectDependencies(runtime=runtime, development=development)
|