fastpluggy-cli 0.1.1__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.
fastpluggy_cli/cli.py ADDED
@@ -0,0 +1,1000 @@
1
+ import importlib.metadata
2
+ import ipaddress
3
+ import re
4
+ import sys
5
+ import os
6
+ from pathlib import Path
7
+
8
+ import click
9
+ import questionary
10
+ from jinja2 import Environment, FileSystemLoader
11
+
12
+ TEMPLATE_ROOT = Path(__file__).parent / "scaffold_templates"
13
+
14
+ _PLUGIN_NAME_RE = re.compile(r"^[a-z][a-z0-9_]*$")
15
+
16
+
17
+ def _to_pascal_case(slug: str) -> str:
18
+ """Convert a snake_case slug to PascalCase."""
19
+ return "".join(word.capitalize() for word in slug.split("_"))
20
+
21
+
22
+ def _to_label(slug: str) -> str:
23
+ """Convert a snake_case slug to a title-cased label."""
24
+ return " ".join(word.capitalize() for word in slug.split("_"))
25
+
26
+ PLUGIN_COMMANDS_EP_GROUP = "fastpluggy.cli"
27
+
28
+
29
+ class RichGroup(click.Group):
30
+ """Click Group subclass that visually separates core and plugin commands."""
31
+
32
+ def __init__(self, *args, **kwargs):
33
+ super().__init__(*args, **kwargs)
34
+ self._plugin_command_names: set[str] = set()
35
+
36
+ def format_commands(self, ctx, formatter):
37
+ core_cmds = []
38
+ plugin_cmds = []
39
+ for name in self.list_commands(ctx):
40
+ cmd = self.get_command(ctx, name)
41
+ if cmd is None or cmd.hidden:
42
+ continue
43
+ help_text = cmd.get_short_help_str(limit=formatter.width)
44
+ if name in self._plugin_command_names:
45
+ plugin_cmds.append((name, help_text))
46
+ else:
47
+ core_cmds.append((name, help_text))
48
+
49
+ if core_cmds:
50
+ with formatter.section("Core Commands"):
51
+ formatter.write_dl(core_cmds)
52
+ if plugin_cmds:
53
+ with formatter.section("Plugin Commands"):
54
+ formatter.write_dl(plugin_cmds)
55
+
56
+
57
+ def _load_plugin_commands(group: RichGroup) -> None:
58
+ """Discover and register plugin CLI commands from entry points."""
59
+ eps = importlib.metadata.entry_points(group=PLUGIN_COMMANDS_EP_GROUP)
60
+ for ep in eps:
61
+ if ep.name in group.commands:
62
+ print(
63
+ f"WARNING: CLI command group '{ep.name}' conflicts with an existing "
64
+ f"command. Skipping plugin entry point '{ep.value}'. "
65
+ f"Resolve the conflict by renaming one of the plugins.",
66
+ file=sys.stderr,
67
+ )
68
+ continue
69
+ try:
70
+ cmd = ep.load()
71
+ except (ImportError, Exception) as exc:
72
+ print(
73
+ f"WARNING: Failed to load CLI plugin '{ep.name}' "
74
+ f"({ep.value}): {exc}",
75
+ file=sys.stderr,
76
+ )
77
+ continue
78
+ if not isinstance(cmd, click.Command):
79
+ print(
80
+ f"WARNING: CLI plugin '{ep.name}' ({ep.value}) is not a "
81
+ f"click.Command — skipping.",
82
+ file=sys.stderr,
83
+ )
84
+ continue
85
+ group.add_command(cmd, ep.name)
86
+ group._plugin_command_names.add(ep.name)
87
+
88
+
89
+ def _create_dev_app():
90
+ """
91
+ Top-level factory for `fastpluggy start-dev-server`.
92
+ Must stay at module level so uvicorn can import it by string when --reload is used.
93
+ Auto-discovers all installed FastPluggy plugins via entry points.
94
+ """
95
+ from fastapi import FastAPI
96
+ from fastpluggy.fastpluggy import FastPluggy
97
+
98
+ app = FastAPI()
99
+ FastPluggy(app)
100
+ return app
101
+
102
+ @click.group(cls=RichGroup, help="FastPluggy CLI - Scaffold and manage FastPluggy apps.")
103
+ def cli():
104
+ pass
105
+
106
+ @cli.command("new", help="Create a new FastPluggy project")
107
+ @click.argument('project_name', required=False)
108
+ def new(project_name):
109
+ """Scaffold a new FastPluggy app in the given directory."""
110
+ if not project_name:
111
+ project_name = questionary.text(
112
+ "What is your project name?",
113
+ validate=lambda text: True if text else "Project name cannot be empty"
114
+ ).ask()
115
+
116
+ if not project_name:
117
+ click.echo("Project creation cancelled.")
118
+ return
119
+
120
+ output_dir = Path(".").resolve() / project_name
121
+ click.echo(f"Creating new FastPluggy project in: {output_dir}")
122
+ output_dir.mkdir(parents=True, exist_ok=True)
123
+
124
+ env = Environment(loader=FileSystemLoader(str(TEMPLATE_ROOT)))
125
+
126
+ context = {
127
+ "project_name": project_name,
128
+ "plugin_name": "example_plugin",
129
+ "plugin_class": "ExamplePlugin",
130
+ "plugin_label": "Example Plugin",
131
+ "menu_type": "main",
132
+ "icon": "ti ti-puzzle",
133
+ "with_config": False,
134
+ "with_model": False,
135
+ "with_cli_commands": False,
136
+ }
137
+
138
+ # Render main.py from template
139
+ main_py = env.get_template("main.py.j2").render(context)
140
+ (output_dir / "main.py").write_text(main_py)
141
+ click.echo(" created main.py")
142
+
143
+ # Create .env file
144
+ env_content = (
145
+ "# FastPluggy Environment Variables\n"
146
+ "PORT=8000\n"
147
+ "# DATABASE_URL=sqlite:///fastpluggy.db\n"
148
+ )
149
+ (output_dir / ".env").write_text(env_content)
150
+ click.echo(" created .env")
151
+
152
+ # Create pyproject.toml
153
+ pyproject_content = (
154
+ "[build-system]\n"
155
+ 'requires = ["setuptools>=70.0"]\n'
156
+ 'build-backend = "setuptools.build_meta"\n'
157
+ "\n"
158
+ "[project]\n"
159
+ f'name = "{project_name}"\n'
160
+ 'version = "0.1.0"\n'
161
+ 'description = "A FastPluggy project"\n'
162
+ 'requires-python = ">=3.10"\n'
163
+ "dependencies = [\n"
164
+ ' "fastapi",\n'
165
+ ' "uvicorn[standard]",\n'
166
+ ' "fastpluggy>=0.4.0",\n'
167
+ "]\n"
168
+ "\n"
169
+ "[project.optional-dependencies]\n"
170
+ "dev = [\n"
171
+ ' "pytest",\n'
172
+ "]\n"
173
+ )
174
+ (output_dir / "pyproject.toml").write_text(pyproject_content)
175
+ click.echo(" created pyproject.toml")
176
+
177
+ click.echo(f"\nProject '{project_name}' created at {output_dir}")
178
+ click.echo("\nNext steps:")
179
+ click.echo(f" cd {project_name}")
180
+ click.echo(" pip install -e '.[dev]'")
181
+ click.echo(" fastpluggy new-plugin my_plugin")
182
+ click.echo(" fastpluggy start-dev-server")
183
+
184
+
185
+
186
+ @cli.command("new-plugin", help="Scaffold a standalone FastPluggy plugin (src/ layout)")
187
+ @click.argument("plugin_name", required=False)
188
+ @click.option("--output-dir", "-o", default=".", help="Directory where the plugin folder is created")
189
+ @click.option("--label", default=None, help="Display label (default: title-cased slug)")
190
+ @click.option("--menu-type", default=None, type=click.Choice(["main", "admin", "none"]),
191
+ help="Menu type (default: main)")
192
+ @click.option("--icon", default=None, help="Menu icon class (default: ti ti-puzzle)")
193
+ @click.option("--with-config", is_flag=True, default=False, help="Generate config.py with settings class")
194
+ @click.option("--with-model", is_flag=True, default=False, help="Generate models.py skeleton")
195
+ @click.option("--with-cli-commands", is_flag=True, default=False, help="Generate cli.py with click.Group for CLI extension")
196
+ @click.option("--no-interactive", is_flag=True, default=False, help="Skip prompts, use defaults + CLI args")
197
+ @click.option("--dry-run", is_flag=True, default=False, help="Print what would be generated without writing")
198
+ def new_plugin(plugin_name, output_dir, label, menu_type, icon, with_config, with_model,
199
+ with_cli_commands, no_interactive, dry_run):
200
+ """Scaffold a standalone FastPluggy plugin with the src/ layout.
201
+
202
+ Creates a ready-to-develop plugin directory with pyproject.toml,
203
+ src/ package, templates, and tests.
204
+ """
205
+ # --- Gather inputs ---
206
+ if no_interactive:
207
+ if not plugin_name:
208
+ click.echo("Error: plugin_name argument is required with --no-interactive", err=True)
209
+ raise SystemExit(1)
210
+ label = label or _to_label(plugin_name)
211
+ menu_type = menu_type or "main"
212
+ icon = icon or "ti ti-puzzle"
213
+ else:
214
+ # Interactive prompts
215
+ if not plugin_name:
216
+ plugin_name = questionary.text(
217
+ "Plugin name (slug, e.g. my_plugin):",
218
+ validate=lambda t: bool(_PLUGIN_NAME_RE.match(t)) if t else False,
219
+ ).ask()
220
+ if not plugin_name:
221
+ click.echo("Plugin creation cancelled.")
222
+ return
223
+
224
+ if not label:
225
+ default_label = _to_label(plugin_name)
226
+ label = questionary.text(
227
+ "Display label:",
228
+ default=default_label,
229
+ ).ask() or default_label
230
+
231
+ if menu_type is None:
232
+ menu_type = questionary.select(
233
+ "Menu type:",
234
+ choices=["main", "admin", "none"],
235
+ default="main",
236
+ ).ask() or "main"
237
+
238
+ if icon is None:
239
+ icon = questionary.text(
240
+ "Icon (Tabler icons class):",
241
+ default="ti ti-puzzle",
242
+ ).ask() or "ti ti-puzzle"
243
+
244
+ if not with_config:
245
+ with_config = questionary.confirm("Include config.py?", default=False).ask()
246
+
247
+ if not with_model:
248
+ with_model = questionary.confirm("Include models.py?", default=False).ask()
249
+
250
+ # Validate plugin name
251
+ if not _PLUGIN_NAME_RE.match(plugin_name):
252
+ click.echo(f"Error: invalid plugin name '{plugin_name}'. Must match [a-z][a-z0-9_]*", err=True)
253
+ raise SystemExit(1)
254
+
255
+ # Defaults for any remaining None values
256
+ label = label or _to_label(plugin_name)
257
+ menu_type = menu_type or "main"
258
+ icon = icon or "ti ti-puzzle"
259
+
260
+ plugin_class = _to_pascal_case(plugin_name)
261
+
262
+ # --- Build file manifest ---
263
+ base = Path(output_dir).resolve() / plugin_name
264
+ src = base / "src" / plugin_name
265
+
266
+ context = {
267
+ "plugin_name": plugin_name,
268
+ "plugin_class": plugin_class,
269
+ "plugin_label": label,
270
+ "menu_type": menu_type,
271
+ "icon": icon,
272
+ "with_config": with_config,
273
+ "with_model": with_model,
274
+ "with_cli_commands": with_cli_commands,
275
+ }
276
+
277
+ env = Environment(loader=FileSystemLoader(str(TEMPLATE_ROOT)))
278
+
279
+ # Files to generate: (relative_path, content_or_template)
280
+ files: list[tuple[Path, str]] = []
281
+
282
+ # pyproject.toml
283
+ files.append((
284
+ base / "pyproject.toml",
285
+ env.get_template("plugin/pyproject.toml.j2").render(context),
286
+ ))
287
+
288
+ # src/__init__.py
289
+ files.append((src / "__init__.py", ""))
290
+
291
+ # src/plugin.py
292
+ files.append((
293
+ src / "plugin.py",
294
+ env.get_template("plugin/plugin.py.j2").render(context),
295
+ ))
296
+
297
+ # src/router.py
298
+ files.append((
299
+ src / "router.py",
300
+ env.get_template("plugin/router.py.j2").render(context),
301
+ ))
302
+
303
+ # src/config.py (optional)
304
+ if with_config:
305
+ files.append((
306
+ src / "config.py",
307
+ env.get_template("plugin/config.py.j2").render(context),
308
+ ))
309
+
310
+ # src/models.py (optional)
311
+ if with_model:
312
+ models_content = (
313
+ "# models.py\n"
314
+ "from pydantic import BaseModel\n"
315
+ "\n\n"
316
+ f"class {plugin_class}Item(BaseModel):\n"
317
+ ' """Example model for the plugin."""\n'
318
+ "\n"
319
+ " name: str\n"
320
+ ' description: str = ""\n'
321
+ )
322
+ files.append((src / "models.py", models_content))
323
+
324
+ # src/cli.py (optional)
325
+ if with_cli_commands:
326
+ cli_group_name = plugin_name.replace("_", "-")
327
+ cli_content = (
328
+ "import click\n"
329
+ "\n\n"
330
+ f'{plugin_name}_group = click.Group("{cli_group_name}")\n'
331
+ "\n\n"
332
+ f"@{plugin_name}_group.command()\n"
333
+ "def hello():\n"
334
+ f' """Example CLI command for {label}."""\n'
335
+ f' click.echo("Hello from {label}!")\n'
336
+ )
337
+ files.append((src / "cli.py", cli_content))
338
+
339
+ # src/templates/<plugin_name>/index.html.j2
340
+ files.append((
341
+ src / "templates" / plugin_name / "index.html.j2",
342
+ env.get_template("plugin/index.html.j2").render(context),
343
+ ))
344
+
345
+ # tests/__init__.py
346
+ files.append((base / "tests" / "__init__.py", ""))
347
+
348
+ # tests/test_plugin.py
349
+ test_content = (
350
+ f"from fastpluggy_plugin.{plugin_name}.plugin import {plugin_class}\n"
351
+ "\n\n"
352
+ "def test_plugin_class_exists():\n"
353
+ f" assert {plugin_class} is not None\n"
354
+ f' assert {plugin_class}.module_name == "{plugin_name}"\n'
355
+ )
356
+ files.append((base / "tests" / "test_plugin.py", test_content))
357
+
358
+ # README.md
359
+ readme_content = (
360
+ f"# {label}\n"
361
+ "\n"
362
+ "A FastPluggy plugin.\n"
363
+ "\n"
364
+ "## Installation\n"
365
+ "\n"
366
+ "```bash\n"
367
+ 'pip install -e ".[dev]"\n'
368
+ "```\n"
369
+ "\n"
370
+ "## Development\n"
371
+ "\n"
372
+ "```bash\n"
373
+ "pytest tests/\n"
374
+ "```\n"
375
+ )
376
+ files.append((base / "README.md", readme_content))
377
+
378
+ # .gitignore — standard plugin gitignore
379
+ gitignore_content = (
380
+ "# Python\n"
381
+ "__pycache__/\n"
382
+ "*.py[cod]\n"
383
+ "*.egg-info/\n"
384
+ "dist/\n"
385
+ "build/\n"
386
+ "\n"
387
+ "# Environments\n"
388
+ ".env\n"
389
+ ".venv/\n"
390
+ "\n"
391
+ "# IDE\n"
392
+ ".idea/\n"
393
+ ".claude/\n"
394
+ "\n"
395
+ "# Data / temp\n"
396
+ "*.db\n"
397
+ "*.log\n"
398
+ "*.tmp\n"
399
+ "\n"
400
+ "# Test / coverage\n"
401
+ ".coverage\n"
402
+ ".pytest_cache/\n"
403
+ "htmlcov/\n"
404
+ "\n"
405
+ "# Node (e2e tests)\n"
406
+ "node_modules/\n"
407
+ "\n"
408
+ "# Generated\n"
409
+ ".plugin-manifest.json\n"
410
+ "\n"
411
+ "# Security\n"
412
+ ".env.local\n"
413
+ ".env.production\n"
414
+ ".env.*.local\n"
415
+ "*.pem\n"
416
+ "*.key\n"
417
+ "*.p12\n"
418
+ "*.pfx\n"
419
+ "credentials*\n"
420
+ "secrets*\n"
421
+ )
422
+ files.append((base / ".gitignore", gitignore_content))
423
+
424
+ # --- Output ---
425
+ if dry_run:
426
+ click.echo(f"Would create plugin '{plugin_name}' at {base}/\n")
427
+ click.echo("Files:")
428
+ for fpath, _ in files:
429
+ click.echo(f" {fpath.relative_to(base.parent)}")
430
+ return
431
+
432
+ for fpath, content in files:
433
+ fpath.parent.mkdir(parents=True, exist_ok=True)
434
+ fpath.write_text(content)
435
+ click.echo(f" created {fpath.relative_to(base.parent)}")
436
+
437
+ click.echo(f"\nPlugin '{plugin_name}' scaffolded at {base}")
438
+
439
+
440
+ def _generate_self_signed_cert(cert_dir: Path) -> tuple[str, str]:
441
+ """Generate a self-signed SSL certificate for dev use. Returns (certfile, keyfile) paths."""
442
+ from cryptography import x509
443
+ from cryptography.x509.oid import NameOID
444
+ from cryptography.hazmat.primitives import hashes, serialization
445
+ from cryptography.hazmat.primitives.asymmetric import rsa
446
+ import datetime
447
+
448
+ cert_file = cert_dir / "dev-cert.pem"
449
+ key_file = cert_dir / "dev-key.pem"
450
+
451
+ if cert_file.exists() and key_file.exists():
452
+ click.echo(f"🔒 Reusing existing dev certificate: {cert_file}")
453
+ return str(cert_file), str(key_file)
454
+
455
+ cert_dir.mkdir(parents=True, exist_ok=True)
456
+
457
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
458
+
459
+ import socket
460
+ hostname = socket.gethostname()
461
+
462
+ subject = issuer = x509.Name([
463
+ x509.NameAttribute(NameOID.COMMON_NAME, f"FastPluggy Dev ({hostname})"),
464
+ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "FastPluggy Dev"),
465
+ ])
466
+
467
+ san_names: list[x509.GeneralName] = [
468
+ x509.DNSName("localhost"),
469
+ x509.DNSName(hostname),
470
+ x509.IPAddress(ipaddress.IPv4Address("127.0.0.1")),
471
+ ]
472
+ # Add local network IPs so the cert works on LAN
473
+ for local_ip in _get_local_ips():
474
+ san_names.append(x509.IPAddress(local_ip))
475
+
476
+ cert = (
477
+ x509.CertificateBuilder()
478
+ .subject_name(subject)
479
+ .issuer_name(issuer)
480
+ .public_key(key.public_key())
481
+ .serial_number(x509.random_serial_number())
482
+ .not_valid_before(datetime.datetime.now(datetime.timezone.utc))
483
+ .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=365))
484
+ .add_extension(x509.SubjectAlternativeName(san_names), critical=False)
485
+ .sign(key, hashes.SHA256())
486
+ )
487
+
488
+ key_file.write_bytes(key.private_bytes(
489
+ serialization.Encoding.PEM,
490
+ serialization.PrivateFormat.TraditionalOpenSSL,
491
+ serialization.NoEncryption(),
492
+ ))
493
+ cert_file.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
494
+
495
+ click.echo(f"🔒 Generated self-signed dev certificate: {cert_file}")
496
+ return str(cert_file), str(key_file)
497
+
498
+
499
+ def _get_local_ips():
500
+ """Return a list of local IPv4 addresses (non-loopback)."""
501
+ import socket
502
+ ips = []
503
+ try:
504
+ for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET):
505
+ addr = ipaddress.IPv4Address(info[4][0])
506
+ if not addr.is_loopback and addr not in ips:
507
+ ips.append(addr)
508
+ except socket.gaierror:
509
+ pass
510
+ return ips
511
+
512
+
513
+ @cli.command("start-dev-server", help="Start a FastPluggy dev server with auto-discovered plugins")
514
+ @click.option("--port", default=8000, show_default=True, help="Port to listen on")
515
+ @click.option("--host", default="127.0.0.1", show_default=True, help="Host to bind to")
516
+ @click.option("--reload", is_flag=True, default=False, help="Enable hot-reload (local dev only)")
517
+ @click.option("--verbose", "-v", is_flag=True, default=False, help="Enable verbose/debug logging")
518
+ @click.option("--ssl", "use_ssl", is_flag=True, default=False, help="Enable HTTPS with auto-generated self-signed certificate")
519
+ def start_dev_server(port, host, reload, verbose, use_ssl):
520
+ """Start a FastPluggy development server.
521
+
522
+ Auto-discovers all installed FastPluggy plugins via the
523
+ 'fastpluggy.plugins' entry point group. Set DATABASE_URL in your
524
+ environment to use a custom database (defaults to SQLite).
525
+
526
+ Use --ssl to enable HTTPS with an auto-generated self-signed certificate.
527
+ Required for Web Push (VAPID) on non-localhost hosts.
528
+ """
529
+ import logging
530
+
531
+ try:
532
+ import uvicorn
533
+ except ImportError:
534
+ click.echo("❌ uvicorn is required: pip install uvicorn[standard]")
535
+ raise SystemExit(1)
536
+
537
+ if verbose:
538
+ logging.basicConfig(level=logging.DEBUG)
539
+ # Also set loguru (used by fastpluggy core) to DEBUG
540
+ try:
541
+ from loguru import logger
542
+ logger.enable("fastpluggy")
543
+ except ImportError:
544
+ pass
545
+ log_level = "debug"
546
+ else:
547
+ log_level = "info"
548
+
549
+ if not os.environ.get("DATABASE_URL"):
550
+ db_path = Path(".") / "fastpluggy-dev.db"
551
+ os.environ["DATABASE_URL"] = f"sqlite:///{db_path}"
552
+ click.echo(f"ℹ️ DATABASE_URL not set — using SQLite: {db_path}")
553
+
554
+ ssl_kwargs = {}
555
+ if use_ssl:
556
+ try:
557
+ from cryptography import x509 # noqa: F401
558
+ except ImportError:
559
+ click.echo("❌ cryptography is required for --ssl: pip install cryptography")
560
+ raise SystemExit(1)
561
+
562
+ cert_dir = Path(".") / ".fastpluggy" / "ssl"
563
+ cert_file, key_file = _generate_self_signed_cert(cert_dir)
564
+ ssl_kwargs = {"ssl_certfile": cert_file, "ssl_keyfile": key_file}
565
+
566
+ protocol = "https" if use_ssl else "http"
567
+ click.echo(f"🚀 Starting FastPluggy dev server on {protocol}://{host}:{port} ...")
568
+
569
+ uvicorn.run(
570
+ "fastpluggy_cli.cli:_create_dev_app",
571
+ host=host,
572
+ port=port,
573
+ reload=reload,
574
+ factory=True,
575
+ log_level=log_level,
576
+ **ssl_kwargs,
577
+ )
578
+
579
+
580
+ @cli.command("validate", help="Validate a plugin directory against compliance rules")
581
+ @click.argument("plugin_dir", default=".", type=click.Path(exists=True))
582
+ @click.option("--json", "as_json", is_flag=True, default=False, help="Output results as JSON")
583
+ def validate(plugin_dir, as_json):
584
+ """Validate a plugin directory against FastPluggy compliance rules (R1-R13).
585
+
586
+ Checks docs, README, tests, entry points, CI config, and more.
587
+ Returns exit code 0 if all checks pass, 1 if any fail.
588
+
589
+ \b
590
+ Examples:
591
+ fastpluggy validate plugins/my_plugin
592
+ fastpluggy validate --json .
593
+ fp validate /path/to/plugin
594
+ """
595
+ import json as json_mod
596
+ from pathlib import Path as _Path
597
+
598
+ from fastpluggy.core.plugin.validator import validate_plugin
599
+
600
+ path = _Path(plugin_dir).resolve()
601
+ result = validate_plugin(path)
602
+
603
+ if as_json:
604
+ data = {
605
+ "plugin_name": result.plugin_name,
606
+ "path": str(result.path),
607
+ "passed": result.passed,
608
+ "checks": [
609
+ {
610
+ "rule": c.rule,
611
+ "name": c.name,
612
+ "passed": c.passed,
613
+ "detail": c.detail,
614
+ }
615
+ for c in result.checks
616
+ ],
617
+ }
618
+ click.echo(json_mod.dumps(data, indent=2))
619
+ else:
620
+ click.echo(f"Validating: {path.name} ({path})\n")
621
+
622
+ # Table header
623
+ click.echo(f" {'Rule':<6} {'Check':<25} {'Status':<8} {'Detail'}")
624
+ click.echo(f" {'─' * 6} {'─' * 25} {'─' * 8} {'─' * 30}")
625
+
626
+ for c in result.checks:
627
+ status = "PASS" if c.passed else "FAIL"
628
+ detail = c.detail or ""
629
+ click.echo(f" {c.rule:<6} {c.name:<25} {status:<8} {detail}")
630
+
631
+ # Summary
632
+ passed = sum(1 for c in result.checks if c.passed)
633
+ total = len(result.checks)
634
+ click.echo(f"\n {passed}/{total} checks passed.")
635
+
636
+ if result.passed:
637
+ click.echo(" All checks passed!")
638
+ else:
639
+ failed = [c for c in result.checks if not c.passed]
640
+ click.echo(f" {len(failed)} check(s) failed.")
641
+
642
+ if not result.passed:
643
+ raise SystemExit(1)
644
+
645
+
646
+ @cli.command("fix-plugin", help="Interactive auto-fix for failing compliance checks")
647
+ @click.argument("plugin_dir", default=".", type=click.Path(exists=True))
648
+ @click.option("--all", "apply_all", is_flag=True, default=False, help="Apply all fixes without prompting")
649
+ @click.option("--dry-run", is_flag=True, default=False, help="Show what would be fixed without writing")
650
+ @click.option("--rule", "only_rules", multiple=True, help="Only fix specific rules (e.g. --rule R4 --rule R6)")
651
+ def fix_plugin(plugin_dir, apply_all, dry_run, only_rules):
652
+ """Run compliance checks and interactively fix failing ones.
653
+
654
+ Shows a list of fixable issues and lets you pick which to apply.
655
+ Use --all to apply everything, or --rule R4 --rule R6 to target specific rules.
656
+
657
+ \b
658
+ Examples:
659
+ fastpluggy fix-plugin plugins/my_plugin # interactive
660
+ fastpluggy fix-plugin --all . # fix everything
661
+ fastpluggy fix-plugin --rule R4 --rule R6 . # only R4 and R6
662
+ fastpluggy fix-plugin --dry-run . # preview only
663
+ """
664
+ from pathlib import Path as _Path
665
+ from fastpluggy.core.plugin.validator import validate_plugin
666
+
667
+ path = _Path(plugin_dir).resolve()
668
+ result = validate_plugin(path)
669
+ plugin_name = result.plugin_name
670
+
671
+ failed = {c.rule: c for c in result.checks if not c.passed}
672
+
673
+ if not failed:
674
+ click.echo(click.style(f" All checks pass for {plugin_name} — nothing to fix.", fg="green"))
675
+ raise SystemExit(0)
676
+
677
+ # --- Build fixable items with descriptions ---
678
+ RULE_INFO = {
679
+ "R1": ("docs/ directory", "Create docs/ directory"),
680
+ "R2": ("README.md", "Create README.md with install/dev sections"),
681
+ "R3": ("[e2e] deps in pyproject.toml", "Add playwright to [project.optional-dependencies]"),
682
+ "R4": ("e2e/ directory", "Create e2e/ directory with .gitkeep"),
683
+ "R6": ("docs/screenshots/e2e/ directory", "Create docs/screenshots/e2e/ with .gitkeep"),
684
+ "R9": ("tests/ directory + stub", "Create tests/ with __init__.py and test stub"),
685
+ "R10": (".gitignore", "Create or update .gitignore with standard patterns"),
686
+ "R12": ("e2e/routes.json", "Create e2e/routes.json skeleton"),
687
+ }
688
+ NON_FIXABLE = {"R5", "R8", "R13"}
689
+
690
+ fixable = {r: c for r, c in failed.items() if r in RULE_INFO}
691
+ non_fixable = {r: c for r, c in failed.items() if r in NON_FIXABLE}
692
+
693
+ # --- Display issue list ---
694
+ click.echo(f"\n {click.style(plugin_name, bold=True)} — {len(failed)} issue(s) found\n")
695
+
696
+ for rule in sorted(fixable, key=lambda r: int(r[1:])):
697
+ short, desc = RULE_INFO[rule]
698
+ detail = failed[rule].detail
699
+ click.echo(f" {click.style(rule, fg='yellow', bold=True)} {short}")
700
+ click.echo(f" {click.style(desc, fg='cyan')}")
701
+ if detail:
702
+ click.echo(f" {detail}")
703
+
704
+ if non_fixable:
705
+ click.echo("")
706
+ for rule in sorted(non_fixable, key=lambda r: int(r[1:])):
707
+ click.echo(f" {click.style(rule, fg='red', bold=True)} {failed[rule].name} {click.style('(manual fix required)', fg='red')}")
708
+ if failed[rule].detail:
709
+ click.echo(f" {failed[rule].detail}")
710
+
711
+ if not fixable:
712
+ click.echo(click.style("\n No auto-fixable issues found.", fg="red"))
713
+ raise SystemExit(1)
714
+
715
+ # --- Select which rules to apply ---
716
+ if only_rules:
717
+ selected = [r for r in only_rules if r in fixable]
718
+ if not selected:
719
+ click.echo(click.style(f"\n None of {list(only_rules)} are fixable issues.", fg="red"))
720
+ raise SystemExit(1)
721
+ elif apply_all:
722
+ selected = sorted(fixable.keys(), key=lambda r: int(r[1:]))
723
+ click.echo(f"\n {click.style('--all', bold=True)}: applying {len(selected)} fix(es)")
724
+ else:
725
+ # Interactive selection
726
+ click.echo("")
727
+ choices = [
728
+ questionary.Choice(
729
+ title=f"{rule} {RULE_INFO[rule][0]} — {RULE_INFO[rule][1]}",
730
+ value=rule,
731
+ checked=True,
732
+ )
733
+ for rule in sorted(fixable, key=lambda r: int(r[1:]))
734
+ ]
735
+ selected = questionary.checkbox(
736
+ "Select fixes to apply:",
737
+ choices=choices,
738
+ ).ask()
739
+ if not selected:
740
+ click.echo(" No fixes selected.")
741
+ raise SystemExit(0)
742
+
743
+ click.echo("")
744
+ if dry_run:
745
+ click.echo(click.style(" DRY RUN — no files will be written\n", fg="magenta"))
746
+
747
+ # --- Apply selected fixes ---
748
+ fixed = []
749
+ skipped = []
750
+
751
+ # --- R1: docs/ directory ---
752
+ if "R1" in selected:
753
+ docs = path / "docs"
754
+ if dry_run:
755
+ click.echo(f" {click.style('[R1]', fg='yellow')} would create {docs.relative_to(path)}/")
756
+ else:
757
+ docs.mkdir(exist_ok=True)
758
+ click.echo(f" {click.style('[R1]', fg='green')} created {docs.relative_to(path)}/")
759
+ fixed.append("R1")
760
+
761
+ # --- R2: README.md ---
762
+ if "R2" in selected:
763
+ readme = path / "README.md"
764
+ label = _to_label(plugin_name)
765
+ content = (
766
+ f"# {label}\n"
767
+ "\n"
768
+ "A FastPluggy plugin.\n"
769
+ "\n"
770
+ "## Installation\n"
771
+ "\n"
772
+ "```bash\n"
773
+ 'pip install -e ".[dev]"\n'
774
+ "```\n"
775
+ "\n"
776
+ "## Development\n"
777
+ "\n"
778
+ "```bash\n"
779
+ "pytest tests/\n"
780
+ "```\n"
781
+ )
782
+ if dry_run:
783
+ click.echo(f" {click.style('[R2]', fg='yellow')} would create {readme.relative_to(path)}")
784
+ else:
785
+ readme.write_text(content)
786
+ click.echo(f" {click.style('[R2]', fg='green')} created {readme.relative_to(path)}")
787
+ fixed.append("R2")
788
+
789
+ # --- R3: e2e optional deps in pyproject.toml ---
790
+ if "R3" in selected:
791
+ pyproject = path / "pyproject.toml"
792
+ if pyproject.is_file():
793
+ text = pyproject.read_text()
794
+ e2e_block = (
795
+ '\ne2e = [\n'
796
+ ' "playwright",\n'
797
+ ']\n'
798
+ )
799
+ if "[project.optional-dependencies]" in text:
800
+ if dry_run:
801
+ click.echo(f" {click.style('[R3]', fg='yellow')} would add [e2e] deps to pyproject.toml")
802
+ else:
803
+ text = text.replace(
804
+ "[project.optional-dependencies]",
805
+ "[project.optional-dependencies]" + e2e_block,
806
+ 1,
807
+ )
808
+ pyproject.write_text(text)
809
+ click.echo(f" {click.style('[R3]', fg='green')} added [e2e] optional deps to pyproject.toml")
810
+ fixed.append("R3")
811
+ else:
812
+ if dry_run:
813
+ click.echo(f" {click.style('[R3]', fg='yellow')} would add [project.optional-dependencies] with e2e to pyproject.toml")
814
+ else:
815
+ text += (
816
+ "\n[project.optional-dependencies]\n"
817
+ + e2e_block
818
+ )
819
+ pyproject.write_text(text)
820
+ click.echo(f" {click.style('[R3]', fg='green')} added [project.optional-dependencies] with e2e to pyproject.toml")
821
+ fixed.append("R3")
822
+ else:
823
+ skipped.append(("R3", "pyproject.toml not found"))
824
+
825
+ # --- R4: e2e/ directory ---
826
+ if "R4" in selected:
827
+ e2e = path / "e2e"
828
+ if dry_run:
829
+ click.echo(f" {click.style('[R4]', fg='yellow')} would create {e2e.relative_to(path)}/")
830
+ else:
831
+ e2e.mkdir(exist_ok=True)
832
+ gitkeep = e2e / ".gitkeep"
833
+ if not gitkeep.exists():
834
+ gitkeep.write_text("")
835
+ click.echo(f" {click.style('[R4]', fg='green')} created {e2e.relative_to(path)}/")
836
+ fixed.append("R4")
837
+
838
+ # --- R6: docs/screenshots/e2e/ directory ---
839
+ if "R6" in selected:
840
+ ss = path / "docs" / "screenshots" / "e2e"
841
+ if dry_run:
842
+ click.echo(f" {click.style('[R6]', fg='yellow')} would create {ss.relative_to(path)}/")
843
+ else:
844
+ ss.mkdir(parents=True, exist_ok=True)
845
+ gitkeep = ss / ".gitkeep"
846
+ if not gitkeep.exists():
847
+ gitkeep.write_text("")
848
+ click.echo(f" {click.style('[R6]', fg='green')} created {ss.relative_to(path)}/")
849
+ fixed.append("R6")
850
+
851
+ # --- R9: tests/ directory + stub ---
852
+ if "R9" in selected:
853
+ tests = path / "tests"
854
+ if dry_run:
855
+ click.echo(f" {click.style('[R9]', fg='yellow')} would create {tests.relative_to(path)}/ with test stub")
856
+ else:
857
+ tests.mkdir(exist_ok=True)
858
+ init = tests / "__init__.py"
859
+ if not init.exists():
860
+ init.write_text("")
861
+ stub = tests / "test_plugin.py"
862
+ if not stub.exists():
863
+ plugin_class = _to_pascal_case(plugin_name)
864
+ stub.write_text(
865
+ f"from fastpluggy_plugin.{plugin_name}.plugin import {plugin_class}\n"
866
+ "\n\n"
867
+ "def test_plugin_class_exists():\n"
868
+ f" assert {plugin_class} is not None\n"
869
+ f' assert {plugin_class}.module_name == "{plugin_name}"\n'
870
+ )
871
+ click.echo(f" {click.style('[R9]', fg='green')} created {tests.relative_to(path)}/ with test stub")
872
+ fixed.append("R9")
873
+
874
+ # --- R10: .gitignore ---
875
+ if "R10" in selected:
876
+ gitignore = path / ".gitignore"
877
+ content = (
878
+ "# Python\n"
879
+ "__pycache__/\n"
880
+ "*.py[cod]\n"
881
+ "*.egg-info/\n"
882
+ "dist/\n"
883
+ "build/\n"
884
+ "\n"
885
+ "# Environments\n"
886
+ ".env\n"
887
+ ".venv/\n"
888
+ "\n"
889
+ "# IDE\n"
890
+ ".idea/\n"
891
+ "\n"
892
+ "# Data / temp\n"
893
+ "*.db\n"
894
+ "*.log\n"
895
+ "*.tmp\n"
896
+ "\n"
897
+ "# Test / coverage\n"
898
+ ".coverage\n"
899
+ ".pytest_cache/\n"
900
+ "htmlcov/\n"
901
+ "\n"
902
+ "# Node (e2e tests)\n"
903
+ "node_modules/\n"
904
+ "\n"
905
+ "# Generated\n"
906
+ ".plugin-manifest.json\n"
907
+ "\n"
908
+ "# Security\n"
909
+ ".env.local\n"
910
+ ".env.production\n"
911
+ ".env.*.local\n"
912
+ "*.pem\n"
913
+ "*.key\n"
914
+ "*.p12\n"
915
+ "*.pfx\n"
916
+ "credentials*\n"
917
+ "secrets*\n"
918
+ )
919
+ if gitignore.is_file():
920
+ existing = gitignore.read_text()
921
+ required = ["__pycache__/", "*.py[cod]", ".env", "*.db", "*.egg-info"]
922
+ missing = [p for p in required if p not in existing]
923
+ if missing:
924
+ if dry_run:
925
+ click.echo(f" {click.style('[R10]', fg='yellow')} would append missing patterns: {', '.join(missing)}")
926
+ else:
927
+ existing += "\n# Auto-added by fastpluggy fix-plugin\n" + "\n".join(missing) + "\n"
928
+ gitignore.write_text(existing)
929
+ click.echo(f" {click.style('[R10]', fg='green')} appended missing patterns to .gitignore")
930
+ fixed.append("R10")
931
+ else:
932
+ if dry_run:
933
+ click.echo(f" {click.style('[R10]', fg='yellow')} would create .gitignore")
934
+ else:
935
+ gitignore.write_text(content)
936
+ click.echo(f" {click.style('[R10]', fg='green')} created .gitignore")
937
+ fixed.append("R10")
938
+
939
+ # --- R12: e2e/routes.json ---
940
+ if "R12" in selected:
941
+ routes_json = path / "e2e" / "routes.json"
942
+ if dry_run:
943
+ click.echo(f" {click.style('[R12]', fg='yellow')} would create e2e/routes.json")
944
+ else:
945
+ (path / "e2e").mkdir(exist_ok=True)
946
+ if not routes_json.exists():
947
+ import json as json_mod
948
+ routes_json.write_text(json_mod.dumps({"routes": []}, indent=2) + "\n")
949
+ click.echo(f" {click.style('[R12]', fg='green')} created e2e/routes.json")
950
+ fixed.append("R12")
951
+
952
+ # --- Summary ---
953
+ click.echo(f"\n {click.style('Fixed:', bold=True)} {len(fixed)} | "
954
+ f"{click.style('Skipped:', bold=True)} {len(skipped)} | "
955
+ f"{click.style('Total failed:', bold=True)} {len(failed)}")
956
+ if skipped:
957
+ click.echo(f"\n {click.style('Skipped (cannot auto-fix):', fg='red')}")
958
+ for rule, detail in skipped:
959
+ click.echo(f" {rule}: {detail}")
960
+ if non_fixable:
961
+ click.echo(f"\n {click.style('Manual fix required:', fg='red')}")
962
+ for rule in sorted(non_fixable, key=lambda r: int(r[1:])):
963
+ click.echo(f" {rule}: {failed[rule].detail}")
964
+
965
+ if dry_run:
966
+ click.echo(click.style("\n (dry-run — no files were written)", fg="magenta"))
967
+
968
+
969
+ @cli.command("help", help="Show available commands")
970
+ def help_cmd():
971
+ print("""
972
+ FastPluggy CLI - Available Commands:
973
+
974
+ fastpluggy new [project_name] Create a new FastPluggy project with:
975
+ - Modern FastAPI app structure with CORS middleware
976
+ - Environment variables for FastPluggy setup
977
+ - Optional SSL certificate generation
978
+ - .env file for configuration
979
+ - pyproject.toml for dependency management
980
+ - Optional example module
981
+
982
+ fastpluggy new-plugin [plugin_name] Scaffold a new plugin with source, tests, templates.
983
+
984
+ fastpluggy fix-plugin [plugin_dir] Interactive auto-fix for compliance checks.
985
+ [--all] Apply all fixes without prompting.
986
+ [--rule R4 --rule R6] Target specific rules only.
987
+ [--dry-run] Preview changes without writing.
988
+
989
+ fastpluggy start-dev-server Start a FastPluggy dev server. Auto-discovers
990
+ [--port PORT] all installed plugins via entry points.
991
+ [--host HOST] Defaults DATABASE_URL to SQLite if not set.
992
+ [--reload] Use --reload for hot-reload during development.
993
+
994
+ fastpluggy help Show this help message.
995
+ """)
996
+
997
+ _load_plugin_commands(cli)
998
+
999
+ if __name__ == '__main__':
1000
+ cli()