termforge 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.
termforge/profiles.py ADDED
@@ -0,0 +1,128 @@
1
+ """Agrega Git Bash y los distros de WSL detectados al menú de Windows Terminal.
2
+
3
+ WSL y PowerShell Core aparecen en el menú "+" de Windows Terminal como perfiles
4
+ dinámicos (generados en caliente, sin quedar guardados en `settings.json`), así
5
+ que `termforge backup`/`restore` no los cubre y desaparecen si Windows Terminal
6
+ cambia cómo los genera. Este módulo agrega una entrada explícita y persistente
7
+ para cada uno, solo si todavía no existe.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import uuid
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+
17
+ from termforge import jsonc
18
+ from termforge.backup import BackupInfo, create_backup
19
+ from termforge.env import Env, terminal_settings_path
20
+
21
+ _IGNORED_DISTROS = {"docker-desktop", "docker-desktop-data"}
22
+
23
+
24
+ class ProfilesError(Exception):
25
+ """Error esperado: sin settings.json o con un formato inesperado."""
26
+
27
+
28
+ @dataclass
29
+ class ProfileCandidate:
30
+ key: str
31
+ name: str
32
+ commandline: str
33
+ already_present: bool
34
+
35
+
36
+ def detect_git_bash(env: Env) -> Path | None:
37
+ """Ruta de `bash.exe` de Git for Windows, derivada de dónde está `git.exe`."""
38
+ git = env.which("git")
39
+ if not git:
40
+ return None
41
+ for ancestor in Path(git).parents:
42
+ candidate = ancestor / "bin" / "bash.exe"
43
+ if candidate.is_file():
44
+ return candidate
45
+ return None
46
+
47
+
48
+ def detect_wsl_distros(env: Env) -> list[str]:
49
+ """Nombres de distros de WSL instaladas (sin las internas de Docker Desktop)."""
50
+ if env.which("wsl") is None:
51
+ return []
52
+ try:
53
+ result = env.run(["wsl", "--list", "--quiet"], capture_output=True)
54
+ except OSError:
55
+ return []
56
+ if result.returncode != 0:
57
+ return []
58
+
59
+ raw = result.stdout
60
+ # `wsl.exe` siempre escribe su salida en UTF-16LE en Windows, sin BOM.
61
+ text = raw.decode("utf-16-le", errors="ignore") if isinstance(raw, bytes) else raw
62
+ names = [line.strip() for line in text.splitlines() if line.strip()]
63
+ return [n for n in names if n.lower() not in _IGNORED_DISTROS]
64
+
65
+
66
+ def _existing_commandlines(data: dict) -> list[str]:
67
+ profiles = data.get("profiles")
68
+ profile_list = profiles.get("list", []) if isinstance(profiles, dict) else []
69
+ return [
70
+ p.get("commandline", "").lower()
71
+ for p in profile_list
72
+ if isinstance(p, dict) and p.get("commandline")
73
+ ]
74
+
75
+
76
+ def build_plan(env: Env) -> tuple[dict, list[ProfileCandidate]]:
77
+ """Qué perfiles de Git Bash/WSL faltan en `settings.json` de Windows Terminal."""
78
+ path = terminal_settings_path(env)
79
+ if not path.exists():
80
+ raise ProfilesError("No se encontró settings.json de Windows Terminal.")
81
+ try:
82
+ data = jsonc.loads(path.read_text(encoding="utf-8-sig"))
83
+ except (OSError, ValueError) as exc:
84
+ raise ProfilesError(f"settings.json inválido: {exc}") from exc
85
+ if not isinstance(data, dict):
86
+ raise ProfilesError("settings.json no tiene el formato esperado.")
87
+
88
+ existing = _existing_commandlines(data)
89
+ candidates: list[ProfileCandidate] = []
90
+
91
+ bash = detect_git_bash(env)
92
+ if bash:
93
+ commandline = f'"{bash}" -i -l'
94
+ # No comparamos la ruta resuelta: el perfil existente puede usar
95
+ # `%PROGRAMFILES%` sin expandir y no calzaría como texto.
96
+ present = any("bash.exe" in cmd for cmd in existing)
97
+ candidates.append(ProfileCandidate("git-bash", "Git Bash", commandline, present))
98
+
99
+ for distro in detect_wsl_distros(env):
100
+ commandline = f"wsl.exe -d {distro}"
101
+ present = any(
102
+ cmd.startswith("wsl") and distro.lower() in cmd for cmd in existing
103
+ )
104
+ candidates.append(ProfileCandidate(f"wsl:{distro}", distro, commandline, present))
105
+
106
+ return data, candidates
107
+
108
+
109
+ def apply_plan(
110
+ env: Env, data: dict, pending: list[ProfileCandidate], backup_root: Path
111
+ ) -> BackupInfo:
112
+ """Agrega los perfiles pendientes a `settings.json`, respaldándolo antes."""
113
+ path = terminal_settings_path(env)
114
+ backup_info = create_backup({"windows-terminal": path}, backup_root, label="pre-profiles")
115
+
116
+ profiles = data.setdefault("profiles", {})
117
+ profile_list = profiles.setdefault("list", [])
118
+ for candidate in pending:
119
+ profile_list.append(
120
+ {
121
+ "guid": f"{{{uuid.uuid4()}}}",
122
+ "name": candidate.name,
123
+ "commandline": candidate.commandline,
124
+ }
125
+ )
126
+
127
+ path.write_text(json.dumps(data, indent=4, ensure_ascii=False), encoding="utf-8")
128
+ return backup_info
termforge/theme.py ADDED
@@ -0,0 +1,110 @@
1
+ """Selección y aplicación de temas de Oh My Posh, sin teclear el nombre exacto."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ from termforge.backup import BackupInfo, create_backup
9
+ from termforge.env import Env, powershell_profile_path
10
+
11
+ _THEME_SUFFIXES = (".omp.json", ".omp.yaml", ".omp.yml", ".omp.toml")
12
+ _INIT_LINE_PREFIX = "oh-my-posh init pwsh"
13
+ _MARKER = "# Agregado por termforge theme"
14
+
15
+
16
+ class ThemeError(Exception):
17
+ """Error esperado: sin temas, selección ambigua o inexistente."""
18
+
19
+
20
+ @dataclass
21
+ class Theme:
22
+ name: str
23
+ path: Path
24
+
25
+
26
+ def themes_path(env: Env) -> Path:
27
+ """Carpeta de temas de Oh My Posh (variable de entorno, o la ruta por defecto de winget)."""
28
+ override = env.environ.get("POSH_THEMES_PATH")
29
+ if override:
30
+ return Path(override)
31
+ return env.local_appdata / "Programs" / "oh-my-posh" / "themes"
32
+
33
+
34
+ def _theme_name(path: Path) -> str:
35
+ name = path.name
36
+ for suffix in _THEME_SUFFIXES:
37
+ if name.lower().endswith(suffix):
38
+ return name[: -len(suffix)]
39
+ return path.stem
40
+
41
+
42
+ def list_themes(env: Env) -> list[Theme]:
43
+ """Temas disponibles (los que ya trae instalado Oh My Posh), por nombre."""
44
+ root = themes_path(env)
45
+ if not root.is_dir():
46
+ return []
47
+ found = [
48
+ Theme(name=_theme_name(p), path=p)
49
+ for p in root.iterdir()
50
+ if p.is_file() and any(p.name.lower().endswith(s) for s in _THEME_SUFFIXES)
51
+ ]
52
+ return sorted(found, key=lambda t: t.name.lower())
53
+
54
+
55
+ def find_theme(themes: list[Theme], selector: str) -> Theme:
56
+ """Busca por número de la lista (1-based) o por nombre (exacto o prefijo único)."""
57
+ selector = selector.strip()
58
+ if selector.isdigit():
59
+ index = int(selector)
60
+ if 1 <= index <= len(themes):
61
+ return themes[index - 1]
62
+ raise ThemeError(f"No hay un tema con el número {index}.")
63
+
64
+ lowered = selector.lower()
65
+ exact = [t for t in themes if t.name.lower() == lowered]
66
+ if exact:
67
+ return exact[0]
68
+
69
+ matches = [t for t in themes if t.name.lower().startswith(lowered)]
70
+ if len(matches) == 1:
71
+ return matches[0]
72
+ if len(matches) > 1:
73
+ names = ", ".join(t.name for t in matches[:5])
74
+ raise ThemeError(f"'{selector}' es ambiguo, coincide con: {names}")
75
+ raise ThemeError(f"No se encontró el tema '{selector}'.")
76
+
77
+
78
+ def build_init_line(theme: Theme) -> str:
79
+ config = str(theme.path).replace("\\", "/")
80
+ return f'oh-my-posh init pwsh --config "{config}" | Invoke-Expression'
81
+
82
+
83
+ def apply_theme(env: Env, theme: Theme, backup_root: Path) -> BackupInfo | None:
84
+ """Escribe la línea de init con el tema elegido en el perfil de PowerShell.
85
+
86
+ Reemplaza una línea `oh-my-posh init pwsh ...` existente si la hay; si no,
87
+ la agrega al final. Respalda el perfil antes de tocarlo si ya existía.
88
+ """
89
+ path = powershell_profile_path(env)
90
+ content = path.read_text(encoding="utf-8-sig") if path.exists() else ""
91
+ lines = content.splitlines()
92
+
93
+ new_line = build_init_line(theme)
94
+ updated = [
95
+ new_line if line.strip().lower().startswith(_INIT_LINE_PREFIX) else line
96
+ for line in lines
97
+ ]
98
+ if new_line not in updated:
99
+ if updated and updated[-1].strip():
100
+ updated.append("")
101
+ updated.append(_MARKER)
102
+ updated.append(new_line)
103
+
104
+ backup_info = None
105
+ if path.exists():
106
+ backup_info = create_backup({"powershell-profile": path}, backup_root, label="pre-theme")
107
+
108
+ path.parent.mkdir(parents=True, exist_ok=True)
109
+ path.write_text("\n".join(updated) + "\n", encoding="utf-8")
110
+ return backup_info
@@ -0,0 +1,162 @@
1
+ Metadata-Version: 2.5
2
+ Name: termforge
3
+ Version: 0.1.0
4
+ Summary: CLI para diagnosticar, respaldar y configurar tu terminal de Windows (Windows Terminal, PowerShell 7, Oh My Posh).
5
+ Project-URL: Homepage, https://github.com/Rony10-az/Termforge
6
+ Project-URL: Repository, https://github.com/Rony10-az/Termforge
7
+ Project-URL: Issues, https://github.com/Rony10-az/Termforge/issues
8
+ Author-email: Rony <ronnjhost@gmail.com>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: cli,dotfiles,oh-my-posh,powershell,terminal,windows
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: Microsoft :: Windows
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: System :: Systems Administration
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: pyyaml>=6
25
+ Requires-Dist: rich>=13
26
+ Requires-Dist: typer>=0.12
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=8; extra == 'dev'
29
+ Requires-Dist: ruff>=0.6; extra == 'dev'
30
+ Description-Content-Type: text/markdown
31
+
32
+ <div align="center">
33
+
34
+ # ⚒️ termforge
35
+
36
+ **Diagnostica, respalda y configura tu terminal de Windows**
37
+ *(Windows Terminal + PowerShell 7 + Oh My Posh), sin romper lo que ya tienes.*
38
+
39
+ [![CI](https://github.com/Rony10-az/Termforge/actions/workflows/ci.yml/badge.svg)](https://github.com/Rony10-az/Termforge/actions/workflows/ci.yml)
40
+ [![PyPI](https://img.shields.io/pypi/v/termforge.svg)](https://pypi.org/project/termforge/)
41
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
42
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](pyproject.toml)
43
+ [![Platform: Windows](https://img.shields.io/badge/platform-windows-0078D6.svg)](#)
44
+
45
+ ![termforge doctor en acción](docs/doctor.png)
46
+
47
+ </div>
48
+
49
+ ## Instala tu terminal en un comando
50
+
51
+ ```powershell
52
+ pip install termforge
53
+ termforge init # instala PowerShell 7 + Oh My Posh con winget y configura tu perfil
54
+ ```
55
+
56
+ ¿No tienes Python a mano? Descarga `termforge.exe` desde la
57
+ [última versión publicada](https://github.com/Rony10-az/Termforge/releases/latest) y úsalo
58
+ directo, sin instalar nada más.
59
+
60
+ Para desarrollar sobre el código (requiere Python 3.10+):
61
+
62
+ ```powershell
63
+ git clone https://github.com/Rony10-az/Termforge.git
64
+ cd Termforge
65
+ python -m venv .venv
66
+ .venv\Scripts\Activate.ps1
67
+ pip install -e ".[dev]"
68
+ ```
69
+
70
+ Eso es todo: `termforge init` detecta qué falta, lo instala con `winget` y deja tu perfil de
71
+ PowerShell inicializando Oh My Posh, sin que tengas que buscar instaladores ni editar nada a
72
+ mano. Si ya tenías algo instalado, `termforge` lo respeta y solo completa lo que falta.
73
+
74
+ ¿Quieres repetir exactamente esta configuración en otra PC? Describe el resultado en un YAML
75
+ y aplícalo con un comando:
76
+
77
+ ```yaml
78
+ # termforge.yaml
79
+ init: true
80
+ theme: jandedobbeleer
81
+ profiles: [git-bash, wsl]
82
+ ```
83
+
84
+ ```powershell
85
+ termforge apply
86
+ ```
87
+
88
+ ## Por qué
89
+
90
+ Dejar una terminal bien configurada toma horas: instalar programas, elegir una Nerd Font,
91
+ editar `settings.json`, tocar el perfil de PowerShell. `termforge` convierte ese proceso en
92
+ comandos repetibles y **reversibles**.
93
+
94
+ ¿Quieres saber qué más instalar? [`docs/herramientas.md`](docs/herramientas.md) es una guía con
95
+ las herramientas populares para una buena terminal (zoxide, fzf, eza, lazygit, etc.) y soluciones
96
+ a problemas comunes.
97
+
98
+ ## Comandos (v0.1)
99
+
100
+ | Comando | Qué hace |
101
+ |---|---|
102
+ | `termforge doctor` | Revisa qué falta o está mal (PowerShell 7, Windows Terminal, Oh My Posh, Nerd Font, Git, WSL, perfil) y muestra cómo arreglarlo. `--json` para scripts. |
103
+ | `termforge init [--dry-run] [-y]` | Instala con `winget` lo que falte (PowerShell 7, Oh My Posh) y agrega la inicialización de Oh My Posh al perfil de PowerShell. Respalda el perfil antes de modificarlo. |
104
+ | `termforge theme [número\|nombre] [--list]` | Lista los temas de Oh My Posh ya instalados y aplica el que elijas (por número, sin buscar el nombre exacto). Respalda el perfil antes de modificarlo. |
105
+ | `termforge profiles [--dry-run] [-y]` | Agrega Git Bash y los distros de WSL detectados como perfiles fijos en el menú de Windows Terminal (WSL normalmente solo aparece ahí de forma dinámica, sin quedar guardado). Respalda `settings.json` antes de modificarlo. |
106
+ | `termforge apply [-f archivo.yaml] [--dry-run] [-y]` | Deja tu terminal como la describe un YAML (`init`, `theme`, `profiles` en una sola corrida). Ver [`termforge.example.yaml`](termforge.example.yaml). |
107
+ | `termforge backup [-l etiqueta]` | Guarda una copia de `settings.json` y del perfil de PowerShell. |
108
+ | `termforge backups` | Lista los respaldos. |
109
+ | `termforge restore [id] [--dry-run] [-y]` | Restaura un respaldo (el más reciente por defecto). Antes guarda el estado actual como `pre-restore`. |
110
+
111
+ `doctor` termina con código `1` si hay fallos, así que sirve también en scripts y CI.
112
+
113
+ ## Seguridad
114
+
115
+ - **Backup antes de modificar**: `restore` nunca sobrescribe sin guardar antes el estado actual.
116
+ - **`--dry-run`**: muestra qué haría sin tocar nada.
117
+ - Lee el `settings.json` de Windows Terminal aunque tenga comentarios y comas finales (JSONC).
118
+ - Los respaldos viven en `%LOCALAPPDATA%\termforge\backups` (se cambia con `TERMFORGE_HOME`).
119
+ - `profiles` sí **reescribe** `settings.json` (para agregar perfiles), así que pierde cualquier
120
+ comentario manual que tengas ahí; por eso respalda el archivo antes de tocarlo.
121
+
122
+ ## Desarrollo
123
+
124
+ ```powershell
125
+ pytest -q # tests
126
+ ruff check . # lint
127
+
128
+ pip install pyinstaller
129
+ pyinstaller termforge.spec # genera dist/termforge.exe
130
+ ```
131
+
132
+ Estructura:
133
+
134
+ ```
135
+ src/termforge/
136
+ ├── cli.py # comandos (Typer + Rich)
137
+ ├── doctor.py # diagnóstico
138
+ ├── init.py # instalación (winget) y configuración de Oh My Posh
139
+ ├── theme.py # listar y aplicar temas de Oh My Posh
140
+ ├── profiles.py # agregar Git Bash/WSL al menú de Windows Terminal
141
+ ├── config.py # configuración declarativa (termforge apply)
142
+ ├── backup.py # respaldo y restauración
143
+ ├── env.py # rutas y entorno (simulable en tests)
144
+ └── jsonc.py # lector de JSON con comentarios
145
+ tests/ # corren en Windows y Linux (GitHub Actions)
146
+ ```
147
+
148
+ Todo lo que depende del sistema pasa por `Env`, por eso los tests simulan una PC con Windows
149
+ sin tocar tu configuración real.
150
+
151
+ ## Roadmap
152
+
153
+ - [x] `doctor`, `backup`, `restore`
154
+ - [x] `init`: instalar dependencias con winget y configurar Oh My Posh
155
+ - [x] `theme`: elegir y aplicar un tema de Oh My Posh de una lista
156
+ - [x] `profiles`: agregar Git Bash y WSL al menú de Windows Terminal
157
+ - [x] Configuración declarativa (`termforge apply -f termforge.yaml`)
158
+ - [x] Publicar en PyPI y empaquetar `.exe` (ver [`.github/workflows/release.yml`](.github/workflows/release.yml))
159
+
160
+ ## Licencia
161
+
162
+ Distribuido bajo la licencia MIT. Ver [LICENSE](LICENSE) para el texto completo.
@@ -0,0 +1,16 @@
1
+ termforge/__init__.py,sha256=dOeAkx4g9c8CU8wdYSZYHQaI_1dZ1A8-gxsxyREFjE8,98
2
+ termforge/__main__.py,sha256=ffjErxvEXdnq711MSSNLgN_PgizuRBHFtsS51jmyr70,68
3
+ termforge/backup.py,sha256=1SjYR8BC22rkOSiLDV0spDffGRhrMRV-AWVx6pcbcEw,5515
4
+ termforge/cli.py,sha256=qHdDahPS1XNaUwEdXfHt-e86nbT16EXG1EPzJvDLVzY,14562
5
+ termforge/config.py,sha256=3CSazBlv22I93q-0rR4EPmVSQPFyXGBbR0yBjEnNmy4,5634
6
+ termforge/doctor.py,sha256=_tqplWSqZoR4XekC-Pg8rTxAqkUQVYoesTEyTA57Yyc,6417
7
+ termforge/env.py,sha256=W05OBfwS9gb3X9qN2e5ZLby-ZDMjeaAiUtB6Gd6IZcw,3007
8
+ termforge/init.py,sha256=7O7XmA9eebaHhcHO0T39LtzqD8zmVP_YkkXVsx8bJec,3884
9
+ termforge/jsonc.py,sha256=tNeRkCRFjV6zHnqU7v1eMuHm1Qn71RwT4ZakHLB1OGg,2230
10
+ termforge/profiles.py,sha256=X4FyCxOb_7AjoEBdOpbHaBwzuNeG-eDJQcjl-IWHeKA,4518
11
+ termforge/theme.py,sha256=MBpfaRt9JsqnKvQvshSgQAswtcaD0TeRWmJnbG2brsg,3662
12
+ termforge-0.1.0.dist-info/METADATA,sha256=6iqiNZ3F941i289oBxHnRB7gfu9y44uABX2utZYE9MM,7085
13
+ termforge-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
+ termforge-0.1.0.dist-info/entry_points.txt,sha256=sp_haVHzGEvCKQWf_gDTuwDwUNJeZYrJ1Ejj0LW23DI,48
15
+ termforge-0.1.0.dist-info/licenses/LICENSE,sha256=oUQYqc8Hse4DewtsamuPs2v4AeT8QlFKJx0xtP9H4KU,1061
16
+ termforge-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ termforge = termforge.cli:app
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rony
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.