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/__init__.py +3 -0
- termforge/__main__.py +4 -0
- termforge/backup.py +179 -0
- termforge/cli.py +416 -0
- termforge/config.py +148 -0
- termforge/doctor.py +197 -0
- termforge/env.py +97 -0
- termforge/init.py +132 -0
- termforge/jsonc.py +89 -0
- termforge/profiles.py +128 -0
- termforge/theme.py +110 -0
- termforge-0.1.0.dist-info/METADATA +162 -0
- termforge-0.1.0.dist-info/RECORD +16 -0
- termforge-0.1.0.dist-info/WHEEL +4 -0
- termforge-0.1.0.dist-info/entry_points.txt +2 -0
- termforge-0.1.0.dist-info/licenses/LICENSE +21 -0
termforge/config.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Configuración declarativa: describe el estado deseado de tu terminal en un YAML.
|
|
2
|
+
|
|
3
|
+
En vez de correr `init`, `theme` y `profiles` por separado, un archivo
|
|
4
|
+
`termforge.yaml` describe el resultado que quieres y `termforge apply` lo deja
|
|
5
|
+
así. Es complementario, igual que el resto de `termforge`: solo instala o
|
|
6
|
+
agrega lo que falte, nunca borra ni degrada algo que ya tenías.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import yaml
|
|
15
|
+
|
|
16
|
+
from termforge.env import Env
|
|
17
|
+
from termforge.init import InitPlan, InitReport
|
|
18
|
+
from termforge.init import apply_plan as apply_init_plan
|
|
19
|
+
from termforge.init import build_plan as build_init_plan
|
|
20
|
+
from termforge.profiles import ProfileCandidate, ProfilesError
|
|
21
|
+
from termforge.profiles import apply_plan as apply_profiles_plan
|
|
22
|
+
from termforge.profiles import build_plan as build_profiles_plan
|
|
23
|
+
from termforge.theme import Theme, ThemeError, apply_theme, find_theme, list_themes
|
|
24
|
+
|
|
25
|
+
_KNOWN_KEYS = {"init", "theme", "profiles"}
|
|
26
|
+
_KNOWN_PROFILE_KINDS = {"git-bash", "wsl"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ConfigError(Exception):
|
|
30
|
+
"""Error esperado: YAML inválido, con campos desconocidos, o nada que aplicar."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class TermforgeConfig:
|
|
35
|
+
init: bool = False
|
|
36
|
+
theme: str | None = None
|
|
37
|
+
profiles: list[str] = field(default_factory=list)
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def is_empty(self) -> bool:
|
|
41
|
+
return not self.init and self.theme is None and not self.profiles
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def load_config(path: Path) -> TermforgeConfig:
|
|
45
|
+
"""Lee y valida un archivo de configuración declarativa."""
|
|
46
|
+
if not path.is_file():
|
|
47
|
+
raise ConfigError(f"No se encontró el archivo de configuración: {path}")
|
|
48
|
+
try:
|
|
49
|
+
raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
|
50
|
+
except yaml.YAMLError as exc:
|
|
51
|
+
raise ConfigError(f"YAML inválido en {path}: {exc}") from exc
|
|
52
|
+
if not isinstance(raw, dict):
|
|
53
|
+
raise ConfigError(f"{path} debe describir un mapa (init, theme, profiles).")
|
|
54
|
+
|
|
55
|
+
unknown = set(raw) - _KNOWN_KEYS
|
|
56
|
+
if unknown:
|
|
57
|
+
raise ConfigError(f"Clave(s) desconocida(s) en {path}: {', '.join(sorted(unknown))}")
|
|
58
|
+
|
|
59
|
+
init_flag = raw.get("init", False)
|
|
60
|
+
if not isinstance(init_flag, bool):
|
|
61
|
+
raise ConfigError("'init' debe ser true o false.")
|
|
62
|
+
|
|
63
|
+
theme = raw.get("theme")
|
|
64
|
+
if theme is not None and not isinstance(theme, str):
|
|
65
|
+
raise ConfigError("'theme' debe ser el nombre de un tema (texto).")
|
|
66
|
+
|
|
67
|
+
profiles = raw.get("profiles", [])
|
|
68
|
+
if not isinstance(profiles, list) or not all(isinstance(p, str) for p in profiles):
|
|
69
|
+
raise ConfigError("'profiles' debe ser una lista de nombres (git-bash, wsl).")
|
|
70
|
+
unknown_profiles = set(profiles) - _KNOWN_PROFILE_KINDS
|
|
71
|
+
if unknown_profiles:
|
|
72
|
+
valid = ", ".join(sorted(_KNOWN_PROFILE_KINDS))
|
|
73
|
+
raise ConfigError(
|
|
74
|
+
f"profiles desconocido(s): {', '.join(sorted(unknown_profiles))} (válidos: {valid})"
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
return TermforgeConfig(init=init_flag, theme=theme, profiles=profiles)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class ConfigReport:
|
|
82
|
+
init_plan: InitPlan | None = None
|
|
83
|
+
init_report: InitReport | None = None
|
|
84
|
+
theme_applied: Theme | None = None
|
|
85
|
+
theme_pending_install: bool = False
|
|
86
|
+
profiles_status: list[ProfileCandidate] = field(default_factory=list)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def run_config(
|
|
90
|
+
env: Env, config: TermforgeConfig, backup_root: Path, dry_run: bool = False
|
|
91
|
+
) -> ConfigReport:
|
|
92
|
+
"""Aplica (o, en `dry_run`, solo describe) el estado deseado en `config`.
|
|
93
|
+
|
|
94
|
+
`init` se ejecuta antes de resolver `theme` a propósito: en una PC nueva,
|
|
95
|
+
así `init` ya instaló Oh My Posh (y sus temas) para cuando se busca el
|
|
96
|
+
tema pedido. En `--dry-run` nada se instala de verdad, así que si el tema
|
|
97
|
+
todavía no se puede resolver pero `init` lo dejaría listo, se avisa en vez
|
|
98
|
+
de fallar.
|
|
99
|
+
"""
|
|
100
|
+
init_plan = build_init_plan(env) if config.init else None
|
|
101
|
+
if init_plan and not dry_run and init_plan.has_pending_work:
|
|
102
|
+
init_report = apply_init_plan(env, init_plan, backup_root)
|
|
103
|
+
else:
|
|
104
|
+
init_report = None
|
|
105
|
+
|
|
106
|
+
theme_applied: Theme | None = None
|
|
107
|
+
theme_pending_install = False
|
|
108
|
+
if config.theme:
|
|
109
|
+
themes = list_themes(env)
|
|
110
|
+
if themes:
|
|
111
|
+
try:
|
|
112
|
+
theme_applied = find_theme(themes, config.theme)
|
|
113
|
+
except ThemeError as exc:
|
|
114
|
+
raise ConfigError(str(exc)) from exc
|
|
115
|
+
if not dry_run:
|
|
116
|
+
apply_theme(env, theme_applied, backup_root)
|
|
117
|
+
elif dry_run and config.init:
|
|
118
|
+
theme_pending_install = True
|
|
119
|
+
else:
|
|
120
|
+
raise ConfigError(
|
|
121
|
+
f"No se encontraron temas de Oh My Posh instalados para aplicar '{config.theme}'. "
|
|
122
|
+
"Agrega `init: true` a la configuración, o corre `termforge init` primero."
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
profiles_status: list[ProfileCandidate] = []
|
|
126
|
+
if config.profiles:
|
|
127
|
+
try:
|
|
128
|
+
data, all_candidates = build_profiles_plan(env)
|
|
129
|
+
except ProfilesError as exc:
|
|
130
|
+
raise ConfigError(str(exc)) from exc
|
|
131
|
+
wanted = set(config.profiles)
|
|
132
|
+
profiles_status = [
|
|
133
|
+
c
|
|
134
|
+
for c in all_candidates
|
|
135
|
+
if (c.key == "git-bash" and "git-bash" in wanted)
|
|
136
|
+
or (c.key.startswith("wsl:") and "wsl" in wanted)
|
|
137
|
+
]
|
|
138
|
+
pending = [c for c in profiles_status if not c.already_present]
|
|
139
|
+
if not dry_run and pending:
|
|
140
|
+
apply_profiles_plan(env, data, pending, backup_root)
|
|
141
|
+
|
|
142
|
+
return ConfigReport(
|
|
143
|
+
init_plan=init_plan,
|
|
144
|
+
init_report=init_report,
|
|
145
|
+
theme_applied=theme_applied,
|
|
146
|
+
theme_pending_install=theme_pending_install,
|
|
147
|
+
profiles_status=profiles_status,
|
|
148
|
+
)
|
termforge/doctor.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Diagnóstico del entorno de terminal."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from dataclasses import asdict, dataclass
|
|
8
|
+
from enum import Enum
|
|
9
|
+
|
|
10
|
+
from termforge import jsonc
|
|
11
|
+
from termforge.env import Env, powershell_profile_path, terminal_settings_path
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Status(str, Enum):
|
|
15
|
+
OK = "ok"
|
|
16
|
+
WARN = "warn"
|
|
17
|
+
FAIL = "fail"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class CheckResult:
|
|
22
|
+
name: str
|
|
23
|
+
status: Status
|
|
24
|
+
detail: str
|
|
25
|
+
hint: str = ""
|
|
26
|
+
|
|
27
|
+
def to_dict(self) -> dict[str, str]:
|
|
28
|
+
data = asdict(self)
|
|
29
|
+
data["status"] = self.status.value
|
|
30
|
+
return data
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
_NERD_FONT = re.compile(r"nerd font|\bNF[MP]?\b", re.IGNORECASE)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def installed_fonts(env: Env) -> list[str] | None:
|
|
37
|
+
"""Nombres de fuentes instaladas (registro de Windows). None si no se puede leer."""
|
|
38
|
+
if not env.is_windows:
|
|
39
|
+
return None
|
|
40
|
+
try:
|
|
41
|
+
import winreg # type: ignore[import-not-found]
|
|
42
|
+
except ImportError:
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
names: list[str] = []
|
|
46
|
+
locations = [
|
|
47
|
+
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"),
|
|
48
|
+
(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"),
|
|
49
|
+
]
|
|
50
|
+
for root, subkey in locations:
|
|
51
|
+
try:
|
|
52
|
+
with winreg.OpenKey(root, subkey) as key:
|
|
53
|
+
count = winreg.QueryInfoKey(key)[1]
|
|
54
|
+
names.extend(winreg.EnumValue(key, i)[0] for i in range(count))
|
|
55
|
+
except OSError:
|
|
56
|
+
continue
|
|
57
|
+
return names
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _program(env: Env, name: str, label: str, hint: str, status_if_missing: Status) -> CheckResult:
|
|
61
|
+
path = env.which(name)
|
|
62
|
+
if path:
|
|
63
|
+
return CheckResult(label, Status.OK, path)
|
|
64
|
+
return CheckResult(label, status_if_missing, "no encontrado", hint)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _check_os(env: Env) -> CheckResult:
|
|
68
|
+
if env.is_windows:
|
|
69
|
+
return CheckResult("Sistema operativo", Status.OK, "Windows")
|
|
70
|
+
return CheckResult(
|
|
71
|
+
"Sistema operativo",
|
|
72
|
+
Status.WARN,
|
|
73
|
+
f"{env.system or 'desconocido'}: termforge está pensado para Windows",
|
|
74
|
+
"Ejecútalo en Windows para un diagnóstico completo",
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _check_terminal_settings(env: Env) -> list[CheckResult]:
|
|
79
|
+
path = terminal_settings_path(env)
|
|
80
|
+
install_hint = "winget install --id Microsoft.WindowsTerminal"
|
|
81
|
+
if not path.exists():
|
|
82
|
+
missing = "settings.json no encontrado"
|
|
83
|
+
return [CheckResult("Windows Terminal", Status.FAIL, missing, install_hint)]
|
|
84
|
+
|
|
85
|
+
try:
|
|
86
|
+
data = jsonc.loads(path.read_text(encoding="utf-8-sig"))
|
|
87
|
+
except (OSError, ValueError) as exc:
|
|
88
|
+
return [
|
|
89
|
+
CheckResult(
|
|
90
|
+
"Windows Terminal",
|
|
91
|
+
Status.FAIL,
|
|
92
|
+
f"settings.json inválido: {exc}",
|
|
93
|
+
"Restaura un respaldo con `termforge restore` o corrige el JSON",
|
|
94
|
+
)
|
|
95
|
+
]
|
|
96
|
+
|
|
97
|
+
profiles = data.get("profiles", {}) if isinstance(data, dict) else {}
|
|
98
|
+
profile_list = profiles.get("list", []) if isinstance(profiles, dict) else []
|
|
99
|
+
results = [
|
|
100
|
+
CheckResult("Windows Terminal", Status.OK, f"{len(profile_list)} perfiles en {path}")
|
|
101
|
+
]
|
|
102
|
+
|
|
103
|
+
defaults = profiles.get("defaults", {}) if isinstance(profiles, dict) else {}
|
|
104
|
+
font = defaults.get("font", {}) if isinstance(defaults, dict) else {}
|
|
105
|
+
face = font.get("face") if isinstance(font, dict) else None
|
|
106
|
+
face = face or (defaults.get("fontFace") if isinstance(defaults, dict) else None)
|
|
107
|
+
if face:
|
|
108
|
+
results.append(CheckResult("Fuente del terminal", Status.OK, str(face)))
|
|
109
|
+
else:
|
|
110
|
+
results.append(
|
|
111
|
+
CheckResult(
|
|
112
|
+
"Fuente del terminal",
|
|
113
|
+
Status.WARN,
|
|
114
|
+
"sin fuente definida en profiles.defaults",
|
|
115
|
+
"Define una Nerd Font para ver iconos y ligaduras",
|
|
116
|
+
)
|
|
117
|
+
)
|
|
118
|
+
return results
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _check_nerd_font(env: Env, fonts: Callable[[Env], list[str] | None]) -> CheckResult:
|
|
122
|
+
names = fonts(env)
|
|
123
|
+
hint = "oh-my-posh font install"
|
|
124
|
+
if names is None:
|
|
125
|
+
return CheckResult("Nerd Font instalada", Status.WARN, "no se pudo verificar", hint)
|
|
126
|
+
matches = sorted({n for n in names if _NERD_FONT.search(n)})
|
|
127
|
+
if matches:
|
|
128
|
+
return CheckResult("Nerd Font instalada", Status.OK, matches[0])
|
|
129
|
+
return CheckResult("Nerd Font instalada", Status.WARN, "ninguna detectada", hint)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _check_profile(env: Env) -> CheckResult:
|
|
133
|
+
path = powershell_profile_path(env)
|
|
134
|
+
if not path.exists():
|
|
135
|
+
return CheckResult(
|
|
136
|
+
"Perfil de PowerShell",
|
|
137
|
+
Status.WARN,
|
|
138
|
+
"no existe",
|
|
139
|
+
"Se creará al configurar Oh My Posh",
|
|
140
|
+
)
|
|
141
|
+
try:
|
|
142
|
+
content = path.read_text(encoding="utf-8-sig")
|
|
143
|
+
except OSError as exc:
|
|
144
|
+
return CheckResult("Perfil de PowerShell", Status.FAIL, f"no se pudo leer: {exc}")
|
|
145
|
+
if "oh-my-posh" in content.lower():
|
|
146
|
+
return CheckResult("Perfil de PowerShell", Status.OK, f"inicializa Oh My Posh ({path})")
|
|
147
|
+
return CheckResult(
|
|
148
|
+
"Perfil de PowerShell",
|
|
149
|
+
Status.WARN,
|
|
150
|
+
"existe pero no inicializa Oh My Posh",
|
|
151
|
+
"Agrega: oh-my-posh init pwsh | Invoke-Expression",
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def run_checks(
|
|
156
|
+
env: Env,
|
|
157
|
+
fonts: Callable[[Env], list[str] | None] = installed_fonts,
|
|
158
|
+
) -> list[CheckResult]:
|
|
159
|
+
results: list[CheckResult] = [_check_os(env)]
|
|
160
|
+
results.append(
|
|
161
|
+
_program(
|
|
162
|
+
env,
|
|
163
|
+
"winget",
|
|
164
|
+
"winget",
|
|
165
|
+
"Instala 'App Installer' desde Microsoft Store",
|
|
166
|
+
Status.WARN,
|
|
167
|
+
)
|
|
168
|
+
)
|
|
169
|
+
results.append(
|
|
170
|
+
_program(
|
|
171
|
+
env,
|
|
172
|
+
"pwsh",
|
|
173
|
+
"PowerShell 7",
|
|
174
|
+
"winget install --id Microsoft.PowerShell",
|
|
175
|
+
Status.FAIL,
|
|
176
|
+
)
|
|
177
|
+
)
|
|
178
|
+
results.extend(_check_terminal_settings(env))
|
|
179
|
+
results.append(
|
|
180
|
+
_program(
|
|
181
|
+
env,
|
|
182
|
+
"oh-my-posh",
|
|
183
|
+
"Oh My Posh",
|
|
184
|
+
"winget install JanDeDobbeleer.OhMyPosh -s winget",
|
|
185
|
+
Status.FAIL,
|
|
186
|
+
)
|
|
187
|
+
)
|
|
188
|
+
results.append(_check_nerd_font(env, fonts))
|
|
189
|
+
results.append(_check_profile(env))
|
|
190
|
+
results.append(_program(env, "git", "Git", "winget install --id Git.Git", Status.WARN))
|
|
191
|
+
results.append(_program(env, "wsl", "WSL", "wsl --install", Status.WARN))
|
|
192
|
+
return results
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def exit_code(results: list[CheckResult]) -> int:
|
|
196
|
+
"""1 si hay algún fallo; las advertencias no cuentan como error."""
|
|
197
|
+
return 1 if any(r.status is Status.FAIL for r in results) else 0
|
termforge/env.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Entorno de ejecución y rutas conocidas.
|
|
2
|
+
|
|
3
|
+
Todo lo que depende del sistema (SO, variables, home, búsqueda de programas)
|
|
4
|
+
vive en `Env`, para poder simularlo en los tests sin tocar tu PC.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import platform
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
from collections.abc import Callable, Mapping
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class Env:
|
|
20
|
+
system: str = field(default_factory=platform.system)
|
|
21
|
+
environ: Mapping[str, str] = field(default_factory=lambda: dict(os.environ))
|
|
22
|
+
home: Path = field(default_factory=Path.home)
|
|
23
|
+
which: Callable[[str], str | None] = shutil.which
|
|
24
|
+
run: Callable[..., subprocess.CompletedProcess] = subprocess.run
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def is_windows(self) -> bool:
|
|
28
|
+
return self.system == "Windows"
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def local_appdata(self) -> Path:
|
|
32
|
+
value = self.environ.get("LOCALAPPDATA")
|
|
33
|
+
return Path(value) if value else self.home / "AppData" / "Local"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _first_existing(candidates: list[Path]) -> Path:
|
|
37
|
+
"""Devuelve el primer candidato que exista; si ninguno, el primero."""
|
|
38
|
+
for path in candidates:
|
|
39
|
+
if path.exists():
|
|
40
|
+
return path
|
|
41
|
+
return candidates[0]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def terminal_settings_candidates(env: Env) -> list[Path]:
|
|
45
|
+
local = env.local_appdata
|
|
46
|
+
return [
|
|
47
|
+
# Windows Terminal instalado desde Microsoft Store / winget
|
|
48
|
+
local
|
|
49
|
+
/ "Packages"
|
|
50
|
+
/ "Microsoft.WindowsTerminal_8wekyb3d8bbwe"
|
|
51
|
+
/ "LocalState"
|
|
52
|
+
/ "settings.json",
|
|
53
|
+
# Windows Terminal Preview
|
|
54
|
+
local
|
|
55
|
+
/ "Packages"
|
|
56
|
+
/ "Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe"
|
|
57
|
+
/ "LocalState"
|
|
58
|
+
/ "settings.json",
|
|
59
|
+
# Instalación sin empaquetar (portable)
|
|
60
|
+
local / "Microsoft" / "Windows Terminal" / "settings.json",
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def terminal_settings_path(env: Env) -> Path:
|
|
65
|
+
return _first_existing(terminal_settings_candidates(env))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def powershell_profile_candidates(env: Env) -> list[Path]:
|
|
69
|
+
name = Path("PowerShell") / "Microsoft.PowerShell_profile.ps1"
|
|
70
|
+
return [
|
|
71
|
+
env.home / "Documents" / name,
|
|
72
|
+
# Si OneDrive redirige la carpeta Documentos
|
|
73
|
+
env.home / "OneDrive" / "Documents" / name,
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def powershell_profile_path(env: Env) -> Path:
|
|
78
|
+
return _first_existing(powershell_profile_candidates(env))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def managed_files(env: Env) -> dict[str, Path]:
|
|
82
|
+
"""Archivos que termforge respalda y restaura, por nombre estable."""
|
|
83
|
+
return {
|
|
84
|
+
"windows-terminal": terminal_settings_path(env),
|
|
85
|
+
"powershell-profile": powershell_profile_path(env),
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def backup_root(env: Env) -> Path:
|
|
90
|
+
override = env.environ.get("TERMFORGE_HOME")
|
|
91
|
+
if override:
|
|
92
|
+
return Path(override) / "backups"
|
|
93
|
+
if env.is_windows:
|
|
94
|
+
return env.local_appdata / "termforge" / "backups"
|
|
95
|
+
data_home = env.environ.get("XDG_DATA_HOME")
|
|
96
|
+
base = Path(data_home) if data_home else env.home / ".local" / "share"
|
|
97
|
+
return base / "termforge" / "backups"
|
termforge/init.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Instalación de dependencias (winget) y configuración de Oh My Posh."""
|
|
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
|
+
OH_MY_POSH_INIT_LINE = "oh-my-posh init pwsh | Invoke-Expression"
|
|
12
|
+
_MARKER = "# Agregado por termforge init"
|
|
13
|
+
|
|
14
|
+
_REQUIRED_PROGRAMS = [
|
|
15
|
+
("pwsh", "PowerShell 7", "Microsoft.PowerShell"),
|
|
16
|
+
("oh-my-posh", "Oh My Posh", "JanDeDobbeleer.OhMyPosh"),
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class InstallStep:
|
|
22
|
+
id: str
|
|
23
|
+
name: str
|
|
24
|
+
package_id: str
|
|
25
|
+
installed: bool
|
|
26
|
+
command: list[str]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class ProfileStep:
|
|
31
|
+
path: Path
|
|
32
|
+
exists: bool
|
|
33
|
+
already_configured: bool
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class InitPlan:
|
|
38
|
+
install_steps: list[InstallStep]
|
|
39
|
+
profile: ProfileStep
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def pending_installs(self) -> list[InstallStep]:
|
|
43
|
+
return [s for s in self.install_steps if not s.installed]
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def has_pending_work(self) -> bool:
|
|
47
|
+
return bool(self.pending_installs) or not self.profile.already_configured
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class InitReport:
|
|
52
|
+
installed: list[InstallStep]
|
|
53
|
+
failed: list[tuple[InstallStep, str]]
|
|
54
|
+
profile_updated: bool
|
|
55
|
+
profile_backup: BackupInfo | None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _winget_install_command(package_id: str) -> list[str]:
|
|
59
|
+
return [
|
|
60
|
+
"winget",
|
|
61
|
+
"install",
|
|
62
|
+
"--id",
|
|
63
|
+
package_id,
|
|
64
|
+
"-e",
|
|
65
|
+
"--source",
|
|
66
|
+
"winget",
|
|
67
|
+
"--accept-package-agreements",
|
|
68
|
+
"--accept-source-agreements",
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def build_plan(env: Env) -> InitPlan:
|
|
73
|
+
"""Qué falta instalar y si el perfil de PowerShell ya inicializa Oh My Posh."""
|
|
74
|
+
steps = [
|
|
75
|
+
InstallStep(
|
|
76
|
+
id=cmd,
|
|
77
|
+
name=name,
|
|
78
|
+
package_id=package_id,
|
|
79
|
+
installed=env.which(cmd) is not None,
|
|
80
|
+
command=_winget_install_command(package_id),
|
|
81
|
+
)
|
|
82
|
+
for cmd, name, package_id in _REQUIRED_PROGRAMS
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
path = powershell_profile_path(env)
|
|
86
|
+
exists = path.exists()
|
|
87
|
+
content = path.read_text(encoding="utf-8-sig") if exists else ""
|
|
88
|
+
already_configured = "oh-my-posh" in content.lower()
|
|
89
|
+
profile = ProfileStep(path=path, exists=exists, already_configured=already_configured)
|
|
90
|
+
|
|
91
|
+
return InitPlan(install_steps=steps, profile=profile)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def apply_plan(env: Env, plan: InitPlan, backup_root: Path) -> InitReport:
|
|
95
|
+
"""Ejecuta los `winget install` pendientes y agrega la inicialización al perfil."""
|
|
96
|
+
installed: list[InstallStep] = []
|
|
97
|
+
failed: list[tuple[InstallStep, str]] = []
|
|
98
|
+
|
|
99
|
+
for step in plan.pending_installs:
|
|
100
|
+
try:
|
|
101
|
+
result = env.run(step.command, capture_output=True, text=True)
|
|
102
|
+
except OSError as exc:
|
|
103
|
+
failed.append((step, str(exc)))
|
|
104
|
+
continue
|
|
105
|
+
if result.returncode == 0:
|
|
106
|
+
installed.append(step)
|
|
107
|
+
else:
|
|
108
|
+
fallback = f"código de salida {result.returncode}"
|
|
109
|
+
error = (result.stderr or result.stdout or fallback).strip()
|
|
110
|
+
failed.append((step, error))
|
|
111
|
+
|
|
112
|
+
profile_updated = False
|
|
113
|
+
profile_backup = None
|
|
114
|
+
if not plan.profile.already_configured:
|
|
115
|
+
if plan.profile.exists:
|
|
116
|
+
profile_backup = create_backup(
|
|
117
|
+
{"powershell-profile": plan.profile.path}, backup_root, label="pre-init"
|
|
118
|
+
)
|
|
119
|
+
plan.profile.path.parent.mkdir(parents=True, exist_ok=True)
|
|
120
|
+
needs_leading_newline = plan.profile.exists and plan.profile.path.stat().st_size > 0
|
|
121
|
+
with plan.profile.path.open("a", encoding="utf-8") as f:
|
|
122
|
+
if needs_leading_newline:
|
|
123
|
+
f.write("\n")
|
|
124
|
+
f.write(f"{_MARKER}\n{OH_MY_POSH_INIT_LINE}\n")
|
|
125
|
+
profile_updated = True
|
|
126
|
+
|
|
127
|
+
return InitReport(
|
|
128
|
+
installed=installed,
|
|
129
|
+
failed=failed,
|
|
130
|
+
profile_updated=profile_updated,
|
|
131
|
+
profile_backup=profile_backup,
|
|
132
|
+
)
|
termforge/jsonc.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Lector de JSON con comentarios (JSONC).
|
|
2
|
+
|
|
3
|
+
El settings.json de Windows Terminal permite comentarios (// y /* */) y comas
|
|
4
|
+
finales, que el módulo json estándar rechaza. Este módulo los limpia sin tocar
|
|
5
|
+
el contenido de los strings.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def strip_jsonc(text: str) -> str:
|
|
15
|
+
"""Quita comentarios y comas finales, respetando los strings."""
|
|
16
|
+
out: list[str] = []
|
|
17
|
+
i, n = 0, len(text)
|
|
18
|
+
in_string = False
|
|
19
|
+
|
|
20
|
+
while i < n:
|
|
21
|
+
c = text[i]
|
|
22
|
+
|
|
23
|
+
if in_string:
|
|
24
|
+
out.append(c)
|
|
25
|
+
if c == "\\" and i + 1 < n:
|
|
26
|
+
out.append(text[i + 1])
|
|
27
|
+
i += 2
|
|
28
|
+
continue
|
|
29
|
+
if c == '"':
|
|
30
|
+
in_string = False
|
|
31
|
+
i += 1
|
|
32
|
+
continue
|
|
33
|
+
|
|
34
|
+
if c == '"':
|
|
35
|
+
in_string = True
|
|
36
|
+
out.append(c)
|
|
37
|
+
i += 1
|
|
38
|
+
elif text.startswith("//", i):
|
|
39
|
+
while i < n and text[i] not in "\r\n":
|
|
40
|
+
i += 1
|
|
41
|
+
elif text.startswith("/*", i):
|
|
42
|
+
end = text.find("*/", i + 2)
|
|
43
|
+
if end == -1:
|
|
44
|
+
raise ValueError("comentario /* sin cerrar")
|
|
45
|
+
i = end + 2
|
|
46
|
+
else:
|
|
47
|
+
out.append(c)
|
|
48
|
+
i += 1
|
|
49
|
+
|
|
50
|
+
return _remove_trailing_commas("".join(out))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _remove_trailing_commas(text: str) -> str:
|
|
54
|
+
out: list[str] = []
|
|
55
|
+
in_string = False
|
|
56
|
+
i, n = 0, len(text)
|
|
57
|
+
|
|
58
|
+
while i < n:
|
|
59
|
+
c = text[i]
|
|
60
|
+
|
|
61
|
+
if in_string:
|
|
62
|
+
out.append(c)
|
|
63
|
+
if c == "\\" and i + 1 < n:
|
|
64
|
+
out.append(text[i + 1])
|
|
65
|
+
i += 2
|
|
66
|
+
continue
|
|
67
|
+
if c == '"':
|
|
68
|
+
in_string = False
|
|
69
|
+
i += 1
|
|
70
|
+
continue
|
|
71
|
+
|
|
72
|
+
if c == '"':
|
|
73
|
+
in_string = True
|
|
74
|
+
elif c == ",":
|
|
75
|
+
j = i + 1
|
|
76
|
+
while j < n and text[j] in " \t\r\n":
|
|
77
|
+
j += 1
|
|
78
|
+
if j < n and text[j] in "}]":
|
|
79
|
+
i += 1
|
|
80
|
+
continue
|
|
81
|
+
out.append(c)
|
|
82
|
+
i += 1
|
|
83
|
+
|
|
84
|
+
return "".join(out)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def loads(text: str) -> Any:
|
|
88
|
+
"""Equivalente a json.loads, pero tolera comentarios, comas finales y BOM."""
|
|
89
|
+
return json.loads(strip_jsonc(text.lstrip("")))
|