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/__init__.py
ADDED
termforge/__main__.py
ADDED
termforge/backup.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Respaldo y restauración de los archivos de configuración de la terminal."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
MANIFEST = "manifest.json"
|
|
14
|
+
MANIFEST_VERSION = 1
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class BackupError(Exception):
|
|
18
|
+
"""Error esperado (nada que respaldar, respaldo inexistente, etc.)."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class BackupEntry:
|
|
23
|
+
name: str
|
|
24
|
+
stored: str
|
|
25
|
+
original: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class BackupInfo:
|
|
30
|
+
id: str
|
|
31
|
+
path: Path
|
|
32
|
+
created: str
|
|
33
|
+
label: str
|
|
34
|
+
entries: list[BackupEntry]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class RestoreAction:
|
|
39
|
+
name: str
|
|
40
|
+
destination: Path
|
|
41
|
+
overwrites: bool
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class RestoreReport:
|
|
46
|
+
backup: BackupInfo
|
|
47
|
+
actions: list[RestoreAction]
|
|
48
|
+
skipped: list[str]
|
|
49
|
+
safety_backup: BackupInfo | None
|
|
50
|
+
dry_run: bool
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _slug(label: str) -> str:
|
|
54
|
+
return re.sub(r"[^a-z0-9]+", "-", label.lower()).strip("-")[:40]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _unique_dir(root: Path, base_id: str) -> tuple[str, Path]:
|
|
58
|
+
candidate, counter = base_id, 1
|
|
59
|
+
while (root / candidate).exists():
|
|
60
|
+
counter += 1
|
|
61
|
+
candidate = f"{base_id}-{counter}"
|
|
62
|
+
return candidate, root / candidate
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def create_backup(
|
|
66
|
+
targets: Mapping[str, Path],
|
|
67
|
+
root: Path,
|
|
68
|
+
label: str = "",
|
|
69
|
+
now: datetime | None = None,
|
|
70
|
+
) -> BackupInfo:
|
|
71
|
+
"""Copia los archivos existentes de `targets` a una carpeta con fecha."""
|
|
72
|
+
existing = {name: path for name, path in targets.items() if path.is_file()}
|
|
73
|
+
if not existing:
|
|
74
|
+
raise BackupError("No hay archivos de configuración para respaldar.")
|
|
75
|
+
|
|
76
|
+
now = now or datetime.now()
|
|
77
|
+
base_id = now.strftime("%Y%m%d-%H%M%S")
|
|
78
|
+
if label:
|
|
79
|
+
base_id = f"{base_id}-{_slug(label)}".rstrip("-")
|
|
80
|
+
|
|
81
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
82
|
+
backup_id, backup_dir = _unique_dir(root, base_id)
|
|
83
|
+
backup_dir.mkdir()
|
|
84
|
+
|
|
85
|
+
entries: list[BackupEntry] = []
|
|
86
|
+
for name, path in existing.items():
|
|
87
|
+
stored = f"{name}{path.suffix}"
|
|
88
|
+
shutil.copy2(path, backup_dir / stored)
|
|
89
|
+
entries.append(BackupEntry(name=name, stored=stored, original=str(path)))
|
|
90
|
+
|
|
91
|
+
manifest = {
|
|
92
|
+
"version": MANIFEST_VERSION,
|
|
93
|
+
"id": backup_id,
|
|
94
|
+
"created": now.isoformat(timespec="seconds"),
|
|
95
|
+
"label": label,
|
|
96
|
+
"entries": [e.__dict__ for e in entries],
|
|
97
|
+
}
|
|
98
|
+
(backup_dir / MANIFEST).write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
|
99
|
+
|
|
100
|
+
return BackupInfo(backup_id, backup_dir, manifest["created"], label, entries)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _load(backup_dir: Path) -> BackupInfo | None:
|
|
104
|
+
manifest_path = backup_dir / MANIFEST
|
|
105
|
+
try:
|
|
106
|
+
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
|
107
|
+
entries = [BackupEntry(**e) for e in data["entries"]]
|
|
108
|
+
return BackupInfo(
|
|
109
|
+
id=backup_dir.name,
|
|
110
|
+
path=backup_dir,
|
|
111
|
+
created=data["created"],
|
|
112
|
+
label=data.get("label", ""),
|
|
113
|
+
entries=entries,
|
|
114
|
+
)
|
|
115
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def list_backups(root: Path) -> list[BackupInfo]:
|
|
120
|
+
"""Respaldos válidos, del más reciente al más antiguo."""
|
|
121
|
+
if not root.is_dir():
|
|
122
|
+
return []
|
|
123
|
+
found = [info for d in root.iterdir() if d.is_dir() and (info := _load(d))]
|
|
124
|
+
return sorted(found, key=lambda b: b.id, reverse=True)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def get_backup(root: Path, backup_id: str | None = None) -> BackupInfo:
|
|
128
|
+
"""Busca un respaldo por id; sin id devuelve el más reciente."""
|
|
129
|
+
if backup_id is None or backup_id == "latest":
|
|
130
|
+
backups = list_backups(root)
|
|
131
|
+
if not backups:
|
|
132
|
+
raise BackupError("No hay respaldos. Crea uno con `termforge backup`.")
|
|
133
|
+
return backups[0]
|
|
134
|
+
|
|
135
|
+
# Evita rutas como "../x": el id debe ser un nombre de carpeta simple.
|
|
136
|
+
if Path(backup_id).name != backup_id or backup_id in {".", ".."}:
|
|
137
|
+
raise BackupError(f"Id de respaldo inválido: {backup_id!r}")
|
|
138
|
+
info = _load(root / backup_id)
|
|
139
|
+
if info is None:
|
|
140
|
+
raise BackupError(f"No existe el respaldo {backup_id!r}.")
|
|
141
|
+
return info
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def restore_backup(
|
|
145
|
+
root: Path,
|
|
146
|
+
targets: Mapping[str, Path],
|
|
147
|
+
backup_id: str | None = None,
|
|
148
|
+
dry_run: bool = False,
|
|
149
|
+
now: datetime | None = None,
|
|
150
|
+
) -> RestoreReport:
|
|
151
|
+
"""Restaura un respaldo. Antes de sobrescribir guarda el estado actual."""
|
|
152
|
+
backup = get_backup(root, backup_id)
|
|
153
|
+
|
|
154
|
+
actions: list[RestoreAction] = []
|
|
155
|
+
skipped: list[str] = []
|
|
156
|
+
for entry in backup.entries:
|
|
157
|
+
stored = backup.path / entry.stored
|
|
158
|
+
# Solo nombres de archivo simples y destinos conocidos.
|
|
159
|
+
if Path(entry.stored).name != entry.stored or not stored.is_file():
|
|
160
|
+
skipped.append(entry.name)
|
|
161
|
+
continue
|
|
162
|
+
if entry.name not in targets:
|
|
163
|
+
skipped.append(entry.name)
|
|
164
|
+
continue
|
|
165
|
+
destination = targets[entry.name]
|
|
166
|
+
actions.append(RestoreAction(entry.name, destination, destination.exists()))
|
|
167
|
+
|
|
168
|
+
if dry_run:
|
|
169
|
+
return RestoreReport(backup, actions, skipped, None, dry_run=True)
|
|
170
|
+
|
|
171
|
+
current = {a.name: a.destination for a in actions if a.overwrites}
|
|
172
|
+
safety = create_backup(current, root, label="pre-restore", now=now) if current else None
|
|
173
|
+
|
|
174
|
+
entries = {e.name: e for e in backup.entries}
|
|
175
|
+
for action in actions:
|
|
176
|
+
action.destination.parent.mkdir(parents=True, exist_ok=True)
|
|
177
|
+
shutil.copy2(backup.path / entries[action.name].stored, action.destination)
|
|
178
|
+
|
|
179
|
+
return RestoreReport(backup, actions, skipped, safety, dry_run=False)
|
termforge/cli.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
"""Interfaz de línea de comandos de termforge."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Annotated
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
from rich import box
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
from rich.table import Table
|
|
13
|
+
|
|
14
|
+
from termforge import __version__
|
|
15
|
+
from termforge.backup import (
|
|
16
|
+
BackupError,
|
|
17
|
+
create_backup,
|
|
18
|
+
list_backups,
|
|
19
|
+
restore_backup,
|
|
20
|
+
)
|
|
21
|
+
from termforge.config import ConfigError, ConfigReport, TermforgeConfig, load_config, run_config
|
|
22
|
+
from termforge.doctor import CheckResult, Status, exit_code, run_checks
|
|
23
|
+
from termforge.env import Env, backup_root, managed_files
|
|
24
|
+
from termforge.init import InitPlan, apply_plan, build_plan
|
|
25
|
+
from termforge.profiles import ProfileCandidate, ProfilesError
|
|
26
|
+
from termforge.profiles import apply_plan as apply_profiles_plan
|
|
27
|
+
from termforge.profiles import build_plan as build_profiles_plan
|
|
28
|
+
from termforge.theme import Theme, ThemeError, apply_theme, find_theme, list_themes
|
|
29
|
+
|
|
30
|
+
app = typer.Typer(
|
|
31
|
+
help="Diagnostica, respalda y configura tu terminal de Windows.",
|
|
32
|
+
no_args_is_help=True,
|
|
33
|
+
add_completion=False,
|
|
34
|
+
)
|
|
35
|
+
console = Console()
|
|
36
|
+
err_console = Console(stderr=True)
|
|
37
|
+
|
|
38
|
+
_STATUS_STYLE = {
|
|
39
|
+
Status.OK: ("OK", "green"),
|
|
40
|
+
Status.WARN: ("AVISO", "yellow"),
|
|
41
|
+
Status.FAIL: ("FALLO", "red"),
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def get_env() -> Env:
|
|
46
|
+
"""Punto único para obtener el entorno (se reemplaza en los tests)."""
|
|
47
|
+
return Env()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _version_callback(value: bool) -> None:
|
|
51
|
+
if value:
|
|
52
|
+
console.print(f"termforge {__version__}")
|
|
53
|
+
raise typer.Exit()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@app.callback()
|
|
57
|
+
def main(
|
|
58
|
+
version: Annotated[
|
|
59
|
+
bool,
|
|
60
|
+
typer.Option(
|
|
61
|
+
"--version", "-v", callback=_version_callback, is_eager=True, help="Muestra la versión."
|
|
62
|
+
),
|
|
63
|
+
] = False,
|
|
64
|
+
) -> None:
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _render_checks(results: list[CheckResult]) -> None:
|
|
69
|
+
table = Table(box=box.SIMPLE_HEAD, show_edge=False, pad_edge=False)
|
|
70
|
+
table.add_column("Estado")
|
|
71
|
+
table.add_column("Revisión")
|
|
72
|
+
table.add_column("Detalle", overflow="fold")
|
|
73
|
+
for r in results:
|
|
74
|
+
label, color = _STATUS_STYLE[r.status]
|
|
75
|
+
table.add_row(f"[{color}]{label}[/{color}]", r.name, r.detail)
|
|
76
|
+
console.print(table)
|
|
77
|
+
|
|
78
|
+
hints = [r for r in results if r.status is not Status.OK and r.hint]
|
|
79
|
+
if hints:
|
|
80
|
+
console.print("\n[bold]Cómo arreglarlo[/bold]")
|
|
81
|
+
for r in hints:
|
|
82
|
+
console.print(f" {r.name}: [cyan]{r.hint}[/cyan]", highlight=False)
|
|
83
|
+
|
|
84
|
+
fails = sum(r.status is Status.FAIL for r in results)
|
|
85
|
+
warns = sum(r.status is Status.WARN for r in results)
|
|
86
|
+
oks = sum(r.status is Status.OK for r in results)
|
|
87
|
+
console.print(f"\nOK: {oks} | Avisos: {warns} | Fallos: {fails}")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@app.command()
|
|
91
|
+
def doctor(
|
|
92
|
+
json_output: Annotated[
|
|
93
|
+
bool, typer.Option("--json", help="Salida en JSON (para scripts).")
|
|
94
|
+
] = False,
|
|
95
|
+
) -> None:
|
|
96
|
+
"""Revisa qué falta o está mal configurado en tu terminal."""
|
|
97
|
+
results = run_checks(get_env())
|
|
98
|
+
if json_output:
|
|
99
|
+
typer.echo(json.dumps([r.to_dict() for r in results], indent=2, ensure_ascii=False))
|
|
100
|
+
else:
|
|
101
|
+
_render_checks(results)
|
|
102
|
+
raise typer.Exit(exit_code(results))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _render_init_plan(plan: InitPlan) -> None:
|
|
106
|
+
pending = plan.pending_installs
|
|
107
|
+
if pending:
|
|
108
|
+
console.print("[bold]Se instalará con winget:[/bold]")
|
|
109
|
+
for step in pending:
|
|
110
|
+
console.print(f" {step.name} ([cyan]{step.package_id}[/cyan])", highlight=False)
|
|
111
|
+
else:
|
|
112
|
+
console.print("[green]Ya están instalados: PowerShell 7, Oh My Posh.[/green]")
|
|
113
|
+
|
|
114
|
+
if plan.profile.already_configured:
|
|
115
|
+
console.print("[green]El perfil de PowerShell ya inicializa Oh My Posh.[/green]")
|
|
116
|
+
else:
|
|
117
|
+
verb = "agrega" if plan.profile.exists else "crea y agrega"
|
|
118
|
+
console.print(
|
|
119
|
+
f"[bold]Perfil de PowerShell:[/bold] {verb} la inicialización en {plan.profile.path}"
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@app.command()
|
|
124
|
+
def init(
|
|
125
|
+
dry_run: Annotated[
|
|
126
|
+
bool, typer.Option("--dry-run", help="Muestra qué haría sin instalar ni modificar nada.")
|
|
127
|
+
] = False,
|
|
128
|
+
yes: Annotated[bool, typer.Option("--yes", "-y", help="No pedir confirmación.")] = False,
|
|
129
|
+
) -> None:
|
|
130
|
+
"""Instala lo que falte (winget) y configura Oh My Posh en tu perfil de PowerShell."""
|
|
131
|
+
env = get_env()
|
|
132
|
+
plan = build_plan(env)
|
|
133
|
+
|
|
134
|
+
if not plan.has_pending_work:
|
|
135
|
+
console.print("[green]Todo ya está instalado y configurado.[/green]")
|
|
136
|
+
return
|
|
137
|
+
|
|
138
|
+
_render_init_plan(plan)
|
|
139
|
+
|
|
140
|
+
if dry_run:
|
|
141
|
+
console.print("\n[dim]--dry-run: no se instaló ni modificó nada.[/dim]")
|
|
142
|
+
return
|
|
143
|
+
if not yes and not typer.confirm("\n¿Continuar?"):
|
|
144
|
+
raise typer.Exit(1)
|
|
145
|
+
|
|
146
|
+
report = apply_plan(env, plan, backup_root(env))
|
|
147
|
+
|
|
148
|
+
for step in report.installed:
|
|
149
|
+
console.print(f"[green]Instalado:[/green] {step.name}")
|
|
150
|
+
for step, error in report.failed:
|
|
151
|
+
err_console.print(f"[red]Falló instalar {step.name}:[/red] {error}")
|
|
152
|
+
if report.profile_updated:
|
|
153
|
+
console.print(f"[green]Perfil actualizado:[/green] {plan.profile.path}")
|
|
154
|
+
if report.profile_backup:
|
|
155
|
+
console.print(
|
|
156
|
+
f"Estado anterior guardado como {report.profile_backup.id}", highlight=False
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
if report.installed:
|
|
160
|
+
console.print("\n[yellow]Reinicia la terminal para que los cambios tomen efecto.[/yellow]")
|
|
161
|
+
if report.failed:
|
|
162
|
+
raise typer.Exit(1)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _render_themes(themes: list[Theme]) -> None:
|
|
166
|
+
table = Table(box=box.SIMPLE_HEAD, show_edge=False, pad_edge=False)
|
|
167
|
+
table.add_column("#")
|
|
168
|
+
table.add_column("Tema")
|
|
169
|
+
for i, t in enumerate(themes, start=1):
|
|
170
|
+
table.add_row(str(i), t.name)
|
|
171
|
+
console.print(table)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@app.command()
|
|
175
|
+
def theme(
|
|
176
|
+
selector: Annotated[
|
|
177
|
+
str | None, typer.Argument(help="Número de la lista o nombre del tema (parcial sirve).")
|
|
178
|
+
] = None,
|
|
179
|
+
list_only: Annotated[
|
|
180
|
+
bool, typer.Option("--list", "-l", help="Solo lista los temas, no aplica nada.")
|
|
181
|
+
] = False,
|
|
182
|
+
) -> None:
|
|
183
|
+
"""Elige un tema de Oh My Posh de una lista, sin buscar el nombre exacto."""
|
|
184
|
+
env = get_env()
|
|
185
|
+
themes = list_themes(env)
|
|
186
|
+
if not themes:
|
|
187
|
+
err_console.print(
|
|
188
|
+
"[red]No se encontraron temas de Oh My Posh.[/red] "
|
|
189
|
+
"¿Está instalado? Corre `termforge init`."
|
|
190
|
+
)
|
|
191
|
+
raise typer.Exit(1)
|
|
192
|
+
|
|
193
|
+
_render_themes(themes)
|
|
194
|
+
if list_only:
|
|
195
|
+
return
|
|
196
|
+
|
|
197
|
+
if selector is None:
|
|
198
|
+
selector = typer.prompt("\nElige un tema (número o nombre)")
|
|
199
|
+
|
|
200
|
+
try:
|
|
201
|
+
chosen = find_theme(themes, selector)
|
|
202
|
+
except ThemeError as exc:
|
|
203
|
+
err_console.print(f"[red]{exc}[/red]")
|
|
204
|
+
raise typer.Exit(1) from exc
|
|
205
|
+
|
|
206
|
+
backup_info = apply_theme(env, chosen, backup_root(env))
|
|
207
|
+
console.print(f"\n[green]Tema aplicado:[/green] {chosen.name}")
|
|
208
|
+
if backup_info:
|
|
209
|
+
console.print(f"Perfil anterior guardado como {backup_info.id}", highlight=False)
|
|
210
|
+
console.print("[yellow]Reinicia la terminal para verlo.[/yellow]")
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@app.command()
|
|
214
|
+
def profiles(
|
|
215
|
+
dry_run: Annotated[
|
|
216
|
+
bool, typer.Option("--dry-run", help="Muestra qué agregaría sin modificar nada.")
|
|
217
|
+
] = False,
|
|
218
|
+
yes: Annotated[bool, typer.Option("--yes", "-y", help="No pedir confirmación.")] = False,
|
|
219
|
+
) -> None:
|
|
220
|
+
"""Agrega Git Bash y los distros de WSL detectados al menú de Windows Terminal."""
|
|
221
|
+
env = get_env()
|
|
222
|
+
try:
|
|
223
|
+
data, candidates = build_profiles_plan(env)
|
|
224
|
+
except ProfilesError as exc:
|
|
225
|
+
err_console.print(f"[red]{exc}[/red]")
|
|
226
|
+
raise typer.Exit(1) from exc
|
|
227
|
+
|
|
228
|
+
if not candidates:
|
|
229
|
+
console.print("No se detectó Git Bash ni distros de WSL para agregar.")
|
|
230
|
+
return
|
|
231
|
+
|
|
232
|
+
for c in candidates:
|
|
233
|
+
marker = "[green]ya está[/green]" if c.already_present else "[cyan]se agregará[/cyan]"
|
|
234
|
+
console.print(f" {c.name}: {marker}", highlight=False)
|
|
235
|
+
|
|
236
|
+
pending: list[ProfileCandidate] = [c for c in candidates if not c.already_present]
|
|
237
|
+
if not pending:
|
|
238
|
+
console.print("\n[green]Ya están todos en el menú de Windows Terminal.[/green]")
|
|
239
|
+
return
|
|
240
|
+
|
|
241
|
+
if dry_run:
|
|
242
|
+
console.print("\n[dim]--dry-run: no se modificó nada.[/dim]")
|
|
243
|
+
return
|
|
244
|
+
if not yes and not typer.confirm(
|
|
245
|
+
"\nEsto reescribe settings.json (se respalda antes, pero se pierde cualquier "
|
|
246
|
+
"comentario manual que tengas ahí). ¿Continuar?"
|
|
247
|
+
):
|
|
248
|
+
raise typer.Exit(1)
|
|
249
|
+
|
|
250
|
+
backup_info = apply_profiles_plan(env, data, pending, backup_root(env))
|
|
251
|
+
names = ", ".join(c.name for c in pending)
|
|
252
|
+
console.print(f"\n[green]Perfiles agregados:[/green] {names}")
|
|
253
|
+
console.print(f"Respaldo previo guardado como {backup_info.id}", highlight=False)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _render_config_report(config: TermforgeConfig, report: ConfigReport) -> None:
|
|
257
|
+
if config.init:
|
|
258
|
+
plan = report.init_plan
|
|
259
|
+
if plan and plan.has_pending_work:
|
|
260
|
+
pending = [s.name for s in plan.pending_installs]
|
|
261
|
+
if pending:
|
|
262
|
+
console.print(f"[bold]init:[/bold] instalaría {', '.join(pending)}")
|
|
263
|
+
if not plan.profile.already_configured:
|
|
264
|
+
console.print(
|
|
265
|
+
"[bold]init:[/bold] inicializaría Oh My Posh en el perfil de PowerShell"
|
|
266
|
+
)
|
|
267
|
+
else:
|
|
268
|
+
console.print("[bold]init:[/bold] [green]ya está todo instalado y configurado[/green]")
|
|
269
|
+
|
|
270
|
+
if config.theme:
|
|
271
|
+
if report.theme_pending_install:
|
|
272
|
+
console.print(
|
|
273
|
+
f"[bold]theme:[/bold] '{config.theme}' se aplicará después de que "
|
|
274
|
+
"`init` instale Oh My Posh"
|
|
275
|
+
)
|
|
276
|
+
elif report.theme_applied:
|
|
277
|
+
console.print(f"[bold]theme:[/bold] aplicaría '{report.theme_applied.name}'")
|
|
278
|
+
|
|
279
|
+
if config.profiles:
|
|
280
|
+
if report.profiles_status:
|
|
281
|
+
for c in report.profiles_status:
|
|
282
|
+
marker = "ya está" if c.already_present else "se agregaría"
|
|
283
|
+
console.print(f"[bold]profiles:[/bold] {c.name}: {marker}")
|
|
284
|
+
else:
|
|
285
|
+
console.print("[bold]profiles:[/bold] nada que coincida con lo pedido en este equipo")
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
@app.command()
|
|
289
|
+
def apply(
|
|
290
|
+
file: Annotated[
|
|
291
|
+
Path, typer.Option("--file", "-f", help="Archivo de configuración declarativa (YAML).")
|
|
292
|
+
] = Path("termforge.yaml"),
|
|
293
|
+
dry_run: Annotated[
|
|
294
|
+
bool, typer.Option("--dry-run", help="Muestra qué haría sin instalar ni modificar nada.")
|
|
295
|
+
] = False,
|
|
296
|
+
yes: Annotated[bool, typer.Option("--yes", "-y", help="No pedir confirmación.")] = False,
|
|
297
|
+
) -> None:
|
|
298
|
+
"""Deja tu terminal como la describe un YAML (init, theme, profiles en uno)."""
|
|
299
|
+
env = get_env()
|
|
300
|
+
try:
|
|
301
|
+
config = load_config(file)
|
|
302
|
+
except ConfigError as exc:
|
|
303
|
+
err_console.print(f"[red]{exc}[/red]")
|
|
304
|
+
raise typer.Exit(1) from exc
|
|
305
|
+
|
|
306
|
+
if config.is_empty:
|
|
307
|
+
console.print(f"Archivo: {file}", highlight=False)
|
|
308
|
+
console.print("No hay nada que aplicar (agrega `init`, `theme` o `profiles`).")
|
|
309
|
+
return
|
|
310
|
+
|
|
311
|
+
try:
|
|
312
|
+
preview = run_config(env, config, backup_root(env), dry_run=True)
|
|
313
|
+
except ConfigError as exc:
|
|
314
|
+
err_console.print(f"[red]{exc}[/red]")
|
|
315
|
+
raise typer.Exit(1) from exc
|
|
316
|
+
|
|
317
|
+
_render_config_report(config, preview)
|
|
318
|
+
|
|
319
|
+
if dry_run:
|
|
320
|
+
console.print("\n[dim]--dry-run: no se instaló ni modificó nada.[/dim]")
|
|
321
|
+
return
|
|
322
|
+
if not yes and not typer.confirm("\n¿Aplicar esta configuración?"):
|
|
323
|
+
raise typer.Exit(1)
|
|
324
|
+
|
|
325
|
+
try:
|
|
326
|
+
run_config(env, config, backup_root(env), dry_run=False)
|
|
327
|
+
except ConfigError as exc:
|
|
328
|
+
err_console.print(f"[red]{exc}[/red]")
|
|
329
|
+
raise typer.Exit(1) from exc
|
|
330
|
+
|
|
331
|
+
console.print("\n[green]Configuración aplicada.[/green]")
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
@app.command()
|
|
335
|
+
def backup(
|
|
336
|
+
label: Annotated[str, typer.Option("--label", "-l", help="Etiqueta opcional.")] = "",
|
|
337
|
+
) -> None:
|
|
338
|
+
"""Guarda una copia de tu configuración actual."""
|
|
339
|
+
env = get_env()
|
|
340
|
+
try:
|
|
341
|
+
info = create_backup(managed_files(env), backup_root(env), label=label)
|
|
342
|
+
except BackupError as exc:
|
|
343
|
+
err_console.print(f"[red]{exc}[/red]")
|
|
344
|
+
raise typer.Exit(1) from exc
|
|
345
|
+
|
|
346
|
+
console.print(f"[green]Respaldo creado:[/green] {info.id}")
|
|
347
|
+
for entry in info.entries:
|
|
348
|
+
console.print(f" {entry.name}", highlight=False)
|
|
349
|
+
console.print(f"Ubicación: {info.path}", highlight=False)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
@app.command()
|
|
353
|
+
def backups() -> None:
|
|
354
|
+
"""Lista los respaldos disponibles."""
|
|
355
|
+
found = list_backups(backup_root(get_env()))
|
|
356
|
+
if not found:
|
|
357
|
+
console.print("No hay respaldos todavía. Crea uno con `termforge backup`.")
|
|
358
|
+
return
|
|
359
|
+
|
|
360
|
+
table = Table(box=box.SIMPLE_HEAD, show_edge=False, pad_edge=False)
|
|
361
|
+
table.add_column("Id")
|
|
362
|
+
table.add_column("Fecha")
|
|
363
|
+
table.add_column("Etiqueta")
|
|
364
|
+
table.add_column("Archivos")
|
|
365
|
+
for b in found:
|
|
366
|
+
files = ", ".join(e.name for e in b.entries)
|
|
367
|
+
table.add_row(b.id, b.created.replace("T", " "), b.label, files)
|
|
368
|
+
console.print(table)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
@app.command()
|
|
372
|
+
def restore(
|
|
373
|
+
backup_id: Annotated[
|
|
374
|
+
str | None, typer.Argument(help="Id del respaldo (por defecto, el más reciente).")
|
|
375
|
+
] = None,
|
|
376
|
+
dry_run: Annotated[
|
|
377
|
+
bool, typer.Option("--dry-run", help="Muestra qué haría sin modificar nada.")
|
|
378
|
+
] = False,
|
|
379
|
+
yes: Annotated[bool, typer.Option("--yes", "-y", help="No pedir confirmación.")] = False,
|
|
380
|
+
) -> None:
|
|
381
|
+
"""Restaura un respaldo (guarda antes el estado actual como 'pre-restore')."""
|
|
382
|
+
env = get_env()
|
|
383
|
+
root, targets = backup_root(env), managed_files(env)
|
|
384
|
+
|
|
385
|
+
try:
|
|
386
|
+
plan = restore_backup(root, targets, backup_id, dry_run=True)
|
|
387
|
+
console.print(f"Respaldo: [bold]{plan.backup.id}[/bold]", highlight=False)
|
|
388
|
+
for action in plan.actions:
|
|
389
|
+
verb = "sobrescribe" if action.overwrites else "crea"
|
|
390
|
+
console.print(f" {verb} {action.destination}", highlight=False)
|
|
391
|
+
for name in plan.skipped:
|
|
392
|
+
console.print(f" [yellow]omitido:[/yellow] {name}", highlight=False)
|
|
393
|
+
|
|
394
|
+
if dry_run:
|
|
395
|
+
console.print("\n[dim]--dry-run: no se modificó nada.[/dim]")
|
|
396
|
+
return
|
|
397
|
+
if not plan.actions:
|
|
398
|
+
console.print("Nada que restaurar.")
|
|
399
|
+
return
|
|
400
|
+
if not yes and not typer.confirm("\n¿Continuar?"):
|
|
401
|
+
raise typer.Exit(1)
|
|
402
|
+
|
|
403
|
+
report = restore_backup(root, targets, plan.backup.id)
|
|
404
|
+
except BackupError as exc:
|
|
405
|
+
err_console.print(f"[red]{exc}[/red]")
|
|
406
|
+
raise typer.Exit(1) from exc
|
|
407
|
+
|
|
408
|
+
console.print("[green]Restauración completada.[/green]")
|
|
409
|
+
if report.safety_backup:
|
|
410
|
+
console.print(
|
|
411
|
+
f"Estado anterior guardado como {report.safety_backup.id}", highlight=False
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
if __name__ == "__main__":
|
|
416
|
+
app()
|