janelkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. janelkit/__init__.py +107 -0
  2. janelkit/cli/__init__.py +0 -0
  3. janelkit/cli/build.py +84 -0
  4. janelkit/cli/dev.py +101 -0
  5. janelkit/cli/main.py +182 -0
  6. janelkit/cli/scaffolding.py +87 -0
  7. janelkit/compiler/__init__.py +251 -0
  8. janelkit/compiler/ast_nodes.py +204 -0
  9. janelkit/compiler/cascade.py +224 -0
  10. janelkit/compiler/expressions.py +206 -0
  11. janelkit/compiler/ir.py +286 -0
  12. janelkit/compiler/layout_choice.py +282 -0
  13. janelkit/compiler/lowering.py +1543 -0
  14. janelkit/compiler/qml_generator.py +97 -0
  15. janelkit/compiler/qml_interface.py +125 -0
  16. janelkit/compiler/script_analysis.py +302 -0
  17. janelkit/compiler/sfc_parser.py +80 -0
  18. janelkit/compiler/template_parser.py +480 -0
  19. janelkit/diagnostics.py +65 -0
  20. janelkit/events.py +106 -0
  21. janelkit/ext.py +32 -0
  22. janelkit/inspect.py +588 -0
  23. janelkit/lifecycle.py +199 -0
  24. janelkit/locale.py +46 -0
  25. janelkit/pages.py +441 -0
  26. janelkit/qml/DevError.qml +27 -0
  27. janelkit/qml/Janel/JkBlocker.qml +18 -0
  28. janelkit/qml/Janel/JkBox.qml +220 -0
  29. janelkit/qml/Janel/JkButton.qml +68 -0
  30. janelkit/qml/Janel/JkCheckBox.qml +64 -0
  31. janelkit/qml/Janel/JkColumn.qml +10 -0
  32. janelkit/qml/Janel/JkContext.qml +18 -0
  33. janelkit/qml/Janel/JkFlex.qml +44 -0
  34. janelkit/qml/Janel/JkFlexColumn.qml +9 -0
  35. janelkit/qml/Janel/JkFlexRow.qml +8 -0
  36. janelkit/qml/Janel/JkHover.qml +10 -0
  37. janelkit/qml/Janel/JkImage.qml +43 -0
  38. janelkit/qml/Janel/JkList.qml +199 -0
  39. janelkit/qml/Janel/JkOutline.qml +19 -0
  40. janelkit/qml/Janel/JkPages.qml +101 -0
  41. janelkit/qml/Janel/JkProgressBar.qml +68 -0
  42. janelkit/qml/Janel/JkQtBox.qml +51 -0
  43. janelkit/qml/Janel/JkRadioGroup.qml +92 -0
  44. janelkit/qml/Janel/JkRemote.qml +13 -0
  45. janelkit/qml/Janel/JkRole.qml +72 -0
  46. janelkit/qml/Janel/JkRow.qml +9 -0
  47. janelkit/qml/Janel/JkScroll.qml +57 -0
  48. janelkit/qml/Janel/JkScroller.qml +24 -0
  49. janelkit/qml/Janel/JkSelect.qml +121 -0
  50. janelkit/qml/Janel/JkShadow.qml +40 -0
  51. janelkit/qml/Janel/JkShortcut.qml +20 -0
  52. janelkit/qml/Janel/JkSides.qml +38 -0
  53. janelkit/qml/Janel/JkSlider.qml +64 -0
  54. janelkit/qml/Janel/JkSpacer.qml +25 -0
  55. janelkit/qml/Janel/JkSwitch.qml +65 -0
  56. janelkit/qml/Janel/JkTabs.qml +93 -0
  57. janelkit/qml/Janel/JkTap.qml +15 -0
  58. janelkit/qml/Janel/JkText.qml +68 -0
  59. janelkit/qml/Janel/JkTextArea.qml +68 -0
  60. janelkit/qml/Janel/JkTextBox.qml +14 -0
  61. janelkit/qml/Janel/JkTextField.qml +60 -0
  62. janelkit/qml/Janel/JkTextInherit.qml +17 -0
  63. janelkit/qml/Janel/JkTextLinks.qml +9 -0
  64. janelkit/qml/Janel/JkTextSelect.qml +54 -0
  65. janelkit/qml/Janel/JkTransition.qml +84 -0
  66. janelkit/qml/Janel/JkTranslate.qml +8 -0
  67. janelkit/qml/Janel/JkVideo.qml +66 -0
  68. janelkit/qml/Janel/JkWindow.qml +34 -0
  69. janelkit/qml/Janel/flex.js +844 -0
  70. janelkit/qml/Janel/jk.js +317 -0
  71. janelkit/qml/Janel/qmldir +31 -0
  72. janelkit/qt_backend/__init__.py +0 -0
  73. janelkit/qt_backend/application.py +536 -0
  74. janelkit/qt_backend/controls.py +302 -0
  75. janelkit/qt_backend/events.py +665 -0
  76. janelkit/qt_backend/polish.py +35 -0
  77. janelkit/reactivity/__init__.py +24 -0
  78. janelkit/reactivity/collections.py +294 -0
  79. janelkit/reactivity/computed.py +71 -0
  80. janelkit/reactivity/effects.py +334 -0
  81. janelkit/reactivity/history.py +248 -0
  82. janelkit/reactivity/props.py +91 -0
  83. janelkit/reactivity/state.py +74 -0
  84. janelkit/runtime/__init__.py +3 -0
  85. janelkit/runtime/component.py +1409 -0
  86. janelkit/runtime/list_model.py +183 -0
  87. janelkit/runtime/qt_bridge.py +119 -0
  88. janelkit/storage.py +175 -0
  89. janelkit/styling/__init__.py +0 -0
  90. janelkit/styling/compiler.py +799 -0
  91. janelkit/styling/parser.py +166 -0
  92. janelkit/styling/theme.py +160 -0
  93. janelkit/tasks.py +180 -0
  94. janelkit/templates/starter/README.md.tmpl +25 -0
  95. janelkit/templates/starter/assets/dot-gitkeep.tmpl +0 -0
  96. janelkit/templates/starter/dot-gitignore.tmpl +6 -0
  97. janelkit/templates/starter/main.py.tmpl +6 -0
  98. janelkit/templates/starter/pyproject.toml.tmpl +5 -0
  99. janelkit/templates/starter/src/App.janel.tmpl +39 -0
  100. janelkit/templates/starter/src/components/Counter.janel.tmpl +28 -0
  101. janelkit/templates/starter/src/pages/dot-gitkeep.tmpl +0 -0
  102. janelkit/templates/starter/src/services/users.py.tmpl +6 -0
  103. janelkit/testing.py +115 -0
  104. janelkit/timers.py +133 -0
  105. janelkit/video.py +240 -0
  106. janelkit/windows.py +120 -0
  107. janelkit-0.1.0.dist-info/METADATA +179 -0
  108. janelkit-0.1.0.dist-info/RECORD +112 -0
  109. janelkit-0.1.0.dist-info/WHEEL +5 -0
  110. janelkit-0.1.0.dist-info/entry_points.txt +2 -0
  111. janelkit-0.1.0.dist-info/licenses/LICENSE +21 -0
  112. janelkit-0.1.0.dist-info/top_level.txt +1 -0
janelkit/__init__.py ADDED
@@ -0,0 +1,107 @@
1
+ """JanelKit: componentes de archivo único para escritorio con Python y Qt Quick."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ from typing import TYPE_CHECKING
6
+
7
+ from .reactivity import (
8
+ Computed,
9
+ Effect,
10
+ Event,
11
+ History,
12
+ Prop,
13
+ PropError,
14
+ State,
15
+ batch,
16
+ computed,
17
+ effect,
18
+ event,
19
+ prop,
20
+ state,
21
+ untracked,
22
+ )
23
+ from .locale import locale
24
+ from .events import DragEvent, FocusEvent, KeyEvent, PointerEvent, ResizeEvent, WheelEvent
25
+ from .lifecycle import Ref, before_leave, inject, on_destroy, on_mount, provide, ref
26
+ from .pages import PageStack, Sections, navigation, pages, sections
27
+ from .storage import Persisted, persisted
28
+ from .styling.theme import theme
29
+ from .tasks import Task, background, spawn, task
30
+ from .timers import Timer, interval, timeout
31
+ from .windows import open_window
32
+
33
+ __version__ = "0.1.0"
34
+
35
+ # API pública: lo que se importa desde `janelkit` es estable dentro de una
36
+ # versión menor (ver docs/api.md). Cualquier otro módulo es interno.
37
+ __all__ = [
38
+ "Computed",
39
+ "Effect",
40
+ "DragEvent",
41
+ "Event",
42
+ "History",
43
+ "FocusEvent",
44
+ "Frames",
45
+ "KeyEvent",
46
+ "Prop",
47
+ "PageStack",
48
+ "Persisted",
49
+ "PointerEvent",
50
+ "PropError",
51
+ "Ref",
52
+ "Sections",
53
+ "ResizeEvent",
54
+ "State",
55
+ "Task",
56
+ "Timer",
57
+ "WheelEvent",
58
+ "__version__",
59
+ "background",
60
+ "batch",
61
+ "before_leave",
62
+ "computed",
63
+ "effect",
64
+ "event",
65
+ "inject",
66
+ "interval",
67
+ "locale",
68
+ "navigation",
69
+ "on_destroy",
70
+ "on_mount",
71
+ "pages",
72
+ "persisted",
73
+ "open_window",
74
+ "prop",
75
+ "provide",
76
+ "ref",
77
+ "run",
78
+ "sections",
79
+ "spawn",
80
+ "state",
81
+ "task",
82
+ "theme",
83
+ "timeout",
84
+ "untracked",
85
+ ]
86
+
87
+ if TYPE_CHECKING:
88
+ from .qt_backend.application import run
89
+ from .video import Frames
90
+ else:
91
+
92
+ def run(entry: str | os.PathLike[str], argv: list[str] | None = None) -> int:
93
+ # Importación diferida: `from janelkit import state` no necesita cargar Qt.
94
+ from .qt_backend.application import run as _run
95
+
96
+ return _run(entry, argv)
97
+
98
+ run.__doc__ = "Compila el componente raíz `entry`, abre la ventana y ejecuta el ciclo de eventos de Qt."
99
+
100
+
101
+ def __getattr__(name: str):
102
+ # Importación diferida: Frames carga QtMultimedia, que solo necesitan las apps con vídeo.
103
+ if name == "Frames":
104
+ from .video import Frames
105
+
106
+ return Frames
107
+ raise AttributeError(f"module 'janelkit' has no attribute {name!r}")
File without changes
janelkit/cli/build.py ADDED
@@ -0,0 +1,84 @@
1
+ """`janel build`: compila todos los componentes del proyecto y guarda el QML generado.
2
+
3
+ Sirve para validar el proyecto completo (también componentes que todavía no se
4
+ usan) y para inspeccionar el QML. **No genera un ejecutable**: empaquetar
5
+ aplicaciones para distribuirlas es un paso distinto, previsto para más adelante.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+
12
+ from ..compiler import CompileSession, CompiledComponent
13
+ from ..diagnostics import Diagnostic, JanelError
14
+
15
+
16
+ @dataclass
17
+ class BuildResult:
18
+ out_dir: Path
19
+ written: list[Path] = field(default_factory=list)
20
+ errors: list[Diagnostic] = field(default_factory=list)
21
+ warnings: list[Diagnostic] = field(default_factory=list)
22
+
23
+ @property
24
+ def ok(self) -> bool:
25
+ return not self.errors
26
+
27
+
28
+ def find_source_dir(target: Path) -> Path:
29
+ target = target.resolve()
30
+ if target.is_file():
31
+ return target.parent
32
+ src = target / "src"
33
+ return src if (src / "App.janel").is_file() else target
34
+
35
+
36
+ def build_project(target: Path, out_dir: Path | None = None) -> BuildResult:
37
+ src = find_source_dir(target)
38
+ project = src.parent if src.name == "src" else src
39
+ out = (out_dir or project / "build" / "qml").resolve()
40
+ result = BuildResult(out)
41
+
42
+ entry = src / "App.janel"
43
+ files = sorted(src.rglob("*.janel"))
44
+ if not files:
45
+ result.errors.append(Diagnostic(f"no hay archivos .janel en {src}"))
46
+ return result
47
+
48
+ session = CompileSession([src])
49
+ compiled: dict[str, CompiledComponent] = {}
50
+
51
+ def attempt(path: Path, as_window: bool) -> None:
52
+ try:
53
+ session.compile(path, as_window=as_window)
54
+ except JanelError as exc:
55
+ result.errors.extend(exc.diagnostics)
56
+
57
+ if entry.is_file():
58
+ attempt(entry, as_window=True)
59
+ for path in files:
60
+ if str(path.resolve()) not in session.registry and path != entry:
61
+ # Sin usar en ninguna plantilla: un componente, o una ventana para open_window.
62
+ attempt(path, as_window=_is_window(session, path))
63
+ compiled.update(session.registry)
64
+ # Un archivo con errores puede intentarse dos veces (como hijo y por sí mismo).
65
+ result.errors = list({(d.message, d.location): d for d in result.errors}.values())
66
+
67
+ for key, comp in compiled.items():
68
+ result.warnings.extend(comp.warnings)
69
+ rel = Path(key).relative_to(src) if Path(key).is_relative_to(src) else Path(Path(key).name)
70
+ target_file = out / rel.with_suffix(".qml")
71
+ target_file.parent.mkdir(parents=True, exist_ok=True)
72
+ target_file.write_text(comp.qml, encoding="utf-8")
73
+ result.written.append(target_file)
74
+ return result
75
+
76
+
77
+ def _is_window(session: CompileSession, path: Path) -> bool:
78
+ """El archivo tiene <Window> como raíz (se abrirá con open_window)."""
79
+ try:
80
+ sfc, _ = session.load(path)
81
+ except JanelError:
82
+ return False
83
+ roots = sfc.root_elements
84
+ return bool(roots) and getattr(roots[0], "tag", None) == "Window"
janelkit/cli/dev.py ADDED
@@ -0,0 +1,101 @@
1
+ """`janel dev`: ejecuta la aplicación y la recarga al guardar.
2
+
3
+ - Cambios en `.janel`: la propia aplicación (con JANELKIT_DEV=1) recompila y
4
+ vuelve a montar la vista sin reiniciar el proceso.
5
+ - Cambios en `.py` o en `.qml` propios del proyecto: este supervisor reinicia
6
+ `python main.py`. Los módulos Python no se pueden recargar de forma fiable, y
7
+ Qt (antes de 6.12) no vuelve a leer en el mismo proceso un `.qml` ya cargado.
8
+
9
+ El arranque sigue siendo `main.py`: lo que funciona con `janel dev` funciona
10
+ igual con `python main.py`.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import subprocess
16
+ import sys
17
+ import time
18
+ from pathlib import Path
19
+
20
+ from ..qt_backend.application import DEV_ENV
21
+
22
+ POLL_SECONDS = 0.4
23
+ IGNORED_DIRS = {".venv", "venv", "env", ".git", "__pycache__", "build", "dist", "node_modules", ".pytest_cache"}
24
+
25
+
26
+ class DevError(Exception):
27
+ pass
28
+
29
+
30
+ def find_entry(target: Path) -> Path:
31
+ """`main.py` del proyecto a partir de una carpeta o del propio archivo."""
32
+ target = target.resolve()
33
+ main = target / "main.py" if target.is_dir() else target
34
+ if not main.is_file():
35
+ raise DevError(f"no se encontró {main}; ejecuta janel dev dentro de un proyecto creado con janel new")
36
+ return main
37
+
38
+
39
+ RESTART_SUFFIXES = (".py", ".qml")
40
+
41
+
42
+ def restart_files(project: Path) -> dict[str, float]:
43
+ """Archivos cuyo cambio exige reiniciar el proceso: `.py` y `.qml` del proyecto."""
44
+ found: dict[str, float] = {}
45
+ for root, dirs, files in os.walk(project):
46
+ dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
47
+ for name in files:
48
+ if name.endswith(RESTART_SUFFIXES):
49
+ path = os.path.join(root, name)
50
+ try:
51
+ found[path] = os.stat(path).st_mtime
52
+ except OSError:
53
+ pass
54
+ return found
55
+
56
+
57
+ def _changed(before: dict[str, float], after: dict[str, float]) -> list[str]:
58
+ return sorted({p for p in before.keys() | after.keys() if before.get(p) != after.get(p)})
59
+
60
+
61
+ def _stop(proc: subprocess.Popen) -> None:
62
+ if proc.poll() is None:
63
+ proc.terminate()
64
+ try:
65
+ proc.wait(timeout=5)
66
+ except subprocess.TimeoutExpired:
67
+ proc.kill()
68
+ proc.wait()
69
+
70
+
71
+ def run_dev(target: Path, python: str = sys.executable) -> int:
72
+ main = find_entry(target)
73
+ project = main.parent
74
+ env = {**os.environ, DEV_ENV: "1", "PYTHONUNBUFFERED": "1"}
75
+ print(f"[janel dev] {main.relative_to(project.parent)} — Ctrl+C para salir", flush=True)
76
+ while True:
77
+ proc = subprocess.Popen([python, str(main)], cwd=project, env=env)
78
+ snapshot = restart_files(project)
79
+ restart = False
80
+ try:
81
+ while True:
82
+ code = proc.poll()
83
+ if code is not None:
84
+ if code == 0:
85
+ return 0
86
+ print(f"[janel dev] la aplicación terminó con código {code}; esperando cambios en .py o .qml…", flush=True)
87
+ while not (changed := _changed(snapshot, restart_files(project))):
88
+ time.sleep(POLL_SECONDS)
89
+ restart = True
90
+ else:
91
+ time.sleep(POLL_SECONDS)
92
+ changed = _changed(snapshot, restart_files(project))
93
+ restart = bool(changed)
94
+ if restart:
95
+ names = ", ".join(Path(p).name for p in changed[:3]) + ("…" if len(changed) > 3 else "")
96
+ print(f"[janel dev] cambió {names}: reiniciando", flush=True)
97
+ _stop(proc)
98
+ break
99
+ except KeyboardInterrupt:
100
+ _stop(proc)
101
+ return 130
janelkit/cli/main.py ADDED
@@ -0,0 +1,182 @@
1
+ """Punto de entrada del comando `janel`."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import sys
6
+ from importlib import metadata
7
+ from pathlib import Path
8
+
9
+ from .. import __version__
10
+ from ..diagnostics import JanelError
11
+
12
+
13
+ def _cmd_new(args: argparse.Namespace) -> int:
14
+ from .scaffolding import ScaffoldError, create_project
15
+
16
+ try:
17
+ result = create_project(args.name, Path(args.path) if args.path else None)
18
+ except ScaffoldError as exc:
19
+ print(f"error: {exc}", file=sys.stderr)
20
+ return 1
21
+ try:
22
+ shown = result.root.relative_to(Path.cwd())
23
+ except ValueError:
24
+ shown = result.root
25
+ print(f"Proyecto creado en {shown}\n")
26
+ for f in result.files:
27
+ print(f" {f.relative_to(result.root).as_posix()}")
28
+ print("\nSiguientes pasos:")
29
+ print(f" cd {shown}")
30
+ print(" python main.py")
31
+ print("\nUsa el mismo entorno de Python en el que instalaste JanelKit.")
32
+ return 0
33
+
34
+
35
+ def _cmd_parse(args: argparse.Namespace) -> int:
36
+ from ..compiler import parse_file
37
+ from ..compiler.ast_nodes import dump
38
+
39
+ try:
40
+ print(dump(parse_file(args.file)))
41
+ except JanelError as exc:
42
+ print(exc, file=sys.stderr)
43
+ return 1
44
+ return 0
45
+
46
+
47
+ def _cmd_compile(args: argparse.Namespace) -> int:
48
+ from ..compiler import compile_file
49
+
50
+ try:
51
+ compiled = compile_file(args.file)
52
+ except JanelError as exc:
53
+ print(exc, file=sys.stderr)
54
+ return 1
55
+ for warning in compiled.all_warnings:
56
+ print(warning.format(), file=sys.stderr)
57
+ if args.output:
58
+ Path(args.output).write_text(compiled.qml, encoding="utf-8")
59
+ else:
60
+ sys.stdout.write(compiled.qml)
61
+ return 0
62
+
63
+
64
+ def _cmd_dev(args: argparse.Namespace) -> int:
65
+ from .dev import DevError, run_dev
66
+
67
+ try:
68
+ return run_dev(Path(args.path))
69
+ except DevError as exc:
70
+ print(f"error: {exc}", file=sys.stderr)
71
+ return 1
72
+
73
+
74
+ def _cmd_build(args: argparse.Namespace) -> int:
75
+ from .build import build_project
76
+
77
+ result = build_project(Path(args.path), Path(args.output) if args.output else None)
78
+ for diag in result.warnings:
79
+ print(diag.format(), file=sys.stderr)
80
+ for diag in result.errors:
81
+ print(diag.format(), file=sys.stderr)
82
+ if not result.ok:
83
+ n = len(result.errors)
84
+ print(f"\njanel build: {n} error{'es' if n != 1 else ''}", file=sys.stderr)
85
+ return 1
86
+ try:
87
+ shown = result.out_dir.relative_to(Path.cwd())
88
+ except ValueError:
89
+ shown = result.out_dir
90
+ print(f"{len(result.written)} componente(s) compilado(s) sin errores; QML generado en {shown}")
91
+ print("Nota: janel build valida el proyecto; no crea un ejecutable.")
92
+ return 0
93
+
94
+
95
+ def build_parser() -> argparse.ArgumentParser:
96
+ parser = argparse.ArgumentParser(
97
+ prog="janel",
98
+ description="Herramientas de JanelKit: componentes .janel para escritorio con Python y Qt Quick.",
99
+ )
100
+ parser.add_argument("--version", action="version", version=f"JanelKit {__version__}")
101
+ sub = parser.add_subparsers(dest="command", metavar="<comando>")
102
+
103
+ p_new = sub.add_parser("new", help="crea un proyecto nuevo con main.py y src/App.janel")
104
+ p_new.add_argument("name", help="nombre del proyecto (también el nombre de la carpeta)")
105
+ p_new.add_argument("--path", help="carpeta donde crear el proyecto (por defecto, la actual)")
106
+ p_new.set_defaults(func=_cmd_new)
107
+
108
+ p_parse = sub.add_parser("parse", help="muestra el AST de un archivo .janel o sus errores")
109
+ p_parse.add_argument("file")
110
+ p_parse.set_defaults(func=_cmd_parse)
111
+
112
+ p_compile = sub.add_parser("compile", help="muestra el QML generado para un archivo .janel")
113
+ p_compile.add_argument("file")
114
+ p_compile.add_argument("-o", "--output", help="escribe el QML en este archivo")
115
+ p_compile.set_defaults(func=_cmd_compile)
116
+
117
+ p_dev = sub.add_parser(
118
+ "dev",
119
+ help="ejecuta main.py y recarga la vista al guardar (.janel) o reinicia (.py)",
120
+ description="Ejecuta la aplicación en modo desarrollo. Al guardar un .janel la vista se recompila "
121
+ "y se vuelve a montar (el estado se reinicia); al guardar un .py se reinicia el proceso.",
122
+ )
123
+ p_dev.add_argument("path", nargs="?", default=".", help="carpeta del proyecto o ruta de main.py (por defecto, la actual)")
124
+ p_dev.set_defaults(func=_cmd_dev)
125
+
126
+ p_build = sub.add_parser(
127
+ "build",
128
+ help="compila todos los .janel del proyecto y guarda el QML generado",
129
+ description="Valida todos los componentes del proyecto (incluidos los que aún no se usan) y escribe "
130
+ "el QML generado en build/qml. No genera un ejecutable.",
131
+ )
132
+ p_build.add_argument("path", nargs="?", default=".", help="carpeta del proyecto (por defecto, la actual)")
133
+ p_build.add_argument("-o", "--output", help="carpeta de salida (por defecto, build/qml)")
134
+ p_build.set_defaults(func=_cmd_build)
135
+
136
+ _add_plugin_commands(sub)
137
+ return parser
138
+
139
+
140
+ COMMANDS_GROUP = "janelkit.commands"
141
+
142
+
143
+ def _plugin_commands() -> list[metadata.EntryPoint]:
144
+ return list(metadata.entry_points(group=COMMANDS_GROUP))
145
+
146
+
147
+ def _add_plugin_commands(sub: argparse._SubParsersAction) -> None:
148
+ """Subcomandos de otros paquetes: entry points `nombre = "paquete.modulo:configurar"`.
149
+
150
+ `configurar(parser)` recibe el `ArgumentParser` del subcomando, le añade sus
151
+ argumentos y fija `parser.set_defaults(func=ejecutar)`; `ejecutar(args)` devuelve
152
+ el código de salida. La primera línea de la documentación de `configurar` es la ayuda.
153
+ """
154
+ for entry in _plugin_commands():
155
+ if entry.name in sub.choices:
156
+ print(f"aviso: {entry.value} no puede redefinir el comando {entry.name!r}", file=sys.stderr)
157
+ continue
158
+ try:
159
+ configure = entry.load()
160
+ summary = (configure.__doc__ or "").strip().splitlines()
161
+ configure(sub.add_parser(entry.name, help=summary[0] if summary else None))
162
+ except Exception as exc: # noqa: BLE001 - un plugin roto no debe impedir usar `janel`
163
+ sub.choices.pop(entry.name, None)
164
+ sub._choices_actions = [a for a in sub._choices_actions if a.dest != entry.name]
165
+ print(f"aviso: no se pudo cargar el comando {entry.name!r} ({entry.value}): {exc}", file=sys.stderr)
166
+
167
+
168
+ def main(argv: list[str] | None = None) -> int:
169
+ for stream in (sys.stdout, sys.stderr):
170
+ # Consolas de Windows con codificación heredada: no fallar por acentos.
171
+ if hasattr(stream, "reconfigure"):
172
+ stream.reconfigure(errors="replace")
173
+ parser = build_parser()
174
+ args = parser.parse_args(argv)
175
+ if not getattr(args, "func", None):
176
+ parser.print_help()
177
+ return 2
178
+ return args.func(args)
179
+
180
+
181
+ if __name__ == "__main__":
182
+ raise SystemExit(main())
@@ -0,0 +1,87 @@
1
+ """`janel new`: genera un proyecto a partir de las plantillas instaladas con el paquete.
2
+
3
+ Convenciones de las plantillas (en `janelkit/templates/<nombre>/`):
4
+ - Todo archivo termina en `.tmpl`; el sufijo se elimina al copiarlo. Así ningún
5
+ `.py` de plantilla se importa ni se compila al instalar el wheel.
6
+ - Un nombre que empieza por `dot-` se copia con punto inicial (`dot-gitignore.tmpl` -> `.gitignore`).
7
+ - `{{project_name}}` y `{{janelkit_version}}` se sustituyen en el contenido.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from dataclasses import dataclass
13
+ from importlib import resources
14
+ from pathlib import Path
15
+ from typing import TYPE_CHECKING
16
+
17
+ if TYPE_CHECKING: # importlib.resources.abc no existe en Python 3.10
18
+ from importlib.resources.abc import Traversable
19
+
20
+ from .. import __version__
21
+
22
+ _NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
23
+
24
+
25
+ class ScaffoldError(Exception):
26
+ pass
27
+
28
+
29
+ @dataclass
30
+ class ScaffoldResult:
31
+ root: Path
32
+ files: list[Path]
33
+
34
+
35
+ def _template_root(template: str) -> Traversable:
36
+ root = resources.files("janelkit") / "templates" / template
37
+ if not root.is_dir():
38
+ raise ScaffoldError(f"no existe la plantilla '{template}'")
39
+ return root
40
+
41
+
42
+ def _output_name(name: str) -> str | None:
43
+ if not name.endswith(".tmpl"):
44
+ return None # p. ej. __pycache__ u otros restos: se ignoran
45
+ name = name[: -len(".tmpl")]
46
+ if name.startswith("dot-"):
47
+ name = "." + name[len("dot-"):]
48
+ return name
49
+
50
+
51
+ def _walk(node: Traversable, rel: Path) -> list[tuple[Path, Traversable]]:
52
+ out: list[tuple[Path, Traversable]] = []
53
+ for child in sorted(node.iterdir(), key=lambda c: c.name):
54
+ if child.is_dir():
55
+ if child.name != "__pycache__":
56
+ out.extend(_walk(child, rel / child.name))
57
+ else:
58
+ name = _output_name(child.name)
59
+ if name is not None:
60
+ out.append((rel / name, child))
61
+ return out
62
+
63
+
64
+ def create_project(name: str, parent: Path | None = None, template: str = "starter") -> ScaffoldResult:
65
+ if not _NAME_RE.match(name):
66
+ raise ScaffoldError(
67
+ f"nombre de proyecto no válido: {name!r} (usa letras, números, '-', '_' o '.', empezando por letra o número)"
68
+ )
69
+ target = (parent or Path.cwd()) / name
70
+ if target.exists():
71
+ if not target.is_dir():
72
+ raise ScaffoldError(f"ya existe un archivo llamado {target}")
73
+ if any(target.iterdir()):
74
+ raise ScaffoldError(f"el directorio {target} ya existe y no está vacío; no se sobrescribe nada")
75
+
76
+ entries = _walk(_template_root(template), Path())
77
+ values = {"project_name": name, "janelkit_version": __version__}
78
+ created: list[Path] = []
79
+ for rel, source in entries:
80
+ content = source.read_text(encoding="utf-8")
81
+ for key, value in values.items():
82
+ content = content.replace("{{" + key + "}}", value)
83
+ dest = target / rel
84
+ dest.parent.mkdir(parents=True, exist_ok=True)
85
+ dest.write_text(content, encoding="utf-8", newline="\n")
86
+ created.append(dest)
87
+ return ScaffoldResult(target, created)