zerochat 10.5.0__tar.gz → 10.6.0__tar.gz
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.
- {zerochat-10.5.0/zerochat.egg-info → zerochat-10.6.0}/PKG-INFO +1 -1
- {zerochat-10.5.0 → zerochat-10.6.0}/pyproject.toml +1 -1
- {zerochat-10.5.0 → zerochat-10.6.0/zerochat.egg-info}/PKG-INFO +1 -1
- {zerochat-10.5.0 → zerochat-10.6.0}/zerochat.py +751 -251
- {zerochat-10.5.0 → zerochat-10.6.0}/LICENSE +0 -0
- {zerochat-10.5.0 → zerochat-10.6.0}/README.md +0 -0
- {zerochat-10.5.0 → zerochat-10.6.0}/setup.cfg +0 -0
- {zerochat-10.5.0 → zerochat-10.6.0}/zerochat.egg-info/SOURCES.txt +0 -0
- {zerochat-10.5.0 → zerochat-10.6.0}/zerochat.egg-info/dependency_links.txt +0 -0
- {zerochat-10.5.0 → zerochat-10.6.0}/zerochat.egg-info/entry_points.txt +0 -0
- {zerochat-10.5.0 → zerochat-10.6.0}/zerochat.egg-info/top_level.txt +0 -0
|
@@ -24,6 +24,7 @@ import functools
|
|
|
24
24
|
import getpass
|
|
25
25
|
import hashlib
|
|
26
26
|
import hmac
|
|
27
|
+
import html
|
|
27
28
|
import importlib.metadata
|
|
28
29
|
import ipaddress
|
|
29
30
|
import json
|
|
@@ -53,7 +54,7 @@ import zlib
|
|
|
53
54
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
54
55
|
from pathlib import Path
|
|
55
56
|
|
|
56
|
-
SOURCE_BACKEND_VERSION = "10.
|
|
57
|
+
SOURCE_BACKEND_VERSION = "10.6.0"
|
|
57
58
|
|
|
58
59
|
def _read_source_version(filename: str) -> str | None:
|
|
59
60
|
"""Lee la versión de un archivo del repositorio cuando se ejecuta desde fuentes."""
|
|
@@ -1119,6 +1120,754 @@ def check_command(job_id: int, wait_seconds: int = 0, stop: bool = False) -> str
|
|
|
1119
1120
|
def job_details(job: CommandJob) -> dict:
|
|
1120
1121
|
"""Estado del comando para su tarjeta en la interfaz, con el final de su salida."""
|
|
1121
1122
|
return {**job.summary(), "tail": job.tail_text()}
|
|
1123
|
+
# Visores gráficos que `git difftool` ya sabe lanzar, en orden de preferencia, con el ejecutable que los delata.
|
|
1124
|
+
GUI_DIFF_TOOLS = {"vscode": "code", "meld": "meld", "kdiff3": "kdiff3", "kompare": "kompare", "gvimdiff": "gvim"}
|
|
1125
|
+
# Respaldo cuando no hay ninguno: visor web que se instala en el entorno aislado de ZeroChat.
|
|
1126
|
+
WEBDIFF_REQUIREMENT = "webdiff==1.4.0"
|
|
1127
|
+
WEBDIFF_INSTALL_TIMEOUT_SECONDS = 120
|
|
1128
|
+
DIFF_CONTEXT_LINES = 5
|
|
1129
|
+
|
|
1130
|
+
|
|
1131
|
+
def _venv_webdiff() -> Path:
|
|
1132
|
+
"""Ruta de webdiff dentro de ~/zerochat/.venv, junto al intérprete del entorno."""
|
|
1133
|
+
venv_python = get_venv_python(get_venv_dir())
|
|
1134
|
+
return venv_python.with_name("webdiff" + venv_python.suffix)
|
|
1135
|
+
|
|
1136
|
+
|
|
1137
|
+
def _find_webdiff() -> str:
|
|
1138
|
+
"""webdiff del entorno de ZeroChat o, si no, del PATH; '' si no hay ninguno."""
|
|
1139
|
+
venv_webdiff = _venv_webdiff()
|
|
1140
|
+
if venv_webdiff.exists():
|
|
1141
|
+
return str(venv_webdiff)
|
|
1142
|
+
return shutil.which("webdiff") or ""
|
|
1143
|
+
|
|
1144
|
+
|
|
1145
|
+
def _diff_tool_settings(tool: str, webdiff_bin: str) -> list:
|
|
1146
|
+
"""Pares (clave, valor) de git config que deja `tool` como visor gráfico; webdiff no es un visor integrado de git."""
|
|
1147
|
+
settings = [("diff.guitool", tool)]
|
|
1148
|
+
if tool == "webdiff":
|
|
1149
|
+
settings.insert(0, ("difftool.webdiff.cmd", f'"{webdiff_bin}" "$LOCAL" "$REMOTE"'))
|
|
1150
|
+
return settings
|
|
1151
|
+
|
|
1152
|
+
|
|
1153
|
+
def detect_gui_diff_tool() -> dict:
|
|
1154
|
+
"""Visor que proponer cuando Git no tiene ninguno: el primero instalado o, si no hay, webdiff.
|
|
1155
|
+
|
|
1156
|
+
Incluye las órdenes exactas que aplicará configure_gui_diff_tool, para mostrarlas antes de confirmar.
|
|
1157
|
+
"""
|
|
1158
|
+
tool = next((name for name, binary in GUI_DIFF_TOOLS.items() if shutil.which(binary)), "webdiff")
|
|
1159
|
+
webdiff_bin = _find_webdiff()
|
|
1160
|
+
return {
|
|
1161
|
+
"tool": tool,
|
|
1162
|
+
"install": tool == "webdiff" and not webdiff_bin,
|
|
1163
|
+
"commands": [
|
|
1164
|
+
shlex.join(["git", "config", "--global", key, value])
|
|
1165
|
+
for key, value in _diff_tool_settings(tool, webdiff_bin or str(_venv_webdiff()))
|
|
1166
|
+
],
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
|
|
1170
|
+
def _install_webdiff() -> str:
|
|
1171
|
+
"""Instala webdiff en ~/zerochat/.venv y devuelve la ruta del ejecutable."""
|
|
1172
|
+
ensure_virtual_environment()
|
|
1173
|
+
venv_python = get_venv_python(get_venv_dir())
|
|
1174
|
+
if not venv_python.exists():
|
|
1175
|
+
raise RuntimeError(f"No se pudo preparar el entorno virtual de ZeroChat: falta {venv_python}")
|
|
1176
|
+
res = subprocess.run(
|
|
1177
|
+
[str(venv_python), "-m", "pip", "install", WEBDIFF_REQUIREMENT],
|
|
1178
|
+
capture_output=True,
|
|
1179
|
+
text=True,
|
|
1180
|
+
timeout=WEBDIFF_INSTALL_TIMEOUT_SECONDS,
|
|
1181
|
+
check=False
|
|
1182
|
+
)
|
|
1183
|
+
if res.returncode != 0:
|
|
1184
|
+
raise RuntimeError(f"Error instalando webdiff: {(res.stderr or res.stdout).strip()[-500:]}")
|
|
1185
|
+
webdiff = _venv_webdiff()
|
|
1186
|
+
if not webdiff.exists():
|
|
1187
|
+
raise RuntimeError(f"webdiff se instaló pero no aparece en {webdiff}")
|
|
1188
|
+
return str(webdiff)
|
|
1189
|
+
|
|
1190
|
+
|
|
1191
|
+
def configure_gui_diff_tool(tool) -> dict:
|
|
1192
|
+
"""Deja `tool` como visor gráfico global de Git, instalando antes webdiff si es el elegido y falta."""
|
|
1193
|
+
if not isinstance(tool, str) or (tool != "webdiff" and tool not in GUI_DIFF_TOOLS):
|
|
1194
|
+
raise ValueError(f"Visor de diffs '{tool}' no reconocido.")
|
|
1195
|
+
git_bin = shutil.which("git")
|
|
1196
|
+
if not git_bin:
|
|
1197
|
+
raise RuntimeError("Git no está instalado o no se encuentra en el PATH del sistema.")
|
|
1198
|
+
|
|
1199
|
+
webdiff_bin = ""
|
|
1200
|
+
if tool == "webdiff":
|
|
1201
|
+
webdiff_bin = _find_webdiff() or _install_webdiff()
|
|
1202
|
+
elif not shutil.which(GUI_DIFF_TOOLS[tool]):
|
|
1203
|
+
raise ValueError(f"'{GUI_DIFF_TOOLS[tool]}' no está en el PATH del sistema.")
|
|
1204
|
+
|
|
1205
|
+
for key, value in _diff_tool_settings(tool, webdiff_bin):
|
|
1206
|
+
subprocess.run([git_bin, "config", "--global", key, value], capture_output=True, timeout=5, check=True)
|
|
1207
|
+
return {"tool": tool}
|
|
1208
|
+
|
|
1209
|
+
|
|
1210
|
+
def _configured_gui_diff_tool(git_bin: str, repo_root: Path) -> str:
|
|
1211
|
+
"""Herramienta gráfica que usaría `git difftool --gui`, o '' si no hay ninguna configurada."""
|
|
1212
|
+
for key in ("diff.guitool", "merge.guitool"):
|
|
1213
|
+
res = subprocess.run(
|
|
1214
|
+
[git_bin, "config", "--get", key],
|
|
1215
|
+
cwd=str(repo_root),
|
|
1216
|
+
capture_output=True,
|
|
1217
|
+
text=True,
|
|
1218
|
+
timeout=5,
|
|
1219
|
+
check=False
|
|
1220
|
+
)
|
|
1221
|
+
if res.returncode == 0 and res.stdout.strip():
|
|
1222
|
+
return res.stdout.strip()
|
|
1223
|
+
return ""
|
|
1224
|
+
|
|
1225
|
+
|
|
1226
|
+
def _open_gui_file_diff(path: str, commit_fallback: bool = False) -> dict:
|
|
1227
|
+
"""Abre un visor externo de diffs (git difftool) en una ventana del sistema operativo."""
|
|
1228
|
+
if not isinstance(path, str) or not path.strip():
|
|
1229
|
+
raise ValueError("La ruta del archivo está vacía.")
|
|
1230
|
+
if len(path) > MAX_PATH_LENGTH:
|
|
1231
|
+
raise ValueError("La ruta del archivo excede el tamaño máximo permitido.")
|
|
1232
|
+
|
|
1233
|
+
target = Path(path.strip()).expanduser().resolve()
|
|
1234
|
+
if not target.exists():
|
|
1235
|
+
raise ValueError(f"El archivo '{path}' no existe.")
|
|
1236
|
+
if not target.is_file():
|
|
1237
|
+
raise ValueError(f"'{path}' no es un archivo regular.")
|
|
1238
|
+
|
|
1239
|
+
git_bin = shutil.which("git")
|
|
1240
|
+
if not git_bin:
|
|
1241
|
+
raise RuntimeError("Git no está instalado o no se encuentra en el PATH del sistema.")
|
|
1242
|
+
|
|
1243
|
+
try:
|
|
1244
|
+
res = subprocess.run(
|
|
1245
|
+
[git_bin, "rev-parse", "--show-toplevel"],
|
|
1246
|
+
cwd=str(target.parent),
|
|
1247
|
+
capture_output=True,
|
|
1248
|
+
text=True,
|
|
1249
|
+
timeout=5,
|
|
1250
|
+
check=False
|
|
1251
|
+
)
|
|
1252
|
+
except Exception as err:
|
|
1253
|
+
raise RuntimeError(f"Error comprobando repositorio Git: {err}")
|
|
1254
|
+
|
|
1255
|
+
if res.returncode != 0:
|
|
1256
|
+
raise ValueError(f"El archivo '{target.name}' no pertenece a ningún repositorio Git.")
|
|
1257
|
+
|
|
1258
|
+
repo_root = Path(res.stdout.strip()).resolve()
|
|
1259
|
+
if not _configured_gui_diff_tool(git_bin, repo_root):
|
|
1260
|
+
return {"success": False, "setup": detect_gui_diff_tool()}
|
|
1261
|
+
|
|
1262
|
+
has_head = subprocess.run(
|
|
1263
|
+
[git_bin, "rev-parse", "--verify", "HEAD"],
|
|
1264
|
+
cwd=str(repo_root),
|
|
1265
|
+
stdout=subprocess.DEVNULL,
|
|
1266
|
+
stderr=subprocess.DEVNULL,
|
|
1267
|
+
timeout=5,
|
|
1268
|
+
check=False
|
|
1269
|
+
).returncode == 0
|
|
1270
|
+
|
|
1271
|
+
in_head = False
|
|
1272
|
+
has_working_tree_diff = True
|
|
1273
|
+
if has_head:
|
|
1274
|
+
try:
|
|
1275
|
+
rel_path = target.relative_to(repo_root).as_posix()
|
|
1276
|
+
in_head = subprocess.run(
|
|
1277
|
+
[git_bin, "cat-file", "-e", f"HEAD:{rel_path}"],
|
|
1278
|
+
cwd=str(repo_root),
|
|
1279
|
+
stdout=subprocess.DEVNULL,
|
|
1280
|
+
stderr=subprocess.DEVNULL,
|
|
1281
|
+
timeout=5,
|
|
1282
|
+
check=False
|
|
1283
|
+
).returncode == 0
|
|
1284
|
+
if in_head:
|
|
1285
|
+
diff_check = subprocess.run(
|
|
1286
|
+
[git_bin, "diff", "--quiet", "HEAD", "--", str(target)],
|
|
1287
|
+
cwd=str(repo_root),
|
|
1288
|
+
timeout=5,
|
|
1289
|
+
check=False
|
|
1290
|
+
)
|
|
1291
|
+
has_working_tree_diff = (diff_check.returncode != 0)
|
|
1292
|
+
except ValueError:
|
|
1293
|
+
in_head = False
|
|
1294
|
+
|
|
1295
|
+
cmd = [git_bin, "difftool", "--no-prompt", "--gui"]
|
|
1296
|
+
|
|
1297
|
+
mode = "working_tree"
|
|
1298
|
+
last_commit = ""
|
|
1299
|
+
if has_working_tree_diff:
|
|
1300
|
+
if in_head:
|
|
1301
|
+
cmd.extend(["HEAD", "--", str(target)])
|
|
1302
|
+
else:
|
|
1303
|
+
cmd.extend(["--no-index", "--", os.devnull, str(target)])
|
|
1304
|
+
else:
|
|
1305
|
+
rel_path = target.relative_to(repo_root).as_posix()
|
|
1306
|
+
log_res = subprocess.run(
|
|
1307
|
+
[git_bin, "log", "-n", "1", "--format=%H", "--", rel_path],
|
|
1308
|
+
cwd=str(repo_root),
|
|
1309
|
+
capture_output=True,
|
|
1310
|
+
text=True,
|
|
1311
|
+
timeout=5,
|
|
1312
|
+
check=False
|
|
1313
|
+
)
|
|
1314
|
+
last_commit = log_res.stdout.strip() if log_res.returncode == 0 else ""
|
|
1315
|
+
if not commit_fallback or not last_commit:
|
|
1316
|
+
return {
|
|
1317
|
+
"success": True,
|
|
1318
|
+
"has_diff": False,
|
|
1319
|
+
"in_head": in_head,
|
|
1320
|
+
"has_commit_history": bool(last_commit),
|
|
1321
|
+
"last_commit": last_commit or None,
|
|
1322
|
+
"path": str(target)
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
mode = "commit"
|
|
1326
|
+
parent_check = subprocess.run(
|
|
1327
|
+
[git_bin, "rev-parse", "--verify", f"{last_commit}~1"],
|
|
1328
|
+
cwd=str(repo_root),
|
|
1329
|
+
stdout=subprocess.DEVNULL,
|
|
1330
|
+
stderr=subprocess.DEVNULL,
|
|
1331
|
+
timeout=5,
|
|
1332
|
+
check=False
|
|
1333
|
+
)
|
|
1334
|
+
if parent_check.returncode == 0:
|
|
1335
|
+
cmd.extend([f"{last_commit}~1", last_commit, "--", str(target)])
|
|
1336
|
+
else:
|
|
1337
|
+
cmd.extend(["4b825dc642cb6eb9a060e54bf8d69288fbee4904", last_commit, "--", str(target)])
|
|
1338
|
+
|
|
1339
|
+
popen_kwargs = {
|
|
1340
|
+
"cwd": str(repo_root),
|
|
1341
|
+
"stdin": subprocess.DEVNULL,
|
|
1342
|
+
"stdout": subprocess.DEVNULL,
|
|
1343
|
+
"stderr": subprocess.DEVNULL,
|
|
1344
|
+
}
|
|
1345
|
+
if os.name == "nt":
|
|
1346
|
+
popen_kwargs["creationflags"] = (
|
|
1347
|
+
getattr(subprocess, "DETACHED_PROCESS", 0) |
|
|
1348
|
+
getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
|
|
1349
|
+
)
|
|
1350
|
+
else:
|
|
1351
|
+
popen_kwargs["start_new_session"] = True
|
|
1352
|
+
|
|
1353
|
+
proc = subprocess.Popen(cmd, **popen_kwargs)
|
|
1354
|
+
return {
|
|
1355
|
+
"success": True,
|
|
1356
|
+
"has_diff": True,
|
|
1357
|
+
"mode": mode,
|
|
1358
|
+
"pid": proc.pid,
|
|
1359
|
+
"path": str(target),
|
|
1360
|
+
"in_head": in_head,
|
|
1361
|
+
"commit": last_commit or None
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
|
|
1365
|
+
def render_diff_html(
|
|
1366
|
+
diff_text: str,
|
|
1367
|
+
filename: str,
|
|
1368
|
+
rel_path: str = "",
|
|
1369
|
+
mode: str = "working_tree",
|
|
1370
|
+
commit: str | None = None,
|
|
1371
|
+
full_file_bytes: bytes | None = None
|
|
1372
|
+
) -> str:
|
|
1373
|
+
"""Genera una página HTML autocontenida y visualmente limpia con el diff para mostrar en una pestaña nueva."""
|
|
1374
|
+
diff_lines = diff_text.splitlines()
|
|
1375
|
+
rows = []
|
|
1376
|
+
old_num = 0
|
|
1377
|
+
new_num = 0
|
|
1378
|
+
in_hunk = False
|
|
1379
|
+
additions = 0
|
|
1380
|
+
deletions = 0
|
|
1381
|
+
|
|
1382
|
+
hunk_re = re.compile(r"^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@(.*)$")
|
|
1383
|
+
|
|
1384
|
+
for line in diff_lines:
|
|
1385
|
+
hunk_match = hunk_re.match(line)
|
|
1386
|
+
if hunk_match:
|
|
1387
|
+
old_num = int(hunk_match.group(1))
|
|
1388
|
+
new_num = int(hunk_match.group(2))
|
|
1389
|
+
in_hunk = True
|
|
1390
|
+
rows.append({
|
|
1391
|
+
"type": "hunk",
|
|
1392
|
+
"old_num": "",
|
|
1393
|
+
"new_num": "",
|
|
1394
|
+
"sign": "@",
|
|
1395
|
+
"text": line,
|
|
1396
|
+
})
|
|
1397
|
+
continue
|
|
1398
|
+
|
|
1399
|
+
if not in_hunk:
|
|
1400
|
+
rows.append({
|
|
1401
|
+
"type": "meta",
|
|
1402
|
+
"old_num": "",
|
|
1403
|
+
"new_num": "",
|
|
1404
|
+
"sign": " ",
|
|
1405
|
+
"text": line,
|
|
1406
|
+
})
|
|
1407
|
+
continue
|
|
1408
|
+
|
|
1409
|
+
if line.startswith("+"):
|
|
1410
|
+
additions += 1
|
|
1411
|
+
rows.append({
|
|
1412
|
+
"type": "add",
|
|
1413
|
+
"old_num": "",
|
|
1414
|
+
"new_num": str(new_num),
|
|
1415
|
+
"sign": "+",
|
|
1416
|
+
"text": line[1:],
|
|
1417
|
+
})
|
|
1418
|
+
new_num += 1
|
|
1419
|
+
elif line.startswith("-"):
|
|
1420
|
+
deletions += 1
|
|
1421
|
+
rows.append({
|
|
1422
|
+
"type": "del",
|
|
1423
|
+
"old_num": str(old_num),
|
|
1424
|
+
"new_num": "",
|
|
1425
|
+
"sign": "-",
|
|
1426
|
+
"text": line[1:],
|
|
1427
|
+
})
|
|
1428
|
+
old_num += 1
|
|
1429
|
+
elif line.startswith(" "):
|
|
1430
|
+
rows.append({
|
|
1431
|
+
"type": "ctx",
|
|
1432
|
+
"old_num": str(old_num),
|
|
1433
|
+
"new_num": str(new_num),
|
|
1434
|
+
"sign": " ",
|
|
1435
|
+
"text": line[1:],
|
|
1436
|
+
})
|
|
1437
|
+
old_num += 1
|
|
1438
|
+
new_num += 1
|
|
1439
|
+
else:
|
|
1440
|
+
rows.append({
|
|
1441
|
+
"type": "meta",
|
|
1442
|
+
"old_num": "",
|
|
1443
|
+
"new_num": "",
|
|
1444
|
+
"sign": " ",
|
|
1445
|
+
"text": line,
|
|
1446
|
+
})
|
|
1447
|
+
|
|
1448
|
+
table_rows = []
|
|
1449
|
+
for row in rows:
|
|
1450
|
+
r_type = row["type"]
|
|
1451
|
+
old_n = row["old_num"]
|
|
1452
|
+
new_n = row["new_num"]
|
|
1453
|
+
sign = html.escape(row["sign"])
|
|
1454
|
+
txt = html.escape(row["text"])
|
|
1455
|
+
table_rows.append(
|
|
1456
|
+
f'<tr class="row-{r_type}">'
|
|
1457
|
+
f'<td class="line-num">{old_n}</td>'
|
|
1458
|
+
f'<td class="line-num">{new_n}</td>'
|
|
1459
|
+
f'<td class="line-sign">{sign}</td>'
|
|
1460
|
+
f'<td class="line-code">{txt}</td>'
|
|
1461
|
+
f'</tr>'
|
|
1462
|
+
)
|
|
1463
|
+
|
|
1464
|
+
mode_label = f"Commit {commit[:7]}" if (mode == "commit" and commit) else "Working Tree vs HEAD"
|
|
1465
|
+
display_title = filename or "diff"
|
|
1466
|
+
display_path = rel_path or filename or ""
|
|
1467
|
+
|
|
1468
|
+
btn_html = ""
|
|
1469
|
+
script_html = ""
|
|
1470
|
+
if full_file_bytes is not None:
|
|
1471
|
+
b64_content = base64.b64encode(full_file_bytes).decode("ascii")
|
|
1472
|
+
btn_html = (
|
|
1473
|
+
'<button type="button" class="btn-full-file" onclick="openFullFile()">'
|
|
1474
|
+
'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">'
|
|
1475
|
+
'<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>'
|
|
1476
|
+
'<polyline points="14 2 14 8 20 8"></polyline>'
|
|
1477
|
+
'<line x1="16" y1="13" x2="8" y2="13"></line>'
|
|
1478
|
+
'<line x1="16" y1="17" x2="8" y2="17"></line>'
|
|
1479
|
+
'<polyline points="10 9 9 9 8 9"></polyline>'
|
|
1480
|
+
'</svg>'
|
|
1481
|
+
'<span>Abrir fichero completo</span>'
|
|
1482
|
+
'</button>'
|
|
1483
|
+
)
|
|
1484
|
+
script_html = f""" <script>
|
|
1485
|
+
function openFullFile() {{
|
|
1486
|
+
const b64 = "{b64_content}";
|
|
1487
|
+
const binary = atob(b64);
|
|
1488
|
+
const bytes = new Uint8Array(binary.length);
|
|
1489
|
+
for (let i = 0; i < binary.length; i++) {{
|
|
1490
|
+
bytes[i] = binary.charCodeAt(i);
|
|
1491
|
+
}}
|
|
1492
|
+
const blob = new Blob([bytes], {{ type: "text/plain;charset=utf-8" }});
|
|
1493
|
+
window.open(URL.createObjectURL(blob), "_blank");
|
|
1494
|
+
}}
|
|
1495
|
+
</script>"""
|
|
1496
|
+
|
|
1497
|
+
return f"""<!DOCTYPE html>
|
|
1498
|
+
<html lang="es">
|
|
1499
|
+
<head>
|
|
1500
|
+
<meta charset="utf-8">
|
|
1501
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1502
|
+
<title>Diff: {html.escape(display_title)}</title>
|
|
1503
|
+
<style>
|
|
1504
|
+
:root {{
|
|
1505
|
+
--bg: #ffffff;
|
|
1506
|
+
--fg: #1f2328;
|
|
1507
|
+
--header-bg: #f6f8fa;
|
|
1508
|
+
--border: #d0d7de;
|
|
1509
|
+
--hunk-bg: #ddf4ff;
|
|
1510
|
+
--hunk-fg: #0969da;
|
|
1511
|
+
--add-bg: #dafbe1;
|
|
1512
|
+
--add-fg: #1a7f37;
|
|
1513
|
+
--add-num-bg: #aceebb;
|
|
1514
|
+
--del-bg: #ffebe9;
|
|
1515
|
+
--del-fg: #cf222e;
|
|
1516
|
+
--del-num-bg: #ffd7d5;
|
|
1517
|
+
--meta-fg: #656d76;
|
|
1518
|
+
--linenum-fg: #8c959f;
|
|
1519
|
+
--linenum-bg: #f6f8fa;
|
|
1520
|
+
--font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
|
|
1521
|
+
}}
|
|
1522
|
+
@media (prefers-color-scheme: dark) {{
|
|
1523
|
+
:root {{
|
|
1524
|
+
--bg: #0d1117;
|
|
1525
|
+
--fg: #e6edf3;
|
|
1526
|
+
--header-bg: #161b22;
|
|
1527
|
+
--border: #30363d;
|
|
1528
|
+
--hunk-bg: rgba(56, 139, 253, 0.15);
|
|
1529
|
+
--hunk-fg: #58a6ff;
|
|
1530
|
+
--add-bg: rgba(46, 160, 67, 0.15);
|
|
1531
|
+
--add-fg: #3fb950;
|
|
1532
|
+
--add-num-bg: rgba(46, 160, 67, 0.25);
|
|
1533
|
+
--del-bg: rgba(248, 81, 73, 0.15);
|
|
1534
|
+
--del-fg: #f85149;
|
|
1535
|
+
--del-num-bg: rgba(248, 81, 73, 0.25);
|
|
1536
|
+
--meta-fg: #8b949e;
|
|
1537
|
+
--linenum-fg: #6e7681;
|
|
1538
|
+
--linenum-bg: #161b22;
|
|
1539
|
+
}}
|
|
1540
|
+
}}
|
|
1541
|
+
* {{ box-sizing: border-box; }}
|
|
1542
|
+
body {{
|
|
1543
|
+
margin: 0;
|
|
1544
|
+
padding: 16px;
|
|
1545
|
+
background: var(--bg);
|
|
1546
|
+
color: var(--fg);
|
|
1547
|
+
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
|
1548
|
+
line-height: 1.5;
|
|
1549
|
+
}}
|
|
1550
|
+
.diff-container {{
|
|
1551
|
+
max-width: 1400px;
|
|
1552
|
+
margin: 0 auto;
|
|
1553
|
+
border: 1px solid var(--border);
|
|
1554
|
+
border-radius: 6px;
|
|
1555
|
+
overflow: hidden;
|
|
1556
|
+
background: var(--bg);
|
|
1557
|
+
}}
|
|
1558
|
+
.diff-header {{
|
|
1559
|
+
padding: 12px 16px;
|
|
1560
|
+
background: var(--header-bg);
|
|
1561
|
+
border-bottom: 1px solid var(--border);
|
|
1562
|
+
display: flex;
|
|
1563
|
+
justify-content: space-between;
|
|
1564
|
+
align-items: center;
|
|
1565
|
+
flex-wrap: wrap;
|
|
1566
|
+
gap: 12px;
|
|
1567
|
+
}}
|
|
1568
|
+
.diff-title-group {{
|
|
1569
|
+
display: flex;
|
|
1570
|
+
align-items: baseline;
|
|
1571
|
+
gap: 10px;
|
|
1572
|
+
flex-wrap: wrap;
|
|
1573
|
+
}}
|
|
1574
|
+
.diff-title {{
|
|
1575
|
+
margin: 0;
|
|
1576
|
+
font-size: 16px;
|
|
1577
|
+
font-weight: 600;
|
|
1578
|
+
font-family: var(--font-mono);
|
|
1579
|
+
}}
|
|
1580
|
+
.diff-path {{
|
|
1581
|
+
font-size: 13px;
|
|
1582
|
+
color: var(--meta-fg);
|
|
1583
|
+
font-family: var(--font-mono);
|
|
1584
|
+
}}
|
|
1585
|
+
.diff-meta {{
|
|
1586
|
+
display: flex;
|
|
1587
|
+
gap: 10px;
|
|
1588
|
+
align-items: center;
|
|
1589
|
+
}}
|
|
1590
|
+
.diff-badge {{
|
|
1591
|
+
font-size: 12px;
|
|
1592
|
+
padding: 2px 8px;
|
|
1593
|
+
border-radius: 12px;
|
|
1594
|
+
border: 1px solid var(--border);
|
|
1595
|
+
background: var(--bg);
|
|
1596
|
+
color: var(--meta-fg);
|
|
1597
|
+
font-family: var(--font-mono);
|
|
1598
|
+
}}
|
|
1599
|
+
.diff-stat {{
|
|
1600
|
+
font-size: 13px;
|
|
1601
|
+
font-weight: 600;
|
|
1602
|
+
font-family: var(--font-mono);
|
|
1603
|
+
}}
|
|
1604
|
+
.stat-add {{ color: var(--add-fg); }}
|
|
1605
|
+
.stat-del {{ color: var(--del-fg); }}
|
|
1606
|
+
.btn-full-file {{
|
|
1607
|
+
display: inline-flex;
|
|
1608
|
+
align-items: center;
|
|
1609
|
+
gap: 6px;
|
|
1610
|
+
padding: 3px 10px;
|
|
1611
|
+
font-size: 12px;
|
|
1612
|
+
font-weight: 500;
|
|
1613
|
+
color: var(--fg);
|
|
1614
|
+
background: var(--header-bg);
|
|
1615
|
+
border: 1px solid var(--border);
|
|
1616
|
+
border-radius: 6px;
|
|
1617
|
+
cursor: pointer;
|
|
1618
|
+
font-family: inherit;
|
|
1619
|
+
transition: background 0.15s ease, border-color 0.15s ease;
|
|
1620
|
+
}}
|
|
1621
|
+
.btn-full-file:hover {{
|
|
1622
|
+
background: var(--border);
|
|
1623
|
+
}}
|
|
1624
|
+
.diff-table {{
|
|
1625
|
+
width: 100%;
|
|
1626
|
+
border-collapse: collapse;
|
|
1627
|
+
font-family: var(--font-mono);
|
|
1628
|
+
font-size: 12px;
|
|
1629
|
+
line-height: 1.45;
|
|
1630
|
+
}}
|
|
1631
|
+
.diff-table td {{
|
|
1632
|
+
padding: 1px 8px;
|
|
1633
|
+
vertical-align: top;
|
|
1634
|
+
}}
|
|
1635
|
+
.line-num {{
|
|
1636
|
+
width: 1%;
|
|
1637
|
+
min-width: 44px;
|
|
1638
|
+
text-align: right;
|
|
1639
|
+
color: var(--linenum-fg);
|
|
1640
|
+
background: var(--linenum-bg);
|
|
1641
|
+
user-select: none;
|
|
1642
|
+
border-right: 1px solid var(--border);
|
|
1643
|
+
}}
|
|
1644
|
+
.line-sign {{
|
|
1645
|
+
width: 1%;
|
|
1646
|
+
min-width: 20px;
|
|
1647
|
+
text-align: center;
|
|
1648
|
+
user-select: none;
|
|
1649
|
+
font-weight: bold;
|
|
1650
|
+
}}
|
|
1651
|
+
.line-code {{
|
|
1652
|
+
white-space: pre-wrap;
|
|
1653
|
+
word-break: break-all;
|
|
1654
|
+
}}
|
|
1655
|
+
.row-add {{ background: var(--add-bg); color: var(--add-fg); }}
|
|
1656
|
+
.row-add .line-num {{ background: var(--add-num-bg); }}
|
|
1657
|
+
.row-del {{ background: var(--del-bg); color: var(--del-fg); }}
|
|
1658
|
+
.row-del .line-num {{ background: var(--del-num-bg); }}
|
|
1659
|
+
.row-hunk {{
|
|
1660
|
+
background: var(--hunk-bg);
|
|
1661
|
+
color: var(--hunk-fg);
|
|
1662
|
+
border-top: 1px solid var(--border);
|
|
1663
|
+
border-bottom: 1px solid var(--border);
|
|
1664
|
+
}}
|
|
1665
|
+
.row-meta {{ color: var(--meta-fg); background: var(--header-bg); }}
|
|
1666
|
+
</style>
|
|
1667
|
+
</head>
|
|
1668
|
+
<body>
|
|
1669
|
+
<div class="diff-container">
|
|
1670
|
+
<header class="diff-header">
|
|
1671
|
+
<div class="diff-title-group">
|
|
1672
|
+
<h1 class="diff-title">{html.escape(display_title)}</h1>
|
|
1673
|
+
{f'<span class="diff-path">{html.escape(display_path)}</span>' if display_path != display_title else ''}
|
|
1674
|
+
</div>
|
|
1675
|
+
<div class="diff-meta">
|
|
1676
|
+
<span class="diff-badge">{html.escape(mode_label)}</span>
|
|
1677
|
+
<span class="diff-stat stat-add">+{additions}</span>
|
|
1678
|
+
<span class="diff-stat stat-del">-{deletions}</span>
|
|
1679
|
+
{btn_html}
|
|
1680
|
+
</div>
|
|
1681
|
+
</header>
|
|
1682
|
+
<table class="diff-table">
|
|
1683
|
+
<tbody>
|
|
1684
|
+
{"".join(table_rows)}
|
|
1685
|
+
</tbody>
|
|
1686
|
+
</table>
|
|
1687
|
+
</div>
|
|
1688
|
+
{script_html}
|
|
1689
|
+
</body>
|
|
1690
|
+
</html>"""
|
|
1691
|
+
|
|
1692
|
+
|
|
1693
|
+
def generate_file_diff(path: str, commit_fallback: bool = False, context_lines: int = DIFF_CONTEXT_LINES) -> dict:
|
|
1694
|
+
"""Calcula y devuelve el diff de un archivo frente a Git HEAD o su último commit, incluyendo HTML."""
|
|
1695
|
+
if not isinstance(path, str) or not path.strip():
|
|
1696
|
+
raise ValueError("La ruta del archivo está vacía.")
|
|
1697
|
+
if len(path) > MAX_PATH_LENGTH:
|
|
1698
|
+
raise ValueError("La ruta del archivo excede el tamaño máximo permitido.")
|
|
1699
|
+
|
|
1700
|
+
target = Path(path.strip()).expanduser().resolve()
|
|
1701
|
+
if not target.exists():
|
|
1702
|
+
raise ValueError(f"El archivo '{path}' no existe.")
|
|
1703
|
+
if not target.is_file():
|
|
1704
|
+
raise ValueError(f"'{path}' no es un archivo regular.")
|
|
1705
|
+
|
|
1706
|
+
git_bin = shutil.which("git")
|
|
1707
|
+
if not git_bin:
|
|
1708
|
+
raise RuntimeError("Git no está instalado o no se encuentra en el PATH del sistema.")
|
|
1709
|
+
|
|
1710
|
+
try:
|
|
1711
|
+
res = subprocess.run(
|
|
1712
|
+
[git_bin, "rev-parse", "--show-toplevel"],
|
|
1713
|
+
cwd=str(target.parent),
|
|
1714
|
+
capture_output=True,
|
|
1715
|
+
text=True,
|
|
1716
|
+
timeout=5,
|
|
1717
|
+
check=False
|
|
1718
|
+
)
|
|
1719
|
+
except Exception as err:
|
|
1720
|
+
raise RuntimeError(f"Error comprobando repositorio Git: {err}")
|
|
1721
|
+
|
|
1722
|
+
if res.returncode != 0:
|
|
1723
|
+
raise ValueError(f"El archivo '{target.name}' no pertenece a ningún repositorio Git.")
|
|
1724
|
+
|
|
1725
|
+
repo_root = Path(res.stdout.strip()).resolve()
|
|
1726
|
+
has_head = subprocess.run(
|
|
1727
|
+
[git_bin, "rev-parse", "--verify", "HEAD"],
|
|
1728
|
+
cwd=str(repo_root),
|
|
1729
|
+
stdout=subprocess.DEVNULL,
|
|
1730
|
+
stderr=subprocess.DEVNULL,
|
|
1731
|
+
timeout=5,
|
|
1732
|
+
check=False
|
|
1733
|
+
).returncode == 0
|
|
1734
|
+
|
|
1735
|
+
in_head = False
|
|
1736
|
+
has_working_tree_diff = True
|
|
1737
|
+
rel_path = target.name
|
|
1738
|
+
try:
|
|
1739
|
+
rel_path = target.relative_to(repo_root).as_posix()
|
|
1740
|
+
except ValueError:
|
|
1741
|
+
pass
|
|
1742
|
+
|
|
1743
|
+
if has_head:
|
|
1744
|
+
try:
|
|
1745
|
+
in_head = subprocess.run(
|
|
1746
|
+
[git_bin, "cat-file", "-e", f"HEAD:{rel_path}"],
|
|
1747
|
+
cwd=str(repo_root),
|
|
1748
|
+
stdout=subprocess.DEVNULL,
|
|
1749
|
+
stderr=subprocess.DEVNULL,
|
|
1750
|
+
timeout=5,
|
|
1751
|
+
check=False
|
|
1752
|
+
).returncode == 0
|
|
1753
|
+
if in_head:
|
|
1754
|
+
diff_check = subprocess.run(
|
|
1755
|
+
[git_bin, "diff", "--quiet", "HEAD", "--", str(target)],
|
|
1756
|
+
cwd=str(repo_root),
|
|
1757
|
+
timeout=5,
|
|
1758
|
+
check=False
|
|
1759
|
+
)
|
|
1760
|
+
has_working_tree_diff = (diff_check.returncode != 0)
|
|
1761
|
+
except ValueError:
|
|
1762
|
+
in_head = False
|
|
1763
|
+
|
|
1764
|
+
mode = "working_tree"
|
|
1765
|
+
last_commit = ""
|
|
1766
|
+
diff_text = ""
|
|
1767
|
+
|
|
1768
|
+
if has_working_tree_diff:
|
|
1769
|
+
if in_head:
|
|
1770
|
+
cmd = [git_bin, "diff", f"-U{context_lines}", "HEAD", "--", str(target)]
|
|
1771
|
+
else:
|
|
1772
|
+
cmd = [git_bin, "diff", f"-U{context_lines}", "--no-index", "--", os.devnull, str(target)]
|
|
1773
|
+
diff_res = subprocess.run(cmd, cwd=str(repo_root), capture_output=True, text=True, timeout=10, check=False)
|
|
1774
|
+
diff_text = diff_res.stdout
|
|
1775
|
+
else:
|
|
1776
|
+
# No hay cambios pendientes en el árbol de trabajo. Comprobar historial del archivo.
|
|
1777
|
+
log_res = subprocess.run(
|
|
1778
|
+
[git_bin, "log", "-n", "1", "--format=%H", "--", rel_path],
|
|
1779
|
+
cwd=str(repo_root),
|
|
1780
|
+
capture_output=True,
|
|
1781
|
+
text=True,
|
|
1782
|
+
timeout=5,
|
|
1783
|
+
check=False
|
|
1784
|
+
)
|
|
1785
|
+
last_commit = log_res.stdout.strip() if log_res.returncode == 0 else ""
|
|
1786
|
+
if not commit_fallback or not last_commit:
|
|
1787
|
+
return {
|
|
1788
|
+
"success": True,
|
|
1789
|
+
"has_diff": False,
|
|
1790
|
+
"in_head": in_head,
|
|
1791
|
+
"has_commit_history": bool(last_commit),
|
|
1792
|
+
"last_commit": last_commit or None,
|
|
1793
|
+
"path": str(target)
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
mode = "commit"
|
|
1797
|
+
parent_check = subprocess.run(
|
|
1798
|
+
[git_bin, "rev-parse", "--verify", f"{last_commit}~1"],
|
|
1799
|
+
cwd=str(repo_root),
|
|
1800
|
+
stdout=subprocess.DEVNULL,
|
|
1801
|
+
stderr=subprocess.DEVNULL,
|
|
1802
|
+
timeout=5,
|
|
1803
|
+
check=False
|
|
1804
|
+
)
|
|
1805
|
+
if parent_check.returncode == 0:
|
|
1806
|
+
cmd = [git_bin, "diff", f"-U{context_lines}", f"{last_commit}~1", last_commit, "--", str(target)]
|
|
1807
|
+
else:
|
|
1808
|
+
cmd = [git_bin, "diff", f"-U{context_lines}", "4b825dc642cb6eb9a060e54bf8d69288fbee4904", last_commit, "--", str(target)]
|
|
1809
|
+
diff_res = subprocess.run(cmd, cwd=str(repo_root), capture_output=True, text=True, timeout=10, check=False)
|
|
1810
|
+
diff_text = diff_res.stdout
|
|
1811
|
+
|
|
1812
|
+
if not diff_text.strip():
|
|
1813
|
+
return {
|
|
1814
|
+
"success": True,
|
|
1815
|
+
"has_diff": False,
|
|
1816
|
+
"in_head": in_head,
|
|
1817
|
+
"has_commit_history": bool(last_commit),
|
|
1818
|
+
"last_commit": last_commit or None,
|
|
1819
|
+
"path": str(target)
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
full_file_bytes = None
|
|
1823
|
+
if mode == "commit" and last_commit:
|
|
1824
|
+
show_res = subprocess.run(
|
|
1825
|
+
[git_bin, "show", f"{last_commit}:{rel_path}"],
|
|
1826
|
+
cwd=str(repo_root),
|
|
1827
|
+
capture_output=True,
|
|
1828
|
+
timeout=5,
|
|
1829
|
+
check=False
|
|
1830
|
+
)
|
|
1831
|
+
if show_res.returncode == 0:
|
|
1832
|
+
full_file_bytes = show_res.stdout
|
|
1833
|
+
if full_file_bytes is None:
|
|
1834
|
+
try:
|
|
1835
|
+
if target.is_file() and target.stat().st_size <= 5_000_000:
|
|
1836
|
+
full_file_bytes = target.read_bytes()
|
|
1837
|
+
except (OSError, PermissionError):
|
|
1838
|
+
full_file_bytes = None
|
|
1839
|
+
|
|
1840
|
+
html_content = render_diff_html(
|
|
1841
|
+
diff_text=diff_text,
|
|
1842
|
+
filename=target.name,
|
|
1843
|
+
rel_path=rel_path,
|
|
1844
|
+
mode=mode,
|
|
1845
|
+
commit=last_commit or None,
|
|
1846
|
+
full_file_bytes=full_file_bytes
|
|
1847
|
+
)
|
|
1848
|
+
|
|
1849
|
+
return {
|
|
1850
|
+
"success": True,
|
|
1851
|
+
"has_diff": True,
|
|
1852
|
+
"mode": mode,
|
|
1853
|
+
"path": str(target),
|
|
1854
|
+
"in_head": in_head,
|
|
1855
|
+
"commit": last_commit or None,
|
|
1856
|
+
"diff": diff_text,
|
|
1857
|
+
"html": html_content
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
|
|
1861
|
+
def open_file_diff(path: str, commit_fallback: bool = False, gui: bool = False, context_lines: int = DIFF_CONTEXT_LINES) -> dict:
|
|
1862
|
+
"""Obtiene el diff de un archivo asociado a Git.
|
|
1863
|
+
|
|
1864
|
+
Por defecto genera el diff con el visor propio de ZeroChat (HTML y texto), apto para
|
|
1865
|
+
ejecución local y remota sin depender de visores gráficos instalados en el sistema operativo.
|
|
1866
|
+
Con `gui=True` lanza el visor gráfico externo configurado en Git (difftool).
|
|
1867
|
+
"""
|
|
1868
|
+
if gui:
|
|
1869
|
+
return _open_gui_file_diff(path, commit_fallback)
|
|
1870
|
+
return generate_file_diff(path, commit_fallback, context_lines=context_lines)
|
|
1122
1871
|
# ==============================================================================
|
|
1123
1872
|
# Generated from services/ by scripts/build-managed-services.mjs. Do not edit.
|
|
1124
1873
|
# ==============================================================================
|
|
@@ -1366,255 +2115,6 @@ def set_project_directory(path) -> dict:
|
|
|
1366
2115
|
return {"cwd": str(target), "previous_cwd": previous}
|
|
1367
2116
|
|
|
1368
2117
|
|
|
1369
|
-
# Visores gráficos que `git difftool` ya sabe lanzar, en orden de preferencia, con el ejecutable que los delata.
|
|
1370
|
-
GUI_DIFF_TOOLS = {"vscode": "code", "meld": "meld", "kdiff3": "kdiff3", "kompare": "kompare", "gvimdiff": "gvim"}
|
|
1371
|
-
# Respaldo cuando no hay ninguno: visor web que se instala en el entorno aislado de ZeroChat.
|
|
1372
|
-
WEBDIFF_REQUIREMENT = "webdiff==1.4.0"
|
|
1373
|
-
WEBDIFF_INSTALL_TIMEOUT_SECONDS = 120
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
def _venv_webdiff() -> Path:
|
|
1377
|
-
"""Ruta de webdiff dentro de ~/zerochat/.venv, junto al intérprete del entorno."""
|
|
1378
|
-
venv_python = get_venv_python(get_venv_dir())
|
|
1379
|
-
return venv_python.with_name("webdiff" + venv_python.suffix)
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
def _find_webdiff() -> str:
|
|
1383
|
-
"""webdiff del entorno de ZeroChat o, si no, del PATH; '' si no hay ninguno."""
|
|
1384
|
-
venv_webdiff = _venv_webdiff()
|
|
1385
|
-
if venv_webdiff.exists():
|
|
1386
|
-
return str(venv_webdiff)
|
|
1387
|
-
return shutil.which("webdiff") or ""
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
def _diff_tool_settings(tool: str, webdiff_bin: str) -> list:
|
|
1391
|
-
"""Pares (clave, valor) de git config que deja `tool` como visor gráfico; webdiff no es un visor integrado de git."""
|
|
1392
|
-
settings = [("diff.guitool", tool)]
|
|
1393
|
-
if tool == "webdiff":
|
|
1394
|
-
settings.insert(0, ("difftool.webdiff.cmd", f'"{webdiff_bin}" "$LOCAL" "$REMOTE"'))
|
|
1395
|
-
return settings
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
def detect_gui_diff_tool() -> dict:
|
|
1399
|
-
"""Visor que proponer cuando Git no tiene ninguno: el primero instalado o, si no hay, webdiff.
|
|
1400
|
-
|
|
1401
|
-
Incluye las órdenes exactas que aplicará configure_gui_diff_tool, para mostrarlas antes de confirmar.
|
|
1402
|
-
"""
|
|
1403
|
-
tool = next((name for name, binary in GUI_DIFF_TOOLS.items() if shutil.which(binary)), "webdiff")
|
|
1404
|
-
webdiff_bin = _find_webdiff()
|
|
1405
|
-
return {
|
|
1406
|
-
"tool": tool,
|
|
1407
|
-
"install": tool == "webdiff" and not webdiff_bin,
|
|
1408
|
-
"commands": [
|
|
1409
|
-
shlex.join(["git", "config", "--global", key, value])
|
|
1410
|
-
for key, value in _diff_tool_settings(tool, webdiff_bin or str(_venv_webdiff()))
|
|
1411
|
-
],
|
|
1412
|
-
}
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
def _install_webdiff() -> str:
|
|
1416
|
-
"""Instala webdiff en ~/zerochat/.venv y devuelve la ruta del ejecutable."""
|
|
1417
|
-
ensure_virtual_environment()
|
|
1418
|
-
venv_python = get_venv_python(get_venv_dir())
|
|
1419
|
-
if not venv_python.exists():
|
|
1420
|
-
raise RuntimeError(f"No se pudo preparar el entorno virtual de ZeroChat: falta {venv_python}")
|
|
1421
|
-
res = subprocess.run(
|
|
1422
|
-
[str(venv_python), "-m", "pip", "install", WEBDIFF_REQUIREMENT],
|
|
1423
|
-
capture_output=True,
|
|
1424
|
-
text=True,
|
|
1425
|
-
timeout=WEBDIFF_INSTALL_TIMEOUT_SECONDS,
|
|
1426
|
-
check=False
|
|
1427
|
-
)
|
|
1428
|
-
if res.returncode != 0:
|
|
1429
|
-
raise RuntimeError(f"Error instalando webdiff: {(res.stderr or res.stdout).strip()[-500:]}")
|
|
1430
|
-
webdiff = _venv_webdiff()
|
|
1431
|
-
if not webdiff.exists():
|
|
1432
|
-
raise RuntimeError(f"webdiff se instaló pero no aparece en {webdiff}")
|
|
1433
|
-
return str(webdiff)
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
def configure_gui_diff_tool(tool) -> dict:
|
|
1437
|
-
"""Deja `tool` como visor gráfico global de Git, instalando antes webdiff si es el elegido y falta."""
|
|
1438
|
-
if not isinstance(tool, str) or (tool != "webdiff" and tool not in GUI_DIFF_TOOLS):
|
|
1439
|
-
raise ValueError(f"Visor de diffs '{tool}' no reconocido.")
|
|
1440
|
-
git_bin = shutil.which("git")
|
|
1441
|
-
if not git_bin:
|
|
1442
|
-
raise RuntimeError("Git no está instalado o no se encuentra en el PATH del sistema.")
|
|
1443
|
-
|
|
1444
|
-
webdiff_bin = ""
|
|
1445
|
-
if tool == "webdiff":
|
|
1446
|
-
webdiff_bin = _find_webdiff() or _install_webdiff()
|
|
1447
|
-
elif not shutil.which(GUI_DIFF_TOOLS[tool]):
|
|
1448
|
-
raise ValueError(f"'{GUI_DIFF_TOOLS[tool]}' no está en el PATH del sistema.")
|
|
1449
|
-
|
|
1450
|
-
for key, value in _diff_tool_settings(tool, webdiff_bin):
|
|
1451
|
-
subprocess.run([git_bin, "config", "--global", key, value], capture_output=True, timeout=5, check=True)
|
|
1452
|
-
return {"tool": tool}
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
def _configured_gui_diff_tool(git_bin: str, repo_root: Path) -> str:
|
|
1456
|
-
"""Herramienta gráfica que usaría `git difftool --gui`, o '' si no hay ninguna configurada.
|
|
1457
|
-
|
|
1458
|
-
Sin diff.guitool ni merge.guitool, git recurre a diff.tool o adivina una, que puede ser de
|
|
1459
|
-
terminal (vimdiff): lanzada sin terminal quedaría invisible y colgada.
|
|
1460
|
-
"""
|
|
1461
|
-
for key in ("diff.guitool", "merge.guitool"):
|
|
1462
|
-
res = subprocess.run(
|
|
1463
|
-
[git_bin, "config", "--get", key],
|
|
1464
|
-
cwd=str(repo_root),
|
|
1465
|
-
capture_output=True,
|
|
1466
|
-
text=True,
|
|
1467
|
-
timeout=5,
|
|
1468
|
-
check=False
|
|
1469
|
-
)
|
|
1470
|
-
if res.returncode == 0 and res.stdout.strip():
|
|
1471
|
-
return res.stdout.strip()
|
|
1472
|
-
return ""
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
def open_file_diff(path: str, commit_fallback: bool = False) -> dict:
|
|
1476
|
-
"""Abre un visor externo de diffs (git difftool) para comparar el fichero actual frente a Git HEAD, su último commit o fichero vacío.
|
|
1477
|
-
|
|
1478
|
-
Sin visor gráfico configurado no lanza nada y devuelve en `setup` el que propone configurar.
|
|
1479
|
-
"""
|
|
1480
|
-
if not isinstance(path, str) or not path.strip():
|
|
1481
|
-
raise ValueError("La ruta del archivo está vacía.")
|
|
1482
|
-
if len(path) > MAX_PATH_LENGTH:
|
|
1483
|
-
raise ValueError("La ruta del archivo excede el tamaño máximo permitido.")
|
|
1484
|
-
|
|
1485
|
-
target = Path(path.strip()).expanduser().resolve()
|
|
1486
|
-
if not target.exists():
|
|
1487
|
-
raise ValueError(f"El archivo '{path}' no existe.")
|
|
1488
|
-
if not target.is_file():
|
|
1489
|
-
raise ValueError(f"'{path}' no es un archivo regular.")
|
|
1490
|
-
|
|
1491
|
-
git_bin = shutil.which("git")
|
|
1492
|
-
if not git_bin:
|
|
1493
|
-
raise RuntimeError("Git no está instalado o no se encuentra en el PATH del sistema.")
|
|
1494
|
-
|
|
1495
|
-
try:
|
|
1496
|
-
res = subprocess.run(
|
|
1497
|
-
[git_bin, "rev-parse", "--show-toplevel"],
|
|
1498
|
-
cwd=str(target.parent),
|
|
1499
|
-
capture_output=True,
|
|
1500
|
-
text=True,
|
|
1501
|
-
timeout=5,
|
|
1502
|
-
check=False
|
|
1503
|
-
)
|
|
1504
|
-
except Exception as err:
|
|
1505
|
-
raise RuntimeError(f"Error comprobando repositorio Git: {err}")
|
|
1506
|
-
|
|
1507
|
-
if res.returncode != 0:
|
|
1508
|
-
raise ValueError(f"El archivo '{target.name}' no pertenece a ningún repositorio Git.")
|
|
1509
|
-
|
|
1510
|
-
repo_root = Path(res.stdout.strip()).resolve()
|
|
1511
|
-
if not _configured_gui_diff_tool(git_bin, repo_root):
|
|
1512
|
-
return {"success": False, "setup": detect_gui_diff_tool()}
|
|
1513
|
-
|
|
1514
|
-
has_head = subprocess.run(
|
|
1515
|
-
[git_bin, "rev-parse", "--verify", "HEAD"],
|
|
1516
|
-
cwd=str(repo_root),
|
|
1517
|
-
stdout=subprocess.DEVNULL,
|
|
1518
|
-
stderr=subprocess.DEVNULL,
|
|
1519
|
-
timeout=5,
|
|
1520
|
-
check=False
|
|
1521
|
-
).returncode == 0
|
|
1522
|
-
|
|
1523
|
-
in_head = False
|
|
1524
|
-
has_working_tree_diff = True
|
|
1525
|
-
if has_head:
|
|
1526
|
-
try:
|
|
1527
|
-
rel_path = target.relative_to(repo_root).as_posix()
|
|
1528
|
-
in_head = subprocess.run(
|
|
1529
|
-
[git_bin, "cat-file", "-e", f"HEAD:{rel_path}"],
|
|
1530
|
-
cwd=str(repo_root),
|
|
1531
|
-
stdout=subprocess.DEVNULL,
|
|
1532
|
-
stderr=subprocess.DEVNULL,
|
|
1533
|
-
timeout=5,
|
|
1534
|
-
check=False
|
|
1535
|
-
).returncode == 0
|
|
1536
|
-
if in_head:
|
|
1537
|
-
diff_check = subprocess.run(
|
|
1538
|
-
[git_bin, "diff", "--quiet", "HEAD", "--", str(target)],
|
|
1539
|
-
cwd=str(repo_root),
|
|
1540
|
-
timeout=5,
|
|
1541
|
-
check=False
|
|
1542
|
-
)
|
|
1543
|
-
has_working_tree_diff = (diff_check.returncode != 0)
|
|
1544
|
-
except ValueError:
|
|
1545
|
-
in_head = False
|
|
1546
|
-
|
|
1547
|
-
cmd = [git_bin, "difftool", "--no-prompt", "--gui"]
|
|
1548
|
-
|
|
1549
|
-
mode = "working_tree"
|
|
1550
|
-
last_commit = ""
|
|
1551
|
-
if has_working_tree_diff:
|
|
1552
|
-
if in_head:
|
|
1553
|
-
cmd.extend(["HEAD", "--", str(target)])
|
|
1554
|
-
else:
|
|
1555
|
-
cmd.extend(["--no-index", "--", os.devnull, str(target)])
|
|
1556
|
-
else:
|
|
1557
|
-
# No hay cambios pendientes en el árbol de trabajo. Comprobar historial del archivo.
|
|
1558
|
-
rel_path = target.relative_to(repo_root).as_posix()
|
|
1559
|
-
log_res = subprocess.run(
|
|
1560
|
-
[git_bin, "log", "-n", "1", "--format=%H", "--", rel_path],
|
|
1561
|
-
cwd=str(repo_root),
|
|
1562
|
-
capture_output=True,
|
|
1563
|
-
text=True,
|
|
1564
|
-
timeout=5,
|
|
1565
|
-
check=False
|
|
1566
|
-
)
|
|
1567
|
-
last_commit = log_res.stdout.strip() if log_res.returncode == 0 else ""
|
|
1568
|
-
if not commit_fallback or not last_commit:
|
|
1569
|
-
return {
|
|
1570
|
-
"success": True,
|
|
1571
|
-
"has_diff": False,
|
|
1572
|
-
"in_head": in_head,
|
|
1573
|
-
"has_commit_history": bool(last_commit),
|
|
1574
|
-
"last_commit": last_commit or None,
|
|
1575
|
-
"path": str(target)
|
|
1576
|
-
}
|
|
1577
|
-
|
|
1578
|
-
mode = "commit"
|
|
1579
|
-
parent_check = subprocess.run(
|
|
1580
|
-
[git_bin, "rev-parse", "--verify", f"{last_commit}~1"],
|
|
1581
|
-
cwd=str(repo_root),
|
|
1582
|
-
stdout=subprocess.DEVNULL,
|
|
1583
|
-
stderr=subprocess.DEVNULL,
|
|
1584
|
-
timeout=5,
|
|
1585
|
-
check=False
|
|
1586
|
-
)
|
|
1587
|
-
if parent_check.returncode == 0:
|
|
1588
|
-
cmd.extend([f"{last_commit}~1", last_commit, "--", str(target)])
|
|
1589
|
-
else:
|
|
1590
|
-
cmd.extend(["4b825dc642cb6eb9a060e54bf8d69288fbee4904", last_commit, "--", str(target)])
|
|
1591
|
-
|
|
1592
|
-
popen_kwargs = {
|
|
1593
|
-
"cwd": str(repo_root),
|
|
1594
|
-
"stdin": subprocess.DEVNULL,
|
|
1595
|
-
"stdout": subprocess.DEVNULL,
|
|
1596
|
-
"stderr": subprocess.DEVNULL,
|
|
1597
|
-
}
|
|
1598
|
-
if os.name == "nt":
|
|
1599
|
-
popen_kwargs["creationflags"] = (
|
|
1600
|
-
getattr(subprocess, "DETACHED_PROCESS", 0) |
|
|
1601
|
-
getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
|
|
1602
|
-
)
|
|
1603
|
-
else:
|
|
1604
|
-
popen_kwargs["start_new_session"] = True
|
|
1605
|
-
|
|
1606
|
-
proc = subprocess.Popen(cmd, **popen_kwargs)
|
|
1607
|
-
return {
|
|
1608
|
-
"success": True,
|
|
1609
|
-
"has_diff": True,
|
|
1610
|
-
"mode": mode,
|
|
1611
|
-
"pid": proc.pid,
|
|
1612
|
-
"path": str(target),
|
|
1613
|
-
"in_head": in_head,
|
|
1614
|
-
"commit": last_commit or None
|
|
1615
|
-
}
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
2118
|
def search_files(query: str, path: str = ".", file_pattern: str = None, max_results: int = 100) -> str:
|
|
1619
2119
|
"""Recursively search for plain text or regular expressions across project files."""
|
|
1620
2120
|
try:
|
|
@@ -4668,7 +5168,7 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
|
|
|
4668
5168
|
return None, {"code": -32602, "message": str(exc)}, ""
|
|
4669
5169
|
if method == "zerochat/diff/open":
|
|
4670
5170
|
try:
|
|
4671
|
-
return open_file_diff(params.get("path"), bool(params.get("commit_fallback"))), None, ""
|
|
5171
|
+
return open_file_diff(params.get("path"), bool(params.get("commit_fallback")), bool(params.get("gui"))), None, ""
|
|
4672
5172
|
except (ValueError, RuntimeError) as exc:
|
|
4673
5173
|
return None, {"code": -32602, "message": str(exc)}, ""
|
|
4674
5174
|
except Exception as exc:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|