Coverage for fastblocks / cli.py: 18%
480 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1import asyncio
3# Replace ACB actions with standard Python alternatives
4import json
5import os
6import signal
8# Remove ACB logger intercept handler - use standard logging
9# with suppress(ImportError):
10# # MIGRATED: Removed ACB import - logger import InterceptHandler
11# for logger_name in ("uvicorn", "uvicorn.access", "uvicorn.error"):
12# logger = logging.getLogger(logger_name)
13# logger.handlers.clear()
14# logger.addHandler(InterceptHandler())
15# logger.setLevel(logging.DEBUG)
16# logger.propagate = False
17import sys
18import typing as t
19from enum import Enum
20from importlib.metadata import version as get_version
21from pathlib import Path
22from subprocess import DEVNULL
23from subprocess import run as execute
24from typing import Annotated
26import nest_asyncio
27import typer
28import uvicorn
29import yaml
30from anyio import Path as AsyncPath
31from granian import Granian
33# Use standard rich console instead of ACB console
34from rich.console import Console
36console = Console()
38nest_asyncio.apply()
39__all__ = ("cli", "components", "create", "dev", "run")
40default_adapters = {
41 "routes": "default",
42 "templates": "jinja2",
43 "auth": "basic",
44 "sitemap": "asgi",
45}
46fastblocks_path = Path(__file__).parent
47apps_path = Path.cwd()
49# Check if running in the FastBlocks library directory itself
50# Skip this check during tests by examining if we're in a test environment
52is_testing = os.getenv("PYTEST_CURRENT_TEST") or "pytest" in sys.modules
53if Path.cwd() == fastblocks_path and not is_testing:
54 msg = "FastBlocks can not be run in the same directory as FastBlocks itself. Run `python -m fastblocks create`. Move into the app directory and try again."
55 raise SystemExit(
56 msg,
57 )
58cli = typer.Typer(rich_markup_mode="rich")
61class Styles(str, Enum):
62 bulma = "bulma"
63 webawesome = "webawesome"
64 custom = "custom"
66 def __str__(self) -> str:
67 return t.cast(str, self.value)
70run_args: dict[str, t.Any] = {"app": "main:app"}
71dev_args: dict[str, t.Any] = run_args | {"port": 8000, "reload": True}
72granian_dev_args: dict[str, t.Any] = dev_args | {
73 "address": "127.0.0.1",
74 "reload_paths": [Path.cwd(), fastblocks_path],
75 "interface": "asgi",
76 "log_enabled": False,
77 "log_access": True,
78 "reload_ignore_dirs": ["tmp", "settings", "templates"],
79}
80uvicorn_dev_args: dict[str, t.Any] = dev_args | {
81 "host": "127.0.0.1",
82 "reload_includes": ["*.py", str(Path.cwd()), str(fastblocks_path)],
83 "reload_excludes": ["tmp/*", "settings/*", "templates/*"],
84 "lifespan": "on",
85}
88def setup_signal_handlers() -> None:
89 import sys
91 def signal_handler(_signum: int, _frame: t.Any) -> None:
92 sys.exit(0)
94 signal.signal(signal.SIGINT, signal_handler)
95 signal.signal(signal.SIGTERM, signal_handler)
98@cli.command()
99def run(docker: bool = False, granian: bool = False, host: str = "127.0.0.1") -> None:
100 if docker:
101 execute(
102 f"docker run -it -ePORT=8080 -p8080:8080 {Path.cwd().stem}".split(),
103 )
104 else:
105 setup_signal_handlers()
106 if granian:
107 from granian.constants import Interfaces
109 Granian("main:app", address=host, interface=Interfaces.ASGI).serve()
110 else:
111 uvicorn.run(app=run_args["app"], host=host, lifespan="on", log_config=None)
114@cli.command()
115def dev(granian: bool = False) -> None:
116 setup_signal_handlers()
117 if granian:
118 from granian.constants import Interfaces
120 Granian(
121 "main:app",
122 address="127.0.0.1",
123 port=8000,
124 reload=True,
125 reload_paths=[Path.cwd(), fastblocks_path],
126 interface=Interfaces.ASGI,
127 log_enabled=False,
128 log_access=True,
129 ).serve()
130 else:
131 uvicorn.run(
132 app="main:app",
133 host="127.0.0.1",
134 port=8000,
135 reload=True,
136 reload_includes=["*.py", str(Path.cwd()), str(fastblocks_path)],
137 reload_excludes=["tmp/*", "settings/*", "templates/*"],
138 lifespan="on",
139 log_config=None,
140 )
143def _display_adapters() -> None:
144 # Replace ACB adapter discovery with Oneiric adapter registry
145 from oneiric.core.resolution import Resolver
147 console.print("[bold green]Available Adapters:[/bold green]")
149 # Use Oneiric resolver to discover adapters
150 depends = Resolver()
151 try:
152 # Try to get adapter registry from Oneiric
153 adapter_registry = depends.resolve("adapter_registry")
154 if adapter_registry:
155 adapters = adapter_registry.get_all_adapters()
156 else:
157 # Fallback: try to discover adapters manually
158 adapters = []
159 console.print(" [dim]Adapter registry not available[/dim]")
160 return
161 except Exception:
162 console.print(" [dim]No adapters found[/dim]")
163 return
165 if not adapters:
166 console.print(" [dim]No adapters found[/dim]")
167 return
169 categories: dict[str, list[t.Any]] = {}
170 for adapter in adapters:
171 if adapter.category not in categories:
172 categories[adapter.category] = []
173 categories[adapter.category].append(adapter)
174 for category in sorted(categories.keys()):
175 console.print(f"\n [bold cyan]{category.upper()}:[/bold cyan]")
176 for adapter in sorted(categories[category], key=lambda a: a.name):
177 _display_adapter_info(adapter)
180def _display_adapter_info(adapter: t.Any) -> None:
181 status = "[green]✓[/green]" if adapter.installed else "[red]✗[/red]"
182 enabled = "[yellow]enabled[/yellow]" if adapter.enabled else "[dim]disabled[/dim]"
183 console.print(f" {status} [white]{adapter.name}[/white] - {enabled}")
184 if adapter.module:
185 console.print(f" [dim]{adapter.module}[/dim]")
188def _display_default_config() -> None:
189 console.print("\n[bold green]FastBlocks Default Configuration:[/bold green]")
190 for category, default_name in default_adapters.items():
191 console.print(f" [cyan]{category}[/cyan]: [white]{default_name}[/white]")
194def _display_actions() -> None:
195 console.print("\n[bold green]FastBlocks Actions:[/bold green]")
196 try:
197 from fastblocks.actions.minify import minify
199 console.print(" [cyan]minify[/cyan]:")
200 console.print(f" [white]- css[/white] ([dim]{minify.css.__name__}[/dim])")
201 console.print(f" [white]- js[/white] ([dim]{minify.js.__name__}[/dim])")
202 except ImportError:
203 console.print(" [dim]Minify actions not available[/dim]")
206@cli.command()
207def components() -> None:
208 try:
209 console.print("\n[bold blue]FastBlocks Components[/bold blue]\n")
210 _display_adapters()
211 _display_default_config()
212 _display_actions()
213 _display_htmy_commands()
214 except Exception as e:
215 console.print(f"[red]Error displaying components: {e}[/red]")
216 console.print("[dim]Make sure you're in a FastBlocks project directory[/dim]")
219def _display_htmy_commands() -> None:
220 console.print("\n[bold green]HTMY Component Commands:[/bold green]")
221 console.print(" [cyan]scaffold[/cyan]: Create new HTMY components")
222 console.print(" [cyan]list[/cyan]: List all discovered components")
223 console.print(" [cyan]validate[/cyan]: Validate component structure")
224 console.print(" [cyan]info[/cyan]: Get component metadata")
227# Component scaffolding helpers
228_COMPONENT_TYPE_MAP = {
229 "basic": "BASIC",
230 "dataclass": "DATACLASS",
231 "htmx": "HTMX",
232 "composite": "COMPOSITE",
233}
235_TYPE_MAP = {
236 "str": str,
237 "int": int,
238 "float": float,
239 "bool": bool,
240 "list": list,
241 "dict": dict,
242}
245def _parse_component_type(type_str: str) -> t.Any:
246 """Parse component type string to ComponentType enum."""
247 from fastblocks.adapters.templates._htmy_components import ComponentType
249 type_name = _COMPONENT_TYPE_MAP.get(type_str.lower(), "DATACLASS")
250 return getattr(ComponentType, type_name)
253def _parse_component_props(props: str) -> dict[str, type]:
254 """Parse props string into dict of name:type pairs."""
255 if not props:
256 return {}
258 parsed = {}
259 for prop_def in props.split(","):
260 if ":" not in prop_def:
261 continue
262 prop_name, prop_type = prop_def.strip().split(":", 1)
263 parsed[prop_name] = _TYPE_MAP.get(prop_type, str)
264 return parsed
267def _parse_component_children(children: str) -> list[str] | None:
268 """Parse children string into list of component names."""
269 if not children:
270 return None
271 return [c.strip() for c in children.split(",") if c.strip()]
274def _build_scaffold_kwargs(
275 parsed_props: dict[str, t.Any],
276 htmx: bool,
277 component_type: t.Any,
278 endpoint: str,
279 trigger: str,
280 target: str,
281 parsed_children: list[str] | None,
282) -> dict[str, t.Any]:
283 """Build kwargs dict for component scaffolding."""
284 from fastblocks.adapters.templates._htmy_components import ComponentType
286 kwargs: dict[str, t.Any] = {}
288 if parsed_props:
289 kwargs["props"] = parsed_props
291 if htmx or component_type == ComponentType.HTMX:
292 kwargs["htmx_enabled"] = True
293 if endpoint:
294 kwargs["endpoint"] = endpoint
295 kwargs["trigger"] = trigger
296 kwargs["target"] = target
298 if parsed_children:
299 kwargs["children"] = parsed_children
301 return kwargs
304@cli.command()
305def scaffold(
306 name: Annotated[str, typer.Argument(help="Component name")],
307 type: Annotated[
308 str,
309 typer.Option(
310 "--type", "-t", help="Component type: basic, dataclass, htmx, composite"
311 ),
312 ] = "dataclass",
313 htmx: Annotated[
314 bool, typer.Option("--htmx", "-x", help="Enable HTMX features")
315 ] = False,
316 endpoint: Annotated[
317 str, typer.Option("--endpoint", "-e", help="HTMX endpoint URL")
318 ] = "",
319 trigger: Annotated[
320 str, typer.Option("--trigger", help="HTMX trigger event")
321 ] = "click",
322 target: Annotated[
323 str, typer.Option("--target", help="HTMX target selector")
324 ] = "#content",
325 props: Annotated[
326 str,
327 typer.Option("--props", "-p", help="Component props as 'name:type,name:type'"),
328 ] = "",
329 children: Annotated[
330 str, typer.Option("--children", "-c", help="Child components as 'comp1,comp2'")
331 ] = "",
332 path: Annotated[str, typer.Option("--path", help="Custom component path")] = "",
333) -> None:
334 """Scaffold a new HTMY component."""
335 import asyncio
336 from pathlib import Path
338 async def scaffold_component() -> None:
339 try:
340 from oneiric.core.resolution import Resolver
342 # Get HTMY adapter using Oneiric resolver
343 depends = Resolver()
344 htmy_adapter = await depends.resolve("htmy")
345 if htmy_adapter is None:
346 console.print(
347 "[red]HTMY adapter not found. Make sure you're in a FastBlocks project.[/red]"
348 )
349 return
351 # Parse inputs using helper functions
352 component_type = _parse_component_type(type)
353 parsed_props = _parse_component_props(props)
354 parsed_children = _parse_component_children(children)
356 # Build kwargs
357 kwargs = _build_scaffold_kwargs(
358 parsed_props,
359 htmx,
360 component_type,
361 endpoint,
362 trigger,
363 target,
364 parsed_children,
365 )
367 # Custom path
368 target_path = Path(path) if path else None
370 # Scaffold component
371 created_path = await htmy_adapter.scaffold_component(
372 name=name,
373 component_type=component_type,
374 target_path=target_path,
375 **kwargs,
376 )
378 console.print(
379 f"[green]✓[/green] Created {component_type.value} component '{name}' at {created_path}"
380 )
382 except Exception as e:
383 console.print(f"[red]Error scaffolding component: {e}[/red]")
385 asyncio.run(scaffold_component())
388def _get_component_status_color(status_value: str) -> str:
389 """Get the color for a component status."""
390 return {
391 "discovered": "yellow",
392 "validated": "green",
393 "compiled": "blue",
394 "ready": "green",
395 "error": "red",
396 "deprecated": "dim",
397 }.get(status_value, "white")
400def _display_component_entry(name: str, metadata: t.Any) -> None:
401 """Display a single component entry with status and metadata."""
402 status_color = _get_component_status_color(metadata.status.value)
404 console.print(
405 f" [{status_color}]●[/{status_color}] [white]{name}[/white] ({metadata.type.value})"
406 )
407 console.print(f" [dim]{metadata.path}[/dim]")
409 if metadata.error_message:
410 console.print(f" [red]Error: {metadata.error_message}[/red]")
411 elif metadata.docstring:
412 # Show first line of docstring
413 first_line = metadata.docstring.split("\n")[0].strip()
414 if first_line:
415 console.print(f" [dim]{first_line}[/dim]")
418@cli.command(name="list")
419def list_components() -> None:
420 """List all discovered HTMY components."""
421 import asyncio
423 async def list_all_components() -> None:
424 try:
425 from oneiric.core.resolution import Resolver
427 # Get HTMY adapter using Oneiric resolver
428 depends = Resolver()
429 htmy_adapter = await depends.resolve("htmy")
430 if htmy_adapter is None:
431 console.print(
432 "[red]HTMY adapter not found. Make sure you're in a FastBlocks project.[/red]"
433 )
434 return
436 components = await htmy_adapter.discover_components()
438 if not components:
439 console.print("[dim]No components found.[/dim]")
440 return
442 console.print(
443 f"\n[bold green]Found {len(components)} HTMY components:[/bold green]\n"
444 )
446 for name, metadata in components.items():
447 _display_component_entry(name, metadata)
449 except Exception as e:
450 console.print(f"[red]Error listing components: {e}[/red]")
452 asyncio.run(list_all_components())
455def _display_basic_metadata(component: str, metadata: t.Any) -> None:
456 """Display basic component metadata."""
457 console.print(f"\n[bold blue]Component: {component}[/bold blue]")
458 console.print(f" [cyan]Type:[/cyan] {metadata.type.value}")
459 console.print(f" [cyan]Status:[/cyan] {metadata.status.value}")
460 console.print(f" [cyan]Path:[/cyan] {metadata.path}")
463def _display_optional_metadata(metadata: t.Any) -> None:
464 """Display optional component metadata fields."""
465 if metadata.last_modified:
466 console.print(f" [cyan]Modified:[/cyan] {metadata.last_modified}")
468 if metadata.docstring:
469 console.print(f" [cyan]Description:[/cyan] {metadata.docstring}")
472def _display_htmx_attributes(metadata: t.Any) -> None:
473 """Display HTMX attributes if present."""
474 if metadata.htmx_attributes:
475 console.print(" [cyan]HTMX Attributes:[/cyan]")
476 for key, value in metadata.htmx_attributes.items():
477 console.print(f" {key}: {value}")
480def _display_dependencies(metadata: t.Any) -> None:
481 """Display component dependencies if present."""
482 if metadata.dependencies:
483 console.print(
484 f" [cyan]Dependencies:[/cyan] {', '.join(metadata.dependencies)}"
485 )
488def _display_status_message(metadata: t.Any) -> None:
489 """Display status-specific message."""
490 if metadata.status.value == "error":
491 console.print(f" [red]Error:[/red] {metadata.error_message}")
492 elif metadata.status.value == "ready":
493 console.print(" [green]✓ Component is ready[/green]")
496@cli.command()
497def validate(
498 component: Annotated[str, typer.Argument(help="Component name to validate")],
499) -> None:
500 """Validate a specific HTMY component."""
501 import asyncio
503 async def validate_component() -> None:
504 try:
505 from oneiric.core.resolution import Resolver
507 # Get HTMY adapter using Oneiric resolver
508 depends = Resolver()
509 htmy_adapter = await depends.resolve("htmy")
510 if htmy_adapter is None:
511 console.print(
512 "[red]HTMY adapter not found. Make sure you're in a FastBlocks project.[/red]"
513 )
514 return
516 metadata = await htmy_adapter.validate_component(component)
518 _display_basic_metadata(component, metadata)
519 _display_optional_metadata(metadata)
520 _display_htmx_attributes(metadata)
521 _display_dependencies(metadata)
522 _display_status_message(metadata)
524 except Exception as e:
525 console.print(f"[red]Error validating component '{component}': {e}[/red]")
527 asyncio.run(validate_component())
530@cli.command()
531def info(
532 component: Annotated[str, typer.Argument(help="Component name to get info for")],
533) -> None:
534 """Get detailed information about an HTMY component."""
535 import asyncio
537 def _display_component_class_info(
538 component_class: type, component_name: str
539 ) -> None:
540 """Display component class information including dataclass fields and HTMX status."""
541 console.print(f"\n[bold blue]Component: {component_name}[/bold blue]")
542 console.print(f" [cyan]Class:[/cyan] {component_class.__name__}")
543 console.print(f" [cyan]Module:[/cyan] {component_class.__module__}")
545 # Check if it's a dataclass
546 from dataclasses import fields, is_dataclass
548 if is_dataclass(component_class):
549 console.print(" [cyan]Fields:[/cyan]")
550 for field in fields(component_class):
551 console.print(f" {field.name}: {field.type}")
553 # Check for HTMX mixin
554 from fastblocks.adapters.templates._htmy_components import HTMXComponentMixin
556 if issubclass(component_class, HTMXComponentMixin):
557 console.print(" [cyan]HTMX Enabled:[/cyan] Yes")
559 def _display_component_metadata(metadata: t.Any) -> None:
560 """Display component metadata information."""
561 console.print(f" [cyan]Type:[/cyan] {metadata.type.value}")
562 console.print(f" [cyan]Status:[/cyan] {metadata.status.value}")
563 console.print(f" [cyan]Path:[/cyan] {metadata.path}")
565 async def get_component_info() -> None:
566 try:
567 from oneiric.core.resolution import Resolver
569 # Get HTMY adapter using Oneiric resolver
570 depends = Resolver()
571 htmy_adapter = await depends.resolve("htmy")
572 if htmy_adapter is None:
573 console.print(
574 "[red]HTMY adapter not found. Make sure you're in a FastBlocks project.[/red]"
575 )
576 return
578 # Get component metadata
579 metadata = await htmy_adapter.validate_component(component)
581 # Try to get component class for more info
582 try:
583 component_class = await htmy_adapter.get_component_class(component)
584 _display_component_class_info(component_class, component)
585 except Exception as e:
586 console.print(f"[red]Could not load component class: {e}[/red]")
588 # Show metadata
589 _display_component_metadata(metadata)
591 except Exception as e:
592 console.print(
593 f"[red]Error getting info for component '{component}': {e}[/red]"
594 )
596 asyncio.run(get_component_info())
599def _get_severity_color(severity: str) -> str:
600 """Get the color for an error severity level."""
601 return {
602 "error": "red",
603 "warning": "yellow",
604 "info": "blue",
605 "hint": "dim",
606 }.get(severity, "white")
609def _display_syntax_error(error: t.Any) -> None:
610 """Display a single syntax error with formatting."""
611 severity_color = _get_severity_color(error.severity)
613 console.print(
614 f" [{severity_color}]{error.severity.upper()}[/{severity_color}] "
615 f"Line {error.line + 1}, Column {error.column + 1}: {error.message}"
616 )
618 if error.fix_suggestion:
619 console.print(f" [dim]Fix: {error.fix_suggestion}[/dim]")
621 if error.code:
622 console.print(f" [dim]Code: {error.code}[/dim]")
625def _display_syntax_errors(file_path: str, errors: list[t.Any]) -> None:
626 """Display all syntax errors for a file."""
627 console.print(f"\n[bold red]Syntax errors found in {file_path}:[/bold red]")
628 for error in errors:
629 _display_syntax_error(error)
632@cli.command()
633def syntax_check(
634 file_path: Annotated[
635 str, typer.Argument(help="Path to FastBlocks template file to check")
636 ],
637 format_output: Annotated[
638 bool, typer.Option("--format", help="Format the output for better readability")
639 ] = False,
640) -> None:
641 """Check FastBlocks template syntax for errors and warnings."""
642 import asyncio
644 async def check_syntax() -> None:
645 try:
646 from pathlib import Path
648 from oneiric.core.resolution import Resolver
650 # Get syntax support using Oneiric resolver
651 depends = Resolver()
652 syntax_support = await depends.resolve("syntax_support")
653 if syntax_support is None:
654 console.print(
655 "[red]Syntax support not available. Make sure you're in a FastBlocks project.[/red]"
656 )
657 return
659 template_path = Path(file_path)
660 if not template_path.exists():
661 console.print(f"[red]File not found: {file_path}[/red]")
662 return
664 content = template_path.read_text()
665 errors = syntax_support.check_syntax(content, template_path)
667 if not errors:
668 console.print(f"[green]✓ No syntax errors found in {file_path}[/green]")
669 return
671 _display_syntax_errors(file_path, errors)
673 except Exception as e:
674 console.print(f"[red]Error checking syntax: {e}[/red]")
676 asyncio.run(check_syntax())
679@cli.command()
680def format_template(
681 file_path: Annotated[
682 str, typer.Argument(help="Path to FastBlocks template file to format")
683 ],
684 in_place: Annotated[
685 bool, typer.Option("--in-place", "-i", help="Format file in place")
686 ] = False,
687) -> None:
688 """Format a FastBlocks template file."""
689 import asyncio
691 async def format_file() -> None:
692 try:
693 from pathlib import Path
695 from oneiric.core.resolution import Resolver
697 # Get syntax support using Oneiric resolver
698 depends = Resolver()
699 syntax_support = await depends.resolve("syntax_support")
700 if syntax_support is None:
701 console.print(
702 "[red]Syntax support not available. Make sure you're in a FastBlocks project.[/red]"
703 )
704 return
706 template_path = Path(file_path)
707 if not template_path.exists():
708 console.print(f"[red]File not found: {file_path}[/red]")
709 return
711 content = template_path.read_text()
712 formatted = syntax_support.format_template(content)
714 if formatted == content:
715 console.print(f"[green]✓ File {file_path} is already formatted[/green]")
716 return
718 if in_place:
719 template_path.write_text(formatted)
720 console.print(f"[green]✓ Formatted {file_path} in place[/green]")
721 else:
722 console.print(formatted)
724 except Exception as e:
725 console.print(f"[red]Error formatting template: {e}[/red]")
727 asyncio.run(format_file())
730@cli.command()
731def generate_ide_config(
732 output_dir: Annotated[
733 str,
734 typer.Option("--output", "-o", help="Output directory for IDE configurations"),
735 ] = ".vscode",
736 ide: Annotated[
737 str, typer.Option(help="IDE to generate config for (vscode, vim, emacs)")
738 ] = "vscode",
739) -> None:
740 """Generate IDE configuration files for FastBlocks syntax support."""
741 import asyncio
743 async def generate_config() -> None:
744 try:
745 from pathlib import Path
747 output_path = Path(output_dir)
748 output_path.mkdir(exist_ok=True)
750 if ide == "vscode":
751 # Generate VS Code extension configuration
752 from fastblocks.adapters.templates._language_server import (
753 generate_textmate_grammar,
754 generate_vscode_extension,
755 )
757 # Package.json for extension
758 package_json = generate_vscode_extension()
759 (output_path / "package.json").write_text(
760 json.dumps(package_json, indent=2)
761 )
763 # TextMate grammar
764 grammar = generate_textmate_grammar()
765 syntaxes_dir = output_path / "syntaxes"
766 syntaxes_dir.mkdir(exist_ok=True)
767 (syntaxes_dir / "fastblocks.tmLanguage.json").write_text(
768 json.dumps(grammar, indent=2)
769 )
771 # Language configuration
772 lang_config = {
773 "comments": {"blockComment": ["[#", "#]"]},
774 "brackets": [["[[", "]]"], ["[%", "%]"], ["[#", "#]"]],
775 "autoClosingPairs": [
776 {"open": "[[", "close": "]]"},
777 {"open": "[%", "close": "%]"},
778 {"open": "[#", "close": "#]"},
779 {"open": '"', "close": '"'},
780 {"open": "'", "close": "'"},
781 ],
782 "surroundingPairs": [
783 ["[[", "]]"],
784 ["[%", "%]"],
785 ["[#", "#]"],
786 ['"', '"'],
787 ["'", "'"],
788 ],
789 }
790 (output_path / "language-configuration.json").write_text(
791 json.dumps(lang_config, indent=2)
792 )
794 # Settings for FastBlocks language server
795 settings = {
796 "fastblocks.languageServer.enabled": True,
797 "fastblocks.languageServer.port": 7777,
798 "fastblocks.completion.enabled": True,
799 "fastblocks.diagnostics.enabled": True,
800 "files.associations": {
801 "*.fb.html": "fastblocks",
802 "*.fastblocks": "fastblocks",
803 },
804 }
805 (output_path / "settings.json").write_text(
806 json.dumps(settings, indent=2)
807 )
809 console.print(
810 f"[green]✓ VS Code configuration generated in {output_path}[/green]"
811 )
812 console.print(" Files created:")
813 console.print(" - package.json (extension manifest)")
814 console.print(" - language-configuration.json")
815 console.print(" - syntaxes/fastblocks.tmLanguage.json")
816 console.print(" - settings.json")
818 elif ide == "vim":
819 # Generate Vim configuration
820 vim_syntax = """
821" Vim syntax file for FastBlocks templates
822" Language: FastBlocks
823" Maintainer: FastBlocks Team
825if exists("b:current_syntax")
826 finish
827endif
829" FastBlocks delimiters
830syn region fastblocksVariable start="\\[\\[" end="\\]\\]" contains=fastblocksFilter,fastblocksString
831syn region fastblocksBlock start="\\[%" end="%\\]" contains=fastblocksKeyword,fastblocksString
832syn region fastblocksComment start="\\[#" end="#\\]"
834" Keywords
835syn keyword fastblocksKeyword if else elif endif for endfor block endblock extends include set macro endmacro
837" Filters
838syn match fastblocksFilter "|\\s*\\w\\+" contained
840" Strings
841syn region fastblocksString start='"' end='"' contained
842syn region fastblocksString start="'" end="'" contained
844" Highlighting
845hi def link fastblocksVariable Special
846hi def link fastblocksBlock Keyword
847hi def link fastblocksComment Comment
848hi def link fastblocksKeyword Statement
849hi def link fastblocksFilter Function
850hi def link fastblocksString String
852let b:current_syntax = "fastblocks"
853"""
854 (output_path / "fastblocks.vim").write_text(vim_syntax)
855 console.print(
856 f"[green]✓ Vim syntax file generated: {output_path}/fastblocks.vim[/green]"
857 )
859 elif ide == "emacs":
860 # Generate Emacs configuration
861 emacs_mode = """
862;;; fastblocks-mode.el --- Major mode for FastBlocks templates
864(defvar fastblocks-mode-syntax-table
865 (let ((table (make-syntax-table)))
866 (modify-syntax-entry ?\" "\\\"" table)
867 (modify-syntax-entry ?\' "\\\"" table)
868 table)
869 "Syntax table for `fastblocks-mode'.")
871(defvar fastblocks-font-lock-keywords
872 '(("\\\\[\\\\[.*?\\\\]\\\\]" . font-lock-variable-name-face)
873 ("\\\\[%.*?%\\\\]" . font-lock-keyword-face)
874 ("\\\\[#.*?#\\\\]" . font-lock-comment-face)
875 ("\\\\b\\\\(if\\\\|else\\\\|elif\\\\|endif\\\\|for\\\\|endfor\\\\|block\\\\|endblock\\\\|extends\\\\|include\\\\|set\\\\|macro\\\\|endmacro\\\\)\\\\b" . font-lock-builtin-face))
876 "Font lock keywords for FastBlocks mode.")
878(define-derived-mode fastblocks-mode html-mode "FastBlocks"
879 "Major mode for editing FastBlocks templates."
880 (setq font-lock-defaults '(fastblocks-font-lock-keywords)))
882(add-to-list 'auto-mode-alist '("\\\\.fb\\\\.html\\\\'" . fastblocks-mode))
883(add-to-list 'auto-mode-alist '("\\\\.fastblocks\\\\'" . fastblocks-mode))
885(provide 'fastblocks-mode)
886;;; fastblocks-mode.el ends here
887"""
888 (output_path / "fastblocks-mode.el").write_text(emacs_mode)
889 console.print(
890 f"[green]✓ Emacs mode file generated: {output_path}/fastblocks-mode.el[/green]"
891 )
893 else:
894 console.print(f"[red]Unsupported IDE: {ide}[/red]")
895 console.print("Supported IDEs: vscode, vim, emacs")
897 except Exception as e:
898 console.print(f"[red]Error generating IDE configuration: {e}[/red]")
900 asyncio.run(generate_config())
903@cli.command()
904def start_language_server(
905 port: Annotated[
906 int, typer.Option("--port", "-p", help="Port to run language server on")
907 ] = 7777,
908 host: Annotated[
909 str, typer.Option("--host", help="Host to bind language server to")
910 ] = "localhost",
911 stdio: Annotated[
912 bool, typer.Option("--stdio", help="Use stdio instead of TCP")
913 ] = False,
914) -> None:
915 """Start the FastBlocks Language Server."""
916 import asyncio
918 async def start_server() -> None:
919 try:
920 from oneiric.core.resolution import Resolver
922 # Get language server using Oneiric resolver
923 depends = Resolver()
924 language_server = await depends.resolve("language_server")
925 if language_server is None:
926 console.print(
927 "[red]Language server not available. Make sure you're in a FastBlocks project.[/red]"
928 )
929 return
931 if stdio:
932 console.print(
933 "[blue]Starting FastBlocks Language Server in stdio mode...[/blue]"
934 )
935 # In a real implementation, this would handle stdio communication
936 console.print(
937 "[yellow]Stdio mode not yet implemented. Use TCP mode.[/yellow]"
938 )
939 else:
940 console.print(
941 f"[blue]Starting FastBlocks Language Server on {host}:{port}...[/blue]"
942 )
943 console.print("[green]Language Server started successfully![/green]")
944 console.print(f"Connect your IDE to: {host}:{port}")
946 # Keep server running using event-based approach
947 stop_event = asyncio.Event()
948 try:
949 await stop_event.wait()
950 except KeyboardInterrupt:
951 console.print("\n[yellow]Language server stopped.[/yellow]")
953 except Exception as e:
954 console.print(f"[red]Error starting language server: {e}[/red]")
956 asyncio.run(start_server())
959@cli.command()
960def create(
961 app_name: Annotated[
962 str,
963 typer.Option(prompt=True, help="Name of your application"),
964 ],
965 style: Annotated[
966 Styles,
967 typer.Option(
968 prompt=True,
969 help="The style (css, or web component, framework) you want to use[{','.join(Styles._member_names_)}]",
970 ),
971 ] = Styles.bulma,
972 domain: Annotated[
973 str,
974 typer.Option(prompt=True, help="Application domain"),
975 ] = "example.com",
976) -> None:
977 app_path = apps_path / app_name
978 app_path.mkdir(exist_ok=True)
979 os.chdir(app_path)
980 templates = Path("templates")
981 for p in (
982 templates / "base/blocks",
983 templates / f"{style}/blocks",
984 templates / f"{style}/theme",
985 Path("adapters"),
986 Path("actions"),
987 ):
988 p.mkdir(parents=True, exist_ok=True)
989 for p in (
990 Path("models.py"),
991 Path("routes.py"),
992 Path("main.py"),
993 Path(".envrc"),
994 Path("pyproject.toml"),
995 Path("__init__.py"),
996 Path("adapters/__init__.py"),
997 Path("actions/__init__.py"),
998 ):
999 p.touch()
1000 for template_file in (
1001 "main.py.tmpl",
1002 ".envrc",
1003 "pyproject.toml.tmpl",
1004 "Procfile.tmpl",
1005 ):
1006 template_path = Path(template_file)
1007 target_path = Path(template_file.replace(".tmpl", ""))
1008 target_path.write_text(
1009 (fastblocks_path / template_path).read_text().replace("APP_NAME", app_name),
1010 )
1011 commands = (
1012 ["direnv", "allow", "."],
1013 ["pdm", "install"],
1014 ["python", "-m", "fastblocks", "run"],
1015 )
1016 for command in commands:
1017 execute(command, stdout=DEVNULL, stderr=DEVNULL)
1019 async def update_settings(settings: str, values: dict[str, t.Any]) -> None:
1020 settings_path = AsyncPath(app_path / "settings")
1021 content = (settings_path / f"{settings}.yml").read_text()
1022 settings_dict = yaml.safe_load(content) or {}
1023 settings_dict.update(values)
1024 output_content = yaml.safe_dump(settings_dict)
1025 (settings_path / f"{settings}.yml").write_text(output_content)
1027 async def update_configs() -> None:
1028 await update_settings("debug", {"fastblocks": False})
1029 await update_settings("adapters", default_adapters)
1030 await update_settings(
1031 "app", {"title": "Welcome to FastBlocks", "domain": domain}
1032 )
1034 asyncio.run(update_configs())
1035 console.print(
1036 f"\n[bold][white]Project is initialized. Please configure [green]'adapters.yml'[/] and [green]'app.yml'[/] in the [blue]'{app_name}/settings'[/] directory before running [magenta]`python -m fastblocks dev`[/] or [magenta]`python -m fastblocks run`[/] from the [blue]'{app_name}'[/] directory.[/][/]",
1037 )
1038 console.print(
1039 "\n[dim]Use [white]`python -m fastblocks components`[/white] to see available adapters and actions.[/dim]",
1040 )
1041 raise SystemExit
1044@cli.command()
1045def version() -> None:
1046 try:
1047 __version__ = get_version("fastblocks")
1048 console.print(f"FastBlocks v{__version__}")
1049 except Exception:
1050 console.print("Unable to determine FastBlocks version")
1053@cli.command()
1054def mcp(
1055 port: Annotated[
1056 int,
1057 typer.Option("--port", "-p", help="Port for MCP server (default: auto)"),
1058 ] = 0,
1059 host: Annotated[
1060 str, typer.Option("--host", help="Host to bind MCP server to")
1061 ] = "localhost",
1062) -> None:
1063 """Start the FastBlocks MCP (Model Context Protocol) server.
1065 Enables IDE/AI assistant integration for FastBlocks development
1066 including template management, component creation, and adapter configuration.
1067 """
1068 import asyncio
1070 async def start_mcp_server() -> None:
1071 try:
1072 console.print("\n[bold blue]FastBlocks MCP Server[/bold blue]")
1073 console.print("[dim]Model Context Protocol for IDE Integration[/dim]\n")
1075 from .mcp import create_fastblocks_mcp_server
1077 console.print("[yellow]Initializing MCP server...[/yellow]")
1078 server = await create_fastblocks_mcp_server()
1080 console.print("[green]✓ MCP server initialized[/green]")
1082 if port:
1083 console.print(f"[blue]Starting server on {host}:{port}...[/blue]")
1084 else:
1085 console.print("[blue]Starting server...[/blue]")
1087 console.print("[green]✓ FastBlocks MCP server running[/green]")
1088 console.print("\n[dim]Press Ctrl+C to stop[/dim]\n")
1090 await server.start()
1092 except KeyboardInterrupt:
1093 console.print("\n[yellow]MCP server stopped by user[/yellow]")
1094 except ImportError as e:
1095 console.print(f"[red]MCP dependencies not available: {e}[/red]")
1096 console.print("[dim]Make sure Oneiric and mcp-common are installed[/dim]")
1097 except Exception as e:
1098 console.print(f"[red]Error starting MCP server: {e}[/red]")
1100 asyncio.run(start_mcp_server())