PyArch-CLI 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.
Files changed (64) hide show
  1. pyarch/__init__.py +1 -0
  2. pyarch/cli/__init__.py +1 -0
  3. pyarch/cli/add.py +27 -0
  4. pyarch/cli/app.py +83 -0
  5. pyarch/cli/common.py +28 -0
  6. pyarch/cli/generate.py +34 -0
  7. pyarch/config/__init__.py +1 -0
  8. pyarch/config/manifest.py +161 -0
  9. pyarch/config/models.py +51 -0
  10. pyarch/generators/__init__.py +1 -0
  11. pyarch/generators/common/__init__.py +1 -0
  12. pyarch/generators/common/commands.py +6 -0
  13. pyarch/generators/common/filesystem.py +55 -0
  14. pyarch/generators/common/gitignore.py +65 -0
  15. pyarch/generators/common/renderer.py +32 -0
  16. pyarch/generators/integration/__init__.py +1 -0
  17. pyarch/generators/integration/auth.py +158 -0
  18. pyarch/generators/module/__init__.py +1 -0
  19. pyarch/generators/module/layered.py +186 -0
  20. pyarch/generators/project/__init__.py +1 -0
  21. pyarch/generators/project/base.py +52 -0
  22. pyarch/generators/project/layered.py +167 -0
  23. pyarch/main.py +9 -0
  24. pyarch/services/__init__.py +1 -0
  25. pyarch/services/add_integration.py +37 -0
  26. pyarch/services/create_module.py +46 -0
  27. pyarch/services/create_project.py +20 -0
  28. pyarch/templates/layered/alembic_env.py.j2 +58 -0
  29. pyarch/templates/layered/auth/config.py.j2 +30 -0
  30. pyarch/templates/layered/auth/dependencies.py.j2 +75 -0
  31. pyarch/templates/layered/auth/refresh_session_model.py.j2 +31 -0
  32. pyarch/templates/layered/auth/routes.py.j2 +51 -0
  33. pyarch/templates/layered/auth/schemas.py.j2 +31 -0
  34. pyarch/templates/layered/auth/service.py.j2 +160 -0
  35. pyarch/templates/layered/auth/tokens.py.j2 +29 -0
  36. pyarch/templates/layered/auth/user_model.py.j2 +52 -0
  37. pyarch/templates/layered/auth/utils.py.j2 +70 -0
  38. pyarch/templates/layered/config.py.j2 +14 -0
  39. pyarch/templates/layered/env.example.j2 +7 -0
  40. pyarch/templates/layered/models_init.py.j2 +5 -0
  41. pyarch/templates/layered/module/module_model.py.j2 +25 -0
  42. pyarch/templates/layered/module/module_repo.py.j2 +49 -0
  43. pyarch/templates/layered/module/module_router.py.j2 +87 -0
  44. pyarch/templates/layered/module/module_router_protected.py.j2 +97 -0
  45. pyarch/templates/layered/module/module_schema.py.j2 +30 -0
  46. pyarch/templates/layered/module/module_service.py.j2 +76 -0
  47. pyarch/templates/layered/mongodb/config.py.j2 +15 -0
  48. pyarch/templates/layered/mongodb/conftest.py.j2 +36 -0
  49. pyarch/templates/layered/mongodb/env.example.j2 +2 -0
  50. pyarch/templates/layered/mongodb/module/module_model.py.j2 +11 -0
  51. pyarch/templates/layered/mongodb/module/module_repo.py.j2 +99 -0
  52. pyarch/templates/layered/mongodb/module/module_router.py.j2 +97 -0
  53. pyarch/templates/layered/mongodb/module/module_service.py.j2 +69 -0
  54. pyarch/templates/layered/mongodb/session.py.j2 +14 -0
  55. pyarch/templates/layered/router.py.j2 +8 -0
  56. pyarch/templates/layered/session.py.j2 +33 -0
  57. pyarch/templates/project/base/README.md.j2 +22 -0
  58. pyarch/templates/project/base/conftest.py.j2 +101 -0
  59. pyarch/templates/project/base/main.py.j2 +11 -0
  60. pyarch_cli-0.1.0.dist-info/METADATA +378 -0
  61. pyarch_cli-0.1.0.dist-info/RECORD +64 -0
  62. pyarch_cli-0.1.0.dist-info/WHEEL +4 -0
  63. pyarch_cli-0.1.0.dist-info/entry_points.txt +2 -0
  64. pyarch_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
pyarch/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
pyarch/cli/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """PyArch command-line interface."""
pyarch/cli/add.py ADDED
@@ -0,0 +1,27 @@
1
+ from typing import Annotated
2
+
3
+ import typer
4
+
5
+ from pyarch.cli.common import console, execute_or_exit
6
+ from pyarch.services.add_integration import add_integration
7
+
8
+
9
+ app = typer.Typer(no_args_is_help=True)
10
+
11
+
12
+ @app.command("integration")
13
+ def add_integration_command(
14
+ integration_name: Annotated[
15
+ str,
16
+ typer.Argument(help="Integration name."),
17
+ ],
18
+ ) -> None:
19
+ """Add a supported integration to the current project."""
20
+
21
+ project_root, created_files = execute_or_exit(lambda: add_integration(integration_name))
22
+ console.print(
23
+ f"[green]Added integration[/green] [bold]{integration_name}[/bold]"
24
+ f" in {project_root}"
25
+ )
26
+ for file_path in created_files:
27
+ console.print(f" [dim]{file_path.relative_to(project_root)}[/dim]")
pyarch/cli/app.py ADDED
@@ -0,0 +1,83 @@
1
+ from typing import Annotated
2
+
3
+ import typer
4
+ from rich.table import Table
5
+
6
+ from pyarch.cli.add import app as add_app
7
+ from pyarch.cli.common import console, execute_or_exit
8
+ from pyarch.cli.generate import app as generate_app
9
+ from pyarch.config.manifest import find_project_root, load_manifest
10
+ from pyarch.config.models import DatabaseEngine
11
+ from pyarch.services.create_project import create_project
12
+
13
+
14
+ app = typer.Typer(
15
+ name="pyarch",
16
+ help="Generate and extend Layered FastAPI projects.",
17
+ no_args_is_help=True,
18
+ )
19
+ app.add_typer(
20
+ generate_app,
21
+ name="generate",
22
+ help="Generate project components.",
23
+ )
24
+ app.add_typer(
25
+ add_app,
26
+ name="add",
27
+ help="Add project integrations.",
28
+ )
29
+
30
+
31
+ @app.command("init")
32
+ def init_project(
33
+ project_name: Annotated[
34
+ str,
35
+ typer.Argument(help="New project directory name."),
36
+ ],
37
+ database: Annotated[
38
+ DatabaseEngine,
39
+ typer.Option(
40
+ "--database",
41
+ "-d",
42
+ help="Database backend.",
43
+ case_sensitive=False,
44
+ ),
45
+ ] = DatabaseEngine.POSTGRES,
46
+ ) -> None:
47
+ """Create a new Layered FastAPI project."""
48
+
49
+ console.print(
50
+ f"Creating [bold]{project_name}[/bold] "
51
+ f"with [cyan]{database.value}[/cyan]..."
52
+ )
53
+ project_dir = execute_or_exit(
54
+ lambda: create_project(project_name, database)
55
+ )
56
+ console.print(f"[bold green]Project created:[/bold green] {project_dir}")
57
+
58
+
59
+ @app.command()
60
+ def info() -> None:
61
+ """Show information from the current project's manifest."""
62
+
63
+ project_root, manifest = execute_or_exit(load_current_manifest)
64
+
65
+ table = Table(title="PyArch project", show_header=False)
66
+ table.add_column("Field", style="bold")
67
+ table.add_column("Value")
68
+ table.add_row("Root", str(project_root))
69
+ table.add_row("Name", manifest.project.name)
70
+ table.add_row("Architecture", manifest.project.architecture.value)
71
+ table.add_row("Database", manifest.database.engine.value)
72
+ table.add_row("DB access", manifest.database.access.value)
73
+ table.add_row("Modules", ", ".join(manifest.state.modules) or "none")
74
+ table.add_row(
75
+ "Integrations",
76
+ ", ".join(manifest.state.integrations) or "none",
77
+ )
78
+ console.print(table)
79
+
80
+
81
+ def load_current_manifest():
82
+ project_root = find_project_root()
83
+ return project_root, load_manifest(project_root)
pyarch/cli/common.py ADDED
@@ -0,0 +1,28 @@
1
+ import subprocess
2
+ from collections.abc import Callable
3
+ from typing import Never, TypeVar
4
+
5
+ import typer
6
+ from rich.console import Console
7
+
8
+
9
+ console = Console()
10
+ ResultT = TypeVar("ResultT")
11
+
12
+
13
+ def execute_or_exit(action: Callable[[], ResultT]) -> ResultT:
14
+ try:
15
+ return action()
16
+ except (
17
+ FileExistsError,
18
+ FileNotFoundError,
19
+ NotImplementedError,
20
+ subprocess.CalledProcessError,
21
+ ValueError,
22
+ ) as error:
23
+ abort(str(error))
24
+
25
+
26
+ def abort(message: str) -> Never:
27
+ console.print(f"[bold red]Error:[/bold red] {message}")
28
+ raise typer.Exit(code=1)
pyarch/cli/generate.py ADDED
@@ -0,0 +1,34 @@
1
+ from typing import Annotated
2
+
3
+ import typer
4
+
5
+ from pyarch.cli.common import console, execute_or_exit
6
+ from pyarch.services.create_module import create_module
7
+
8
+
9
+ app = typer.Typer(no_args_is_help=True)
10
+
11
+
12
+ @app.command("module")
13
+ def generate_module(
14
+ module_name: Annotated[str, typer.Argument(help="Module name.")],
15
+ protected: Annotated[
16
+ bool,
17
+ typer.Option(
18
+ "--protected",
19
+ help="Protect generated routes with the auth integration.",
20
+ ),
21
+ ] = False,
22
+ ) -> None:
23
+ """Generate a CRUD module using the project's manifest."""
24
+
25
+ project_root, created_files = execute_or_exit(
26
+ lambda: create_module(module_name, protected=protected)
27
+ )
28
+
29
+ console.print(
30
+ f"[green]Created module[/green] [bold]{module_name}[/bold] "
31
+ f"in {project_root}"
32
+ )
33
+ for file_path in created_files:
34
+ console.print(f" [dim]{file_path.relative_to(project_root)}[/dim]")
@@ -0,0 +1 @@
1
+ """PyArch project configuration."""
@@ -0,0 +1,161 @@
1
+ from pathlib import Path
2
+ from typing import Any
3
+
4
+ from tomlkit import document, dumps, load, table
5
+
6
+ from pyarch import __version__
7
+ from pyarch.config.models import (
8
+ Architecture,
9
+ DatabaseAccess,
10
+ DatabaseEngine,
11
+ DatabaseSettings,
12
+ ProjectManifest,
13
+ ProjectPaths,
14
+ ProjectSettings,
15
+ ProjectState,
16
+ )
17
+
18
+
19
+ MANIFEST_NAME = "pyarch.toml"
20
+ SCHEMA_VERSION = 1
21
+
22
+
23
+ class ManifestError(ValueError):
24
+ pass
25
+
26
+
27
+ def create_manifest(
28
+ project_dir: Path,
29
+ project_name: str,
30
+ database: DatabaseEngine,
31
+ ) -> ProjectManifest:
32
+ manifest = ProjectManifest(
33
+ schema_version=SCHEMA_VERSION,
34
+ pyarch_version=__version__,
35
+ project=ProjectSettings(name=project_name),
36
+ database=DatabaseSettings(engine=database),
37
+ paths=ProjectPaths(
38
+ migrations=(
39
+ None if database is DatabaseEngine.MONGODB else "alembic"
40
+ )
41
+ ),
42
+ )
43
+ save_manifest(project_dir, manifest)
44
+ return manifest
45
+
46
+
47
+ def find_project_root(start: Path | None = None) -> Path:
48
+ current = (start or Path.cwd()).resolve()
49
+ if current.is_file():
50
+ current = current.parent
51
+
52
+ for directory in (current, *current.parents):
53
+ if (directory / MANIFEST_NAME).is_file():
54
+ return directory
55
+
56
+ raise FileNotFoundError(
57
+ f"{MANIFEST_NAME} was not found in {current} or its parent directories"
58
+ )
59
+
60
+
61
+ def load_manifest(project_dir: Path) -> ProjectManifest:
62
+ manifest_path = project_dir / MANIFEST_NAME
63
+ if not manifest_path.is_file():
64
+ raise FileNotFoundError(f"Manifest does not exist: {manifest_path}")
65
+
66
+ with manifest_path.open("r", encoding="utf-8") as manifest_file:
67
+ raw = load(manifest_file).unwrap()
68
+
69
+ try:
70
+ schema_version = int(raw["schema_version"])
71
+ if schema_version != SCHEMA_VERSION:
72
+ raise ManifestError(
73
+ f"Unsupported manifest schema version: {schema_version}"
74
+ )
75
+
76
+ project_data = require_table(raw, "project")
77
+ database_data = require_table(raw, "database")
78
+ paths_data = require_table(raw, "paths")
79
+ state_data = require_table(raw, "state")
80
+
81
+ return ProjectManifest(
82
+ schema_version=schema_version,
83
+ pyarch_version=str(raw["pyarch_version"]),
84
+ project=ProjectSettings(
85
+ name=str(project_data["name"]),
86
+ architecture=Architecture(str(project_data["architecture"])),
87
+ ),
88
+ database=DatabaseSettings(
89
+ engine=DatabaseEngine(str(database_data["engine"])),
90
+ access=DatabaseAccess(str(database_data["access"])),
91
+ ),
92
+ paths=ProjectPaths(
93
+ application=str(paths_data["application"]),
94
+ tests=str(paths_data["tests"]),
95
+ migrations=(
96
+ str(paths_data["migrations"])
97
+ if "migrations" in paths_data
98
+ else None
99
+ ),
100
+ ),
101
+ state=ProjectState(
102
+ modules=require_string_list(state_data, "modules"),
103
+ integrations=require_string_list(state_data, "integrations"),
104
+ ),
105
+ )
106
+ except (KeyError, TypeError, ValueError) as error:
107
+ if isinstance(error, ManifestError):
108
+ raise
109
+ raise ManifestError(f"Invalid {MANIFEST_NAME}: {error}") from error
110
+
111
+
112
+ def save_manifest(project_dir: Path, manifest: ProjectManifest) -> Path:
113
+ manifest_path = project_dir / MANIFEST_NAME
114
+ temporary_path = manifest_path.with_suffix(".toml.tmp")
115
+
116
+ doc = document()
117
+ doc.add("schema_version", manifest.schema_version)
118
+ doc.add("pyarch_version", __version__)
119
+
120
+ project = table()
121
+ project.add("name", manifest.project.name)
122
+ project.add("architecture", manifest.project.architecture.value)
123
+ doc.add("project", project)
124
+
125
+ database = table()
126
+ database.add("engine", manifest.database.engine.value)
127
+ database.add("access", manifest.database.access.value)
128
+ doc.add("database", database)
129
+
130
+ paths = table()
131
+ paths.add("application", manifest.paths.application)
132
+ paths.add("tests", manifest.paths.tests)
133
+ if manifest.paths.migrations is not None:
134
+ paths.add("migrations", manifest.paths.migrations)
135
+ doc.add("paths", paths)
136
+
137
+ state = table()
138
+ state.add("modules", manifest.state.modules)
139
+ state.add("integrations", manifest.state.integrations)
140
+ doc.add("state", state)
141
+
142
+ temporary_path.write_text(dumps(doc), encoding="utf-8")
143
+ temporary_path.replace(manifest_path)
144
+ manifest.pyarch_version = __version__
145
+ return manifest_path
146
+
147
+
148
+ def require_table(raw: dict[str, Any], key: str) -> dict[str, Any]:
149
+ value = raw[key]
150
+ if not isinstance(value, dict):
151
+ raise ManifestError(f"{key!r} must be a TOML table")
152
+ return value
153
+
154
+
155
+ def require_string_list(data: dict[str, Any], key: str) -> list[str]:
156
+ value = data[key]
157
+ if not isinstance(value, list) or not all(
158
+ isinstance(item, str) for item in value
159
+ ):
160
+ raise ManifestError(f"{key!r} must be an array of strings")
161
+ return list(value)
@@ -0,0 +1,51 @@
1
+ from dataclasses import dataclass, field
2
+ from enum import StrEnum
3
+
4
+
5
+ class Architecture(StrEnum):
6
+ LAYERED = "layered"
7
+
8
+
9
+ class DatabaseEngine(StrEnum):
10
+ POSTGRES = "postgres"
11
+ SQLITE = "sqlite"
12
+ MONGODB = "mongodb"
13
+
14
+
15
+ class DatabaseAccess(StrEnum):
16
+ SYNC = "sync"
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class ProjectSettings:
21
+ name: str
22
+ architecture: Architecture = Architecture.LAYERED
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class DatabaseSettings:
27
+ engine: DatabaseEngine
28
+ access: DatabaseAccess = DatabaseAccess.SYNC
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class ProjectPaths:
33
+ application: str = "app"
34
+ tests: str = "tests"
35
+ migrations: str | None = "alembic"
36
+
37
+
38
+ @dataclass(slots=True)
39
+ class ProjectState:
40
+ modules: list[str] = field(default_factory=list)
41
+ integrations: list[str] = field(default_factory=list)
42
+
43
+
44
+ @dataclass(slots=True)
45
+ class ProjectManifest:
46
+ schema_version: int
47
+ pyarch_version: str
48
+ project: ProjectSettings
49
+ database: DatabaseSettings
50
+ paths: ProjectPaths = field(default_factory=ProjectPaths)
51
+ state: ProjectState = field(default_factory=ProjectState)
@@ -0,0 +1 @@
1
+ """Project and module generators."""
@@ -0,0 +1 @@
1
+ """Shared generator utilities."""
@@ -0,0 +1,6 @@
1
+ import subprocess
2
+ from pathlib import Path
3
+
4
+
5
+ def run_command(*command: str, cwd: Path | None = None) -> None:
6
+ subprocess.run(command, cwd=cwd or Path.cwd(), check=True)
@@ -0,0 +1,55 @@
1
+ from pathlib import Path
2
+
3
+
4
+ def create_empty_dir(directory: Path) -> Path:
5
+ directory.mkdir(parents=True, exist_ok=True)
6
+ return directory
7
+
8
+
9
+ def create_empty_file(file: Path) -> Path:
10
+ file.parent.mkdir(parents=True, exist_ok=True)
11
+ file.touch(exist_ok=True)
12
+ return file
13
+
14
+
15
+ def init_py_module(directory: Path) -> Path:
16
+ directory.mkdir(parents=True, exist_ok=True)
17
+ init = directory / "__init__.py"
18
+ init.touch(exist_ok=True)
19
+ return init
20
+
21
+
22
+ def create_module_path(directory: Path) -> Path:
23
+ create_empty_dir(directory)
24
+ init_py_module(directory)
25
+ return directory
26
+
27
+
28
+ def insert_line_before_marker(
29
+ file_path: Path,
30
+ marker: str,
31
+ line: str,
32
+ ) -> bool:
33
+ content = file_path.read_text(encoding="utf-8")
34
+
35
+ if line in content.splitlines():
36
+ return False
37
+
38
+ if marker not in content:
39
+ raise ValueError(f"Marker {marker!r} was not found in {file_path}")
40
+
41
+ updated_content = content.replace(marker, f"{line}\n{marker}", 1)
42
+ file_path.write_text(updated_content, encoding="utf-8")
43
+ return True
44
+
45
+
46
+ def append_text_once(file_path: Path, marker: str, text: str) -> bool:
47
+ content = file_path.read_text(encoding="utf-8") if file_path.exists() else ""
48
+
49
+ if marker in content:
50
+ return False
51
+
52
+ separator = "" if not content or content.endswith("\n") else "\n"
53
+ file_path.parent.mkdir(parents=True, exist_ok=True)
54
+ file_path.write_text(f"{content}{separator}{text}", encoding="utf-8")
55
+ return True
@@ -0,0 +1,65 @@
1
+ from pathlib import Path
2
+
3
+
4
+ BASE_GITIGNORE_ENTRIES = (
5
+ ".env",
6
+ ".env.*",
7
+ "!.env.example",
8
+ ".venv",
9
+ ".pytest_cache/",
10
+ ".ruff_cache/",
11
+ ".mypy_cache/",
12
+ ".coverage",
13
+ "htmlcov/",
14
+ "*.db",
15
+ "*.sqlite",
16
+ "*.sqlite3",
17
+ "dist/",
18
+ "build/",
19
+ "*.egg-info",
20
+ )
21
+
22
+ AUTH_GITIGNORE_ENTRIES = (
23
+ "certs/",
24
+ "*.pem",
25
+ "*.key",
26
+ )
27
+
28
+
29
+ def ensure_gitignore_entries(
30
+ project_dir: Path,
31
+ section_name: str,
32
+ entries: tuple[str, ...],
33
+ ) -> Path:
34
+ gitignore_path = project_dir / ".gitignore"
35
+ content = gitignore_path.read_text(encoding="utf-8") if gitignore_path.exists() else ""
36
+ lines = content.splitlines()
37
+ existing_entries = {line.strip() for line in lines}
38
+
39
+ missing_entries = [entry for entry in entries if entry not in existing_entries]
40
+ if not missing_entries:
41
+ return gitignore_path
42
+
43
+ marker = f"# pyarch:{section_name}"
44
+ if marker in lines:
45
+ insert_at = find_section_end(lines, marker)
46
+ updated_lines = [*lines[:insert_at], *missing_entries, *lines[insert_at:]]
47
+ else:
48
+ updated_lines = [*lines]
49
+ if updated_lines and updated_lines[-1] != "":
50
+ updated_lines.append("")
51
+ updated_lines.extend((marker, *missing_entries))
52
+
53
+ gitignore_path.write_text("\n".join(updated_lines) + "\n", encoding="utf-8")
54
+ return gitignore_path
55
+
56
+
57
+ def find_section_end(lines: list[str], marker: str) -> int:
58
+ marker_index = lines.index(marker)
59
+
60
+ for index in range(marker_index + 1, len(lines)):
61
+ line = lines[index]
62
+ if line == "" or line.startswith("# pyarch:"):
63
+ return index
64
+
65
+ return len(lines)
@@ -0,0 +1,32 @@
1
+ from pathlib import Path
2
+
3
+ from jinja2 import Environment, FileSystemLoader, StrictUndefined
4
+
5
+
6
+ TEMPLATES_DIR = Path(__file__).resolve().parents[2] / "templates"
7
+
8
+ environment = Environment(
9
+ loader=FileSystemLoader(TEMPLATES_DIR),
10
+ undefined=StrictUndefined,
11
+ autoescape=False,
12
+ trim_blocks=True,
13
+ lstrip_blocks=True,
14
+ keep_trailing_newline=True,
15
+ )
16
+
17
+
18
+ def render_template(template_name: str, **context: object) -> str:
19
+ template = environment.get_template(template_name)
20
+ return template.render(**context)
21
+
22
+
23
+ def create_file_from_template(
24
+ template_name: str,
25
+ output_path: Path,
26
+ **context: object,
27
+ ) -> Path:
28
+ content = render_template(template_name, **context)
29
+
30
+ output_path.parent.mkdir(parents=True, exist_ok=True)
31
+ output_path.write_text(content, encoding="utf-8")
32
+ return output_path
@@ -0,0 +1 @@
1
+