scaffold-ca-python 0.5.0__py3-none-any.whl → 1.0.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 (114) hide show
  1. scaffold_ca_python/cli.py +15 -10
  2. scaffold_ca_python/commands/_entry_point_rules.py +13 -18
  3. scaffold_ca_python/commands/_shared.py +119 -23
  4. scaffold_ca_python/commands/add_mcp_tool.py +56 -63
  5. scaffold_ca_python/commands/delete_module.py +22 -35
  6. scaffold_ca_python/commands/generate_driven_adapter.py +51 -32
  7. scaffold_ca_python/commands/generate_entry_point.py +29 -75
  8. scaffold_ca_python/commands/generate_helper.py +11 -24
  9. scaffold_ca_python/commands/generate_model.py +12 -24
  10. scaffold_ca_python/commands/generate_pipeline.py +25 -39
  11. scaffold_ca_python/commands/generate_project.py +43 -47
  12. scaffold_ca_python/commands/generate_use_case.py +87 -26
  13. scaffold_ca_python/commands/update_project.py +12 -26
  14. scaffold_ca_python/commands/validate_structure.py +6 -21
  15. scaffold_ca_python/core/errors.py +5 -0
  16. scaffold_ca_python/core/file_writer.py +3 -5
  17. scaffold_ca_python/core/mcp_tool_spec.py +16 -21
  18. scaffold_ca_python/core/module_builder.py +36 -31
  19. scaffold_ca_python/core/module_locator.py +2 -2
  20. scaffold_ca_python/core/name_utils.py +22 -17
  21. scaffold_ca_python/core/project_detector.py +12 -3
  22. scaffold_ca_python/core/pyproject_writer.py +49 -175
  23. scaffold_ca_python/core/structure_validator.py +1 -1
  24. scaffold_ca_python/core/template_renderer.py +3 -7
  25. scaffold_ca_python/core/version.py +17 -0
  26. scaffold_ca_python/core/wiring_utils.py +161 -0
  27. scaffold_ca_python/factory/__init__.py +1 -2
  28. scaffold_ca_python/factory/dependencies.py +18 -0
  29. scaffold_ca_python/factory/driven_adapters/base.py +84 -5
  30. scaffold_ca_python/factory/driven_adapters/da_generic.py +21 -49
  31. scaffold_ca_python/factory/driven_adapters/da_rest_consumer.py +48 -54
  32. scaffold_ca_python/factory/driven_adapters/da_secrets.py +12 -56
  33. scaffold_ca_python/factory/entry_points/base.py +34 -6
  34. scaffold_ca_python/factory/entry_points/ep_agent.py +38 -73
  35. scaffold_ca_python/factory/entry_points/ep_generic.py +15 -58
  36. scaffold_ca_python/factory/entry_points/ep_mcp.py +36 -113
  37. scaffold_ca_python/factory/entry_points/ep_restapi.py +29 -109
  38. scaffold_ca_python/factory/pipelines/__init__.py +2 -0
  39. scaffold_ca_python/factory/pipelines/pipeline_factory.py +4 -3
  40. scaffold_ca_python/factory/simple/delete_module_factory.py +67 -13
  41. scaffold_ca_python/factory/simple/helper_factory.py +10 -47
  42. scaffold_ca_python/factory/simple/model_factory.py +15 -37
  43. scaffold_ca_python/factory/simple/use_case_factory.py +48 -36
  44. scaffold_ca_python/models/context.py +23 -4
  45. scaffold_ca_python/models/file_operation.py +1 -2
  46. scaffold_ca_python/models/layer.py +4 -4
  47. scaffold_ca_python/models/options.py +1 -7
  48. scaffold_ca_python/templates/driven_adapter/generic/adapter.py.jinja2 +18 -2
  49. scaffold_ca_python/templates/driven_adapter/generic/test_adapter.py.jinja2 +1 -1
  50. scaffold_ca_python/templates/driven_adapter/rest_consumer/rest_consumer.py.jinja2 +36 -13
  51. scaffold_ca_python/templates/driven_adapter/rest_consumer/rest_consumer_config.py.jinja2 +22 -0
  52. scaffold_ca_python/templates/driven_adapter/rest_consumer/rest_consumer_settings.py.jinja2 +27 -0
  53. scaffold_ca_python/templates/driven_adapter/rest_consumer/test_rest_consumer.py.jinja2 +10 -1
  54. scaffold_ca_python/templates/driven_adapter/secrets/secrets_adapter.py.jinja2 +24 -13
  55. scaffold_ca_python/templates/driven_adapter/secrets/secrets_settings.py.jinja2 +20 -0
  56. scaffold_ca_python/templates/driven_adapter/wiring_test_stub.py.jinja2 +11 -0
  57. scaffold_ca_python/templates/entry_point/agent/__init__.py.jinja2 +1 -1
  58. scaffold_ca_python/templates/entry_point/agent/a2a_config.py.jinja2 +53 -0
  59. scaffold_ca_python/templates/entry_point/agent/agent_card.py.jinja2 +40 -0
  60. scaffold_ca_python/templates/entry_point/agent/agent_executor.py.jinja2 +64 -0
  61. scaffold_ca_python/templates/entry_point/agent/agent_settings.py.jinja2 +32 -0
  62. scaffold_ca_python/templates/entry_point/agent/app.py.jinja2 +47 -0
  63. scaffold_ca_python/templates/entry_point/agent/routes.py.jinja2 +17 -0
  64. scaffold_ca_python/templates/entry_point/agent/server.py.jinja2 +17 -0
  65. scaffold_ca_python/templates/entry_point/agent/test_agent_card.py.jinja2 +54 -0
  66. scaffold_ca_python/templates/entry_point/agent/test_agent_executor.py.jinja2 +75 -0
  67. scaffold_ca_python/templates/entry_point/agent/test_app.py.jinja2 +76 -0
  68. scaffold_ca_python/templates/entry_point/agent/test_routes.py.jinja2 +23 -0
  69. scaffold_ca_python/templates/entry_point/generic/entrypoint_main.py.jinja2 +7 -2
  70. scaffold_ca_python/templates/entry_point/generic/generic_app.py.jinja2 +19 -0
  71. scaffold_ca_python/templates/entry_point/generic/handler.py.jinja2 +1 -1
  72. scaffold_ca_python/templates/entry_point/generic/test_handler.py.jinja2 +1 -2
  73. scaffold_ca_python/templates/entry_point/mcp/app.py.jinja2 +19 -24
  74. scaffold_ca_python/templates/entry_point/mcp/prompts.py.jinja2 +3 -7
  75. scaffold_ca_python/templates/entry_point/mcp/resources.py.jinja2 +3 -7
  76. scaffold_ca_python/templates/entry_point/mcp/routes.py.jinja2 +1 -1
  77. scaffold_ca_python/templates/entry_point/mcp/server.py.jinja2 +1 -3
  78. scaffold_ca_python/templates/entry_point/mcp/test_app.py.jinja2 +4 -1
  79. scaffold_ca_python/templates/entry_point/mcp/tools.py.jinja2 +4 -7
  80. scaffold_ca_python/templates/entry_point/restapi/app.py.jinja2 +9 -20
  81. scaffold_ca_python/templates/entry_point/restapi/rest_controller.py.jinja2 +16 -9
  82. scaffold_ca_python/templates/entry_point/restapi/test_app.py.jinja2 +1 -1
  83. scaffold_ca_python/templates/entry_point/restapi/test_rest_controller.py.jinja2 +10 -8
  84. scaffold_ca_python/templates/helper/helper.py.jinja2 +14 -3
  85. scaffold_ca_python/templates/project/README.jinja2 +21 -0
  86. scaffold_ca_python/templates/project/application/config/config.py.jinja2 +6 -1
  87. scaffold_ca_python/templates/project/application/config/usecases/__init__.py.jinja2 +2 -0
  88. scaffold_ca_python/templates/project/application/config/wiring.py.jinja2 +16 -0
  89. scaffold_ca_python/templates/project/dockerfile.jinja2 +3 -1
  90. scaffold_ca_python/templates/project/mypy_ini.jinja2 +1 -0
  91. scaffold_ca_python/templates/project/pyproject_toml.jinja2 +6 -2
  92. scaffold_ca_python/templates/project/test_config.py.jinja2 +18 -0
  93. scaffold_ca_python/templates/project/test_main.py.jinja2 +32 -0
  94. scaffold_ca_python/templates/project/test_wiring.py.jinja2 +26 -0
  95. scaffold_ca_python/templates/use_case/test_use_case.py.jinja2 +17 -3
  96. scaffold_ca_python/templates/use_case/test_use_case_factory.py.jinja2 +22 -0
  97. scaffold_ca_python/templates/use_case/use_case.py.jinja2 +17 -2
  98. scaffold_ca_python/templates/use_case/use_case_factory.py.jinja2 +24 -0
  99. scaffold_ca_python/templates/use_case/wiring_test_stub.py.jinja2 +11 -0
  100. {scaffold_ca_python-0.5.0.dist-info → scaffold_ca_python-1.0.0.dist-info}/METADATA +54 -4
  101. scaffold_ca_python-1.0.0.dist-info/RECORD +149 -0
  102. {scaffold_ca_python-0.5.0.dist-info → scaffold_ca_python-1.0.0.dist-info}/WHEEL +1 -1
  103. scaffold_ca_python/templates/entry_point/agent/agent.py.jinja2 +0 -50
  104. scaffold_ca_python/templates/entry_point/agent/card.py.jinja2 +0 -15
  105. scaffold_ca_python/templates/entry_point/agent/entrypoint_main.py.jinja2 +0 -13
  106. scaffold_ca_python/templates/entry_point/agent/test_agent.py.jinja2 +0 -20
  107. scaffold_ca_python/templates/entry_point/restapi/health.py.jinja2 +0 -13
  108. scaffold_ca_python/templates/project/application/config/container.py.jinja2 +0 -17
  109. scaffold_ca_python/templates/project/application/config/driven_adapters_container.py.jinja2 +0 -14
  110. scaffold_ca_python/templates/project/application/config/resource_container.py.jinja2 +0 -17
  111. scaffold_ca_python/templates/project/application/config/usecases_container.py.jinja2 +0 -16
  112. scaffold_ca_python-0.5.0.dist-info/RECORD +0 -130
  113. {scaffold_ca_python-0.5.0.dist-info → scaffold_ca_python-1.0.0.dist-info}/entry_points.txt +0 -0
  114. {scaffold_ca_python-0.5.0.dist-info → scaffold_ca_python-1.0.0.dist-info}/licenses/LICENSE +0 -0
scaffold_ca_python/cli.py CHANGED
@@ -20,16 +20,21 @@ app = typer.Typer(
20
20
  rich_markup_mode="rich",
21
21
  )
22
22
 
23
- generate_project.register(app)
24
- generate_model.register(app)
25
- generate_use_case.register(app)
26
- generate_driven_adapter.register(app)
27
- generate_entry_point.register(app)
28
- generate_helper.register(app)
29
- generate_pipeline.register(app)
30
- delete_module.register(app)
31
- update_project.register(app)
32
- validate_structure.register(app)
23
+ _COMMAND_MODULES = (
24
+ generate_project,
25
+ generate_model,
26
+ generate_use_case,
27
+ generate_driven_adapter,
28
+ generate_entry_point,
29
+ generate_helper,
30
+ generate_pipeline,
31
+ update_project,
32
+ delete_module,
33
+ validate_structure,
34
+ )
35
+
36
+ for _mod in _COMMAND_MODULES:
37
+ _mod.register(app)
33
38
 
34
39
 
35
40
  @app.callback(invoke_without_command=True)
@@ -3,16 +3,10 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from pathlib import Path
6
- from typing import TYPE_CHECKING
7
6
 
8
- import typer
9
-
10
- from scaffold_ca_python.commands._shared import console
7
+ from scaffold_ca_python.commands._shared import fail
11
8
  from scaffold_ca_python.factory.entry_points.base import EntryPointFactory, EntryPointFlag
12
9
 
13
- if TYPE_CHECKING:
14
- pass
15
-
16
10
 
17
11
  def check_flags(
18
12
  type_key: str,
@@ -28,26 +22,27 @@ def check_flags(
28
22
  msg = f"{flag.label} {flag.verb} only valid with --type {types_supporting[0]}."
29
23
  else:
30
24
  msg = f"{flag.label} {flag.verb} not valid with --type {type_key}."
31
- console.print(f"[red]Error:[/red] {msg}")
32
- raise typer.Exit(code=1)
25
+ fail(msg)
33
26
 
34
27
 
35
28
  def check_conflicts(
36
29
  project_root: Path,
37
- pkg: str,
30
+ src_pkg_root: Path,
38
31
  type_key: str,
39
32
  factory: type[EntryPointFactory],
33
+ registry: dict[str, type[EntryPointFactory]],
40
34
  ) -> None:
41
35
  """Exit with an error if any conflicting entry-point directory already exists."""
42
- pkg_ep = project_root / "src" / pkg / "infrastructure" / "entry_points"
36
+ pkg_ep = src_pkg_root / "infrastructure" / "entry_points"
43
37
  for conflict in factory.conflicts:
44
- conflict_dir = pkg_ep / conflict.subdir
38
+ other = registry.get(conflict.type_key)
39
+ if other is None:
40
+ continue
41
+ conflict_subdir = other.subdir.split("/")[0]
42
+ conflict_dir = pkg_ep / conflict_subdir
45
43
  if conflict_dir.exists():
46
44
  rel = conflict_dir.relative_to(project_root)
47
- console.print(
48
- f"[red]Error:[/red] Incompatible entry point '[bold]{conflict.label}[/bold]' "
49
- f"already exists at: {rel}\n"
50
- "[dim]Hint:[/dim] A project may have only one entry-point type. "
51
- f"Remove '{rel}' before adding {type_key}."
45
+ fail(
46
+ f"Incompatible entry point '[bold]{conflict.type_key}[/bold]' already exists at: {rel}",
47
+ hint=f"A project may have only one entry-point type. Remove '{rel}' before adding {type_key}.",
52
48
  )
53
- raise typer.Exit(code=1)
@@ -2,33 +2,50 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import subprocess
5
6
  from collections.abc import Callable, Iterable
6
7
  from pathlib import Path
7
- from typing import TYPE_CHECKING, Literal, NoReturn
8
+ from typing import TYPE_CHECKING, Annotated, Literal, NoReturn, cast, overload
8
9
 
9
10
  import typer
10
11
  from rich.console import Console
11
12
  from rich.markup import escape
12
13
  from rich.tree import Tree
13
14
 
14
- from scaffold_ca_python.core.name_utils import ScaffoldError
15
- from scaffold_ca_python.core.project_detector import find_project_root
15
+ from scaffold_ca_python.core.errors import ScaffoldError
16
+ from scaffold_ca_python.core.project_detector import find_project_root, load_project_context
16
17
 
17
18
  if TYPE_CHECKING:
18
19
  from scaffold_ca_python.core.module_builder import ModuleBuilder
19
20
  from scaffold_ca_python.factory import ModuleFactory
21
+ from scaffold_ca_python.models.context import ProjectContext
20
22
 
21
23
  console = Console()
22
24
 
23
25
  PROJECT_NOT_FOUND = "No scaffold-ca-python project found. Run 'scaffold ca' first."
24
26
 
25
27
 
26
- def fail(message: str, hint: str | None = None) -> NoReturn:
27
- """Print an error (and optional hint) then exit with code 1."""
28
+ def fail(message: str, hint: str | None = None, *, code: int = 1) -> NoReturn:
29
+ """Print an error (and optional hint) then exit."""
28
30
  console.print(f"[red]Error:[/red] {message}")
29
31
  if hint is not None:
30
32
  console.print(f"[dim]Hint:[/dim] {hint}")
31
- raise typer.Exit(code=1)
33
+ raise typer.Exit(code=code) from None
34
+
35
+
36
+ def dry_run_option(help: str = "Preview without writing.") -> typer.models.OptionInfo:
37
+ """Return a ``--dry-run/--no-dry-run`` Typer option."""
38
+ return cast(
39
+ typer.models.OptionInfo,
40
+ typer.Option("--dry-run/--no-dry-run", help=help, rich_help_panel="Options", show_default=True),
41
+ )
42
+
43
+
44
+ DryRun = Annotated[bool, dry_run_option("Preview without writing.")]
45
+ DryRunDelete = Annotated[bool, dry_run_option("Preview deletion without removing files.")]
46
+ DryRunProject = Annotated[bool, dry_run_option("Preview files without writing.")]
47
+ DryRunValidate = Annotated[bool, dry_run_option("Print results but always exit 0.")]
48
+ DryRunUpdate = Annotated[bool, dry_run_option("Preview commands without running.")]
32
49
 
33
50
 
34
51
  def require_project_root(not_found_message: str | None = PROJECT_NOT_FOUND) -> Path:
@@ -41,11 +58,7 @@ def require_project_root(not_found_message: str | None = PROJECT_NOT_FOUND) -> P
41
58
  try:
42
59
  return find_project_root()
43
60
  except ScaffoldError as exc:
44
- if not_found_message is None:
45
- console.print(f"[red]Error:[/red] {exc}")
46
- else:
47
- console.print(f"[red]Error:[/red] {not_found_message}")
48
- raise typer.Exit(code=1) from None
61
+ fail(not_found_message or str(exc))
49
62
 
50
63
 
51
64
  def validate_name_or_exit(name: str, validator: Callable[[str], object]) -> None:
@@ -86,24 +99,107 @@ def print_pending_dependencies(builder: ModuleBuilder) -> None:
86
99
  """Print dry-run summaries for queued dependency injections."""
87
100
  if builder.pending_dependencies:
88
101
  target = escape("[project.dependencies]")
89
- console.print(f"[dim]Would add to {target}: {', '.join(builder.pending_dependencies)}[/dim]")
102
+ console.print(f"[dim]Would add to {target}: {escape(', '.join(builder.pending_dependencies))}[/dim]")
90
103
  for grp, pkgs in builder.pending_group_dependencies.items():
91
104
  target = escape(f"[dependency-groups.{grp}]")
92
- console.print(f"[dim]Would add to {target}: {', '.join(pkgs)}[/dim]")
105
+ console.print(f"[dim]Would add to {target}: {escape(', '.join(pkgs))}[/dim]")
106
+
107
+
108
+ def auto_format_project(project_root: Path) -> None:
109
+ """Run ruff check --fix (I rules) then ruff format on *project_root* (best-effort).
110
+
111
+ Silently skips when ruff is not importable in the active interpreter.
112
+ """
113
+ import sys
114
+
115
+ ruff = [sys.executable, "-m", "ruff"]
116
+ for cmd in (
117
+ [*ruff, "check", "--fix", "--select", "I", "--quiet", "--no-cache", "."],
118
+ [*ruff, "format", "--quiet", "--no-cache", "."],
119
+ [*ruff, "check", "--fix", "--select", "I", "--quiet", "--no-cache", "."],
120
+ ):
121
+ try:
122
+ subprocess.run(cmd, cwd=project_root, check=False, capture_output=True)
123
+ except FileNotFoundError:
124
+ return
93
125
 
94
126
 
95
127
  def build_and_persist(factory: ModuleFactory, builder: ModuleBuilder) -> list[Path]:
96
128
  """Build and persist module operations, returning the affected paths."""
97
129
  factory.build(builder)
98
- return builder.persist()
130
+ paths = builder.persist()
131
+ if not builder.dry_run:
132
+ auto_format_project(builder.project_root)
133
+ return paths
99
134
 
100
135
 
101
- def dry_run_option(help: str = "Preview without writing.") -> typer.models.OptionInfo:
102
- """Return a ``--dry-run/--no-dry-run`` Typer option."""
103
- return typer.models.OptionInfo(
104
- default=False,
105
- param_decls=("--dry-run/--no-dry-run",),
106
- help=help,
107
- rich_help_panel="Options",
108
- show_default=True,
109
- )
136
+ _LEGACY_MIGRATION_HINT = (
137
+ "Migrate from dependency-injector to wireup manually, then set "
138
+ "[bold]scaffold_version[/bold] under [bold][tool.scaffold-ca-python][/bold] in pyproject.toml."
139
+ )
140
+
141
+
142
+ def require_wireup_context(
143
+ project_root: Path | None = None,
144
+ *,
145
+ not_found_message: str | None = PROJECT_NOT_FOUND,
146
+ ) -> tuple[Path, ProjectContext]:
147
+ """Resolve project root, load context, and exit if the project is legacy."""
148
+ root = project_root or require_project_root(not_found_message)
149
+ ctx = load_project_context(root)
150
+ require_wireup_project(ctx)
151
+ return root, ctx
152
+
153
+
154
+ @overload
155
+ def show_help_if_missing(ctx: typer.Context, value: str) -> str: ...
156
+
157
+
158
+ @overload
159
+ def show_help_if_missing(ctx: typer.Context, value: None) -> NoReturn: ...
160
+
161
+
162
+ def show_help_if_missing(ctx: typer.Context, value: str | None) -> str:
163
+ """Show help and exit when a required argument is missing."""
164
+ if value is None:
165
+ typer.echo(ctx.get_help())
166
+ raise typer.Exit()
167
+ return value
168
+
169
+
170
+ def register_with_alias(
171
+ app: typer.Typer,
172
+ name: str,
173
+ alias: str,
174
+ fn: Callable[..., None],
175
+ *,
176
+ help: str,
177
+ epilog: str,
178
+ ) -> None:
179
+ """Register a command and its hidden alias."""
180
+ app.command(name, help=help, epilog=epilog)(fn)
181
+ app.command(alias, hidden=True, help=help, epilog=epilog)(fn)
182
+
183
+
184
+ def require_wireup_project(ctx: ProjectContext) -> None:
185
+ """Exit with code 1 when *ctx* is a legacy project (scaffold_version absent)."""
186
+ if ctx.is_legacy:
187
+ fail(
188
+ f"Project [bold]{ctx.name}[/bold] was generated with scaffold-ca-python ≤ 0.5.0 (dependency-injector).\n"
189
+ "[dim]This scaffolder only modifies wireup projects (0.6.0+). "
190
+ f"{_LEGACY_MIGRATION_HINT}[/dim]"
191
+ )
192
+
193
+
194
+ def find_gateway(src_pkg_root: Path, gateway_name: str) -> str | None:
195
+ """Walk domain/model/*/gateways/ and return the model directory name if the gateway file is found."""
196
+ gateways_base = src_pkg_root / "domain" / "model"
197
+ if not gateways_base.is_dir():
198
+ return None
199
+ for model_dir in gateways_base.iterdir():
200
+ if not model_dir.is_dir():
201
+ continue
202
+ gateway_file = model_dir / "gateways" / f"{gateway_name}.py"
203
+ if gateway_file.exists():
204
+ return model_dir.name
205
+ return None
@@ -7,114 +7,102 @@ import os
7
7
  from pathlib import Path
8
8
  from typing import TYPE_CHECKING
9
9
 
10
- import typer
11
10
  from rich.syntax import Syntax
12
11
 
13
- from scaffold_ca_python.commands._shared import console, require_project_root
12
+ from scaffold_ca_python.commands._shared import (
13
+ auto_format_project,
14
+ console,
15
+ fail,
16
+ require_wireup_context,
17
+ )
14
18
  from scaffold_ca_python.core import mcp_tool_spec
19
+ from scaffold_ca_python.core.errors import ScaffoldError
15
20
  from scaffold_ca_python.core.module_builder import ModuleBuilder
16
- from scaffold_ca_python.core.name_utils import ScaffoldError
17
- from scaffold_ca_python.core.project_detector import load_project_context, resolve_tests_root
21
+ from scaffold_ca_python.core.project_detector import resolve_tests_root
22
+ from scaffold_ca_python.factory.entry_points.ep_mcp import EntryPointMcp
18
23
  from scaffold_ca_python.models.context import ProjectContext
19
24
 
20
25
  if TYPE_CHECKING:
21
26
  from scaffold_ca_python.models.options import EntryPointOptions
22
27
 
23
- _TEST_TOOLS_STRUCTURE_ERROR = (
24
- "[red]Error:[/red] tests/infrastructure/entry_points/mcp_server/test_tools.py is missing or "
25
- "does not have\n"
26
- "the structure --add-tool needs to append a registration test.\n"
27
- "[dim]Hint:[/dim] Restore test_tools.py, or regenerate the entry point with "
28
- "[cyan]scaffold gep --type mcp[/cyan]."
28
+ _MCP_EP_REL = f"infrastructure/entry_points/{EntryPointMcp.subdir}"
29
+
30
+ _TEST_TOOLS_MSG = (
31
+ f"tests/{_MCP_EP_REL}/test_tools.py is missing or "
32
+ "does not have the structure --add-tool needs to append a registration test."
29
33
  )
34
+ _TEST_TOOLS_HINT = "Restore test_tools.py, or regenerate the entry point with [cyan]scaffold gep --type mcp[/cyan]."
30
35
 
31
36
 
32
37
  def _check_add_tool_flags(options: EntryPointOptions) -> None:
33
38
  flags = options.creation_flags()
34
39
  if flags:
35
- console.print(f"[red]Error:[/red] --add-tool is incompatible with {flags[0]}.")
36
- raise typer.Exit(code=1)
40
+ fail(f"--add-tool is incompatible with {flags[0]}.")
37
41
  if options.type_ != "mcp":
38
- console.print("[red]Error:[/red] --add-tool is only valid with --type mcp.")
39
- raise typer.Exit(code=1)
42
+ fail("--add-tool is only valid with --type mcp.")
40
43
  if options.name is None:
41
- console.print("[red]Error:[/red] --name is required with --add-tool.")
42
- raise typer.Exit(code=1)
44
+ fail("--name is required with --add-tool.")
43
45
 
44
46
 
45
47
  def _build_spec(options: EntryPointOptions) -> mcp_tool_spec.ToolSpec:
46
- if options.name is None: # guard; _check_add_tool_flags exits before this if name is None
47
- raise typer.Exit(code=1)
48
+ assert options.name is not None # ensured by _check_add_tool_flags
48
49
  params = list(options.params) if options.params else None
49
50
  try:
50
51
  return mcp_tool_spec.build_tool_spec(options.name, params, options.returns, options.description)
51
52
  except (ValueError, ScaffoldError) as e:
52
- console.print(f"[red]Error:[/red] {e}")
53
- raise typer.Exit(code=1) from None
53
+ fail(str(e))
54
54
 
55
55
 
56
56
  def _resolve_paths(project_root: Path, ctx: ProjectContext) -> tuple[Path, Path]:
57
- tools_py = project_root / "src" / ctx.python_package / "infrastructure" / "entry_points" / "mcp_server" / "tools.py"
58
- test_tools_py = (
59
- resolve_tests_root(project_root) / "infrastructure" / "entry_points" / "mcp_server" / "test_tools.py"
60
- )
57
+ ep_subdir = EntryPointMcp.subdir
58
+ tools_py = ctx.src_pkg_root / "infrastructure" / "entry_points" / ep_subdir / "tools.py"
59
+ test_tools_py = resolve_tests_root(project_root) / "infrastructure" / "entry_points" / ep_subdir / "test_tools.py"
61
60
  return tools_py, test_tools_py
62
61
 
63
62
 
64
63
  def _read_sources(paths: tuple[Path, Path]) -> tuple[str, str]:
65
64
  tools_py, test_tools_py = paths
66
65
  if not tools_py.exists():
67
- console.print(
68
- "[red]Error:[/red] No MCP entry point found at infrastructure/entry_points/mcp_server/.\n"
69
- "[dim]Hint:[/dim] Run [cyan]scaffold gep --type mcp[/cyan] first to create one."
66
+ fail(
67
+ f"No MCP entry point found at {_MCP_EP_REL}/.",
68
+ hint="Run [cyan]scaffold gep --type mcp[/cyan] first to create one.",
70
69
  )
71
- raise typer.Exit(code=1)
72
70
  try:
73
71
  tools_src = tools_py.read_text(encoding="utf-8")
74
72
  except OSError as e:
75
- console.print(f"[red]Error:[/red] Cannot read {tools_py}: {e}")
76
- raise typer.Exit(code=1) from None
73
+ fail(f"Cannot read {tools_py}: {e}")
77
74
  try:
78
75
  test_tools_src = test_tools_py.read_text(encoding="utf-8")
79
76
  except OSError:
80
- console.print(_TEST_TOOLS_STRUCTURE_ERROR)
81
- raise typer.Exit(code=1) from None
77
+ fail(_TEST_TOOLS_MSG, hint=_TEST_TOOLS_HINT)
82
78
  return tools_src, test_tools_src
83
79
 
84
80
 
85
81
  def _check_structure(sources: tuple[str, str], spec: mcp_tool_spec.ToolSpec) -> None:
86
82
  tools_src, test_tools_src = sources
87
83
  if not mcp_tool_spec.has_bind_tools_function(tools_src):
88
- console.print(
89
- "[red]Error:[/red] infrastructure/entry_points/mcp_server/tools.py was generated by an older "
90
- "scaffold\nversion and does not support --add-tool.\n"
91
- "[dim]Hint:[/dim] Make [cyan]async def bind_tools[/cyan] the last function in tools.py, or "
92
- "regenerate the entry point\n(back up any custom tools first) with [cyan]scaffold gep --type mcp[/cyan]."
84
+ fail(
85
+ f"{_MCP_EP_REL}/tools.py was generated by an older scaffold version and does not support --add-tool.",
86
+ hint="Make [cyan]async def bind_tools[/cyan] the last function in tools.py, or "
87
+ "regenerate the entry point (back up any custom tools first) with [cyan]scaffold gep --type mcp[/cyan].",
93
88
  )
94
- raise typer.Exit(code=1)
95
89
  if not mcp_tool_spec.has_test_registration_structure(test_tools_src):
96
- console.print(_TEST_TOOLS_STRUCTURE_ERROR)
97
- raise typer.Exit(code=1)
90
+ fail(_TEST_TOOLS_MSG, hint=_TEST_TOOLS_HINT)
98
91
  existing = mcp_tool_spec.find_existing_tool_names(tools_src)
99
92
  if spec.name in existing:
100
93
  if spec.name == "bind_tools":
101
- console.print(
102
- f"[red]Error:[/red] '{spec.name}' is reserved by the tool-binding function and "
103
- "cannot be used as a tool name."
104
- )
94
+ fail(f"'{spec.name}' is reserved by the tool-binding function and cannot be used as a tool name.")
105
95
  else:
106
- console.print(f"[red]Error:[/red] A tool named '{spec.name}' already exists in tools.py.")
107
- raise typer.Exit(code=1)
96
+ fail(f"A tool named '{spec.name}' already exists in tools.py.")
108
97
 
109
98
 
110
99
  def _check_writable(paths: tuple[Path, Path], project_root: Path) -> None:
111
100
  for path in paths:
112
101
  if not os.access(path, os.W_OK):
113
- console.print(
114
- f"[red]Error:[/red] Cannot write to {path.relative_to(project_root)}.\n"
115
- "[dim]Hint:[/dim] Check the file's permissions and re-run the command."
102
+ fail(
103
+ f"Cannot write to {path.relative_to(project_root)}.",
104
+ hint="Check the file's permissions and re-run the command.",
116
105
  )
117
- raise typer.Exit(code=1)
118
106
 
119
107
 
120
108
  def _persist_with_restore(
@@ -125,18 +113,23 @@ def _persist_with_restore(
125
113
  try:
126
114
  return builder.persist()
127
115
  except OSError as e:
116
+ restore_ok = True
117
+ restore_msg = ""
128
118
  try:
129
119
  tools_py.write_text(tools_src, encoding="utf-8")
130
120
  test_tools_py.write_text(test_tools_src, encoding="utf-8")
131
- except OSError:
132
- pass
121
+ except OSError as restore_err:
122
+ restore_ok = False
123
+ restore_msg = str(restore_err)
133
124
  fname = Path(e.filename).name if e.filename else "tools.py"
134
- console.print(
135
- f"[red]Error:[/red] Failed to write {fname} ({e}). "
136
- "tools.py was restored; no changes were made.\n"
137
- "[dim]Hint:[/dim] Fix the underlying problem (permissions, disk space) and re-run the command."
125
+ if restore_ok:
126
+ detail = "tools.py was restored; no changes were made."
127
+ else:
128
+ detail = f"Restore also failed ({restore_msg}); tools.py may be in an inconsistent state."
129
+ fail(
130
+ f"Failed to write {fname} ({e}). {detail}",
131
+ hint="Fix the underlying problem (permissions, disk space) and re-run the command.",
138
132
  )
139
- raise typer.Exit(code=1) from None
140
133
 
141
134
 
142
135
  def _report_add_tool(
@@ -163,8 +156,7 @@ def add_mcp_tool(options: EntryPointOptions) -> None:
163
156
  """Add a tool stub to an existing MCP entry point."""
164
157
  _check_add_tool_flags(options)
165
158
  spec = _build_spec(options)
166
- project_root = require_project_root(not_found_message=None)
167
- project_ctx = load_project_context(project_root)
159
+ project_root, project_ctx = require_wireup_context(not_found_message=None)
168
160
  paths = _resolve_paths(project_root, project_ctx)
169
161
  sources = _read_sources(paths)
170
162
  _check_structure(sources, spec)
@@ -187,14 +179,15 @@ def add_mcp_tool(options: EntryPointOptions) -> None:
187
179
  try:
188
180
  ast.parse(tools_src + tool_stub)
189
181
  except SyntaxError:
190
- console.print(
191
- "[red]Error:[/red] infrastructure/entry_points/mcp_server/tools.py cannot accept the new tool stub.\n"
192
- "[dim]Hint:[/dim] Regenerate the entry point with [cyan]scaffold gep --type mcp[/cyan]."
182
+ fail(
183
+ f"{_MCP_EP_REL}/tools.py cannot accept the new tool stub.",
184
+ hint="Regenerate the entry point with [cyan]scaffold gep --type mcp[/cyan].",
193
185
  )
194
- raise typer.Exit(code=1) from None
195
186
 
196
187
  _check_writable(paths, project_root)
197
188
  builder.append_to_file(tools_py, tool_stub)
198
189
  builder.append_to_file(test_tools_py, test_stub)
199
190
  modified = _persist_with_restore(builder, (tools_py, tools_src, test_tools_py, test_tools_src))
191
+ if not options.dry_run:
192
+ auto_format_project(project_root)
200
193
  _report_add_tool(modified, tool_stub, test_stub, spec, project_root, options.dry_run)
@@ -7,14 +7,21 @@ from typing import Annotated
7
7
 
8
8
  import typer
9
9
 
10
- from scaffold_ca_python.commands._shared import console, require_project_root, validate_name_or_exit
10
+ from scaffold_ca_python.commands._shared import (
11
+ DryRunDelete,
12
+ auto_format_project,
13
+ console,
14
+ fail,
15
+ register_with_alias,
16
+ require_wireup_context,
17
+ show_help_if_missing,
18
+ validate_name_or_exit,
19
+ )
11
20
  from scaffold_ca_python.core.module_builder import ModuleBuilder
12
21
  from scaffold_ca_python.core.module_locator import find_module_targets
13
22
  from scaffold_ca_python.core.name_utils import to_snake_case, validate_module_name
14
- from scaffold_ca_python.core.project_detector import load_project_context
15
23
  from scaffold_ca_python.factory.simple.delete_module_factory import DeleteModuleFactory
16
24
  from scaffold_ca_python.models.context import ModuleContext
17
- from scaffold_ca_python.models.layer import Layer
18
25
 
19
26
  _DM_HELP = "Delete a previously generated module and its test mirror. Alias 'dm'."
20
27
  _DM_EPILOG = "Examples:\n\n * scaffold dm --name order\n\n * scaffold delete-module --name my_adapter\n\n"
@@ -29,22 +36,19 @@ def _display(path: Path, root: Path) -> Path:
29
36
 
30
37
  def _delete_module_impl(name: str, confirm: bool, dry_run: bool) -> None:
31
38
  validate_name_or_exit(name, validate_module_name)
32
- project_root = require_project_root()
33
- project_ctx = load_project_context(project_root)
39
+ project_root, project_ctx = require_wireup_context()
34
40
 
35
- # Create a placeholder ModuleContext for the factory (layer doesn't matter for delete)
36
- module_ctx = ModuleContext(name=name, layer=Layer.HELPERS, project=project_ctx)
41
+ module_ctx = ModuleContext(name=name, project=project_ctx)
37
42
 
38
43
  # Find targets
39
44
  snake = to_snake_case(name)
40
- targets = find_module_targets(project_root, project_ctx.python_package, snake)
45
+ targets = find_module_targets(project_root, project_ctx.src_pkg_root, snake)
41
46
 
42
47
  if not targets:
43
- console.print(
44
- f"[red]Error:[/red] No module named '{snake}' found in project.\n"
45
- "[dim]Hint:[/dim] Check spelling with 'scaffold vs' to list modules."
48
+ fail(
49
+ f"No module named '{snake}' found in project.",
50
+ hint="Module names match directories under domain/model/ (snake_case).",
46
51
  )
47
- raise typer.Exit(code=1)
48
52
 
49
53
  # dry_run OR no --confirm → preview mode only
50
54
  if dry_run or not confirm:
@@ -66,20 +70,12 @@ def _delete_module_impl(name: str, confirm: bool, dry_run: bool) -> None:
66
70
 
67
71
  DeleteModuleFactory().build(builder)
68
72
 
69
- # Persist deletion
70
73
  builder.persist()
74
+ auto_format_project(project_root)
71
75
  console.print(f"[green]✓[/green] Deleted module(s) for [bold]{name}[/bold].")
72
76
 
73
77
 
74
78
  def register(app: typer.Typer) -> None:
75
- """Register dm / delete-module command onto *app*."""
76
-
77
- @app.command(
78
- "delete-module",
79
- help=_DM_HELP,
80
- epilog=_DM_EPILOG,
81
- )
82
- @app.command("dm", hidden=True, help=_DM_HELP, epilog=_DM_EPILOG)
83
79
  def delete_module(
84
80
  ctx: typer.Context,
85
81
  name: Annotated[
@@ -89,22 +85,13 @@ def register(app: typer.Typer) -> None:
89
85
  bool,
90
86
  typer.Option(
91
87
  "--confirm/--no-confirm",
92
- help="Skip confirmation dialog and delete immediately.",
93
- rich_help_panel="Options",
94
- ),
95
- ] = False,
96
- dry_run: Annotated[
97
- bool,
98
- typer.Option(
99
- "--dry-run/--no-dry-run",
100
- help="Preview deletion without removing files.",
88
+ help="Delete the module and its tests immediately without showing a preview.",
101
89
  rich_help_panel="Options",
102
- show_default=True,
103
90
  ),
104
91
  ] = False,
92
+ dry_run: DryRunDelete = False,
105
93
  ) -> None:
106
- """Delete a module and its test mirror."""
107
- if name is None:
108
- typer.echo(ctx.get_help())
109
- raise typer.Exit(0)
94
+ name = show_help_if_missing(ctx, name)
110
95
  _delete_module_impl(name, confirm, dry_run)
96
+
97
+ register_with_alias(app, "delete-module", "dm", delete_module, help=_DM_HELP, epilog=_DM_EPILOG)