Repository navigation
Expand file tree
/
Copy pathinstall.py
More file actions
410 lines (357 loc) · 13.6 KB
/
Copy pathinstall.py
File metadata and controls
410 lines (357 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
"""Install Codex Notifier on Windows or Linux using only Python's stdlib."""
from __future__ import annotations
import argparse
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from typing import Callable, Sequence
from codex_notifier.files import atomic_copy, atomic_write_text
PROJECT_ROOT = Path(__file__).resolve().parent
NOTIFIER_PATH = PROJECT_ROOT / "notifier.py"
EXAMPLE_CONFIG_PATH = PROJECT_ROOT / "config.example.json"
def default_codex_home(
environment: dict[str, str] | None = None, home: Path | None = None
) -> Path:
env = os.environ if environment is None else environment
configured = env.get("CODEX_HOME", "").strip()
if configured:
return Path(configured).expanduser()
return (Path.home() if home is None else home) / ".codex"
def default_local_config_path(
*,
platform_name: str | None = None,
environment: dict[str, str] | None = None,
home: Path | None = None,
) -> Path:
platform = os.name if platform_name is None else platform_name
env = os.environ if environment is None else environment
configured = env.get("CODEX_NOTIFIER_CONFIG", "").strip()
if configured:
return Path(configured).expanduser()
user_home = Path.home() if home is None else home
if platform == "nt":
local_app_data = env.get("LOCALAPPDATA", "").strip()
if local_app_data:
return Path(local_app_data) / "CodexNotifier" / "config.json"
return user_home / "AppData" / "Local" / "CodexNotifier" / "config.json"
xdg_config_home = env.get("XDG_CONFIG_HOME", "").strip()
config_home = Path(xdg_config_home) if xdg_config_home else user_home / ".config"
return config_home / "codex-notifier" / "config.json"
def _is_python3(
command: Sequence[str],
*,
runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
) -> bool:
try:
result = runner(
[
*command,
"-c",
"import sys; raise SystemExit(0 if sys.version_info.major == 3 else 1)",
],
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
text=True,
timeout=10,
check=False,
)
except (OSError, subprocess.SubprocessError):
return False
return result.returncode == 0
def _is_mise_managed_path(executable: str) -> bool:
normalized = executable.replace("\\", "/").lower()
return "/mise/shims/" in normalized or "/mise/installs/" in normalized
def resolve_python_command(
*,
platform_name: str | None = None,
explicit_executable: str | None = None,
which: Callable[[str], str | None] = shutil.which,
runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
current_executable: str | None = None,
) -> list[str]:
"""Find a stable Python 3 command, preferring non-mise installations."""
platform = os.name if platform_name is None else platform_name
if explicit_executable:
candidate = [str(Path(explicit_executable).expanduser())]
if _is_python3(candidate, runner=runner):
return candidate
raise RuntimeError(f"No es un Python 3 válido: {explicit_executable}")
names: list[tuple[str, list[str]]] = [("python3", [])]
if platform == "nt":
names.append(("py", ["-3"]))
names.append(("python", []))
for name, arguments in names:
executable = which(name)
if executable and not _is_mise_managed_path(executable):
candidate = [executable, *arguments]
if _is_python3(candidate, runner=runner):
return candidate
mise = which("mise")
if mise:
candidate = [mise, "exec", "--", "python"]
if _is_python3(candidate, runner=runner):
return candidate
active_python = current_executable or sys.executable
if active_python and _is_python3([active_python], runner=runner):
return [active_python]
raise RuntimeError(
"No se encontró Python 3. Instálalo o ejecuta este archivo con "
"'mise exec -- python install.py'."
)
def _command_text(arguments: Sequence[str], platform_name: str) -> str:
if platform_name == "nt":
return subprocess.list2cmdline(list(arguments))
return shlex.join(arguments)
def _backup(path: Path, timestamp: str) -> Path:
backup = path.with_name(f"{path.name}.{timestamp}.bak")
shutil.copy2(path, backup)
return backup
def _strip_toml_comment(line: str) -> str:
"""Return the part before an unquoted TOML comment marker."""
quote = ""
escaped = False
for index, character in enumerate(line):
if quote == '"' and escaped:
escaped = False
continue
if quote == '"' and character == "\\":
escaped = True
continue
if character in {'"', "'"}:
if not quote:
quote = character
elif quote == character:
quote = ""
elif character == "#" and not quote:
return line[:index]
return line
def _is_toml_table_header(line: str) -> bool:
return _strip_toml_comment(line).strip().startswith("[")
def _inline_comment(line: str) -> str:
content = line.rstrip("\r\n")
stripped = _strip_toml_comment(content)
return content[len(stripped.rstrip()):]
def update_root_notify(existing: str, notify_line: str) -> str:
"""Update only a bare root-level ``notify`` before the first TOML table."""
lines = existing.splitlines(keepends=True)
first_table = next((index for index, line in enumerate(lines) if _is_toml_table_header(line)), len(lines))
root_index = next(
(index for index, line in enumerate(lines[:first_table])
if re.match(r"^[ \t]*notify[ \t]*=", _strip_toml_comment(line))),
None,
)
if root_index is not None:
original = lines[root_index]
ending = "\r\n" if original.endswith("\r\n") else "\n" if original.endswith("\n") else ""
lines[root_index] = notify_line + _inline_comment(original) + ending
return "".join(lines)
newline = "\r\n" if "\r\n" in existing else "\n"
insertion = notify_line + newline
if first_table < len(lines):
lines.insert(first_table, insertion)
return "".join(lines)
return insertion + existing
def update_codex_config(
config_path: Path,
python_command: Sequence[str],
notifier_path: Path,
*,
timestamp: str,
platform_name: str | None = None,
) -> tuple[bool, Path | None]:
config_path.parent.mkdir(parents=True, exist_ok=True)
existing = config_path.read_text(encoding="utf-8") if config_path.exists() else ""
notify_arguments = [*python_command, str(notifier_path), "notify"]
notify_line = "notify = " + json.dumps(notify_arguments, ensure_ascii=False)
updated = update_root_notify(existing, notify_line)
if updated == existing:
return False, None
backup = _backup(config_path, timestamp) if config_path.exists() else None
atomic_write_text(
config_path,
updated,
mode=0o600,
platform_name=os.name if platform_name is None else platform_name,
)
return True, backup
def _is_notifier_handler(handler: object) -> bool:
if not isinstance(handler, dict):
return False
commands = [handler.get("command"), handler.get("commandWindows")]
return any(
isinstance(command, str)
and "notifier.py" in command
and "record-start" in command
for command in commands
)
def update_hooks(
hooks_path: Path,
python_command: Sequence[str],
notifier_path: Path,
*,
platform_name: str,
timestamp: str,
) -> tuple[bool, Path | None]:
hooks_path.parent.mkdir(parents=True, exist_ok=True)
if hooks_path.exists():
document = json.loads(hooks_path.read_text(encoding="utf-8"))
if not isinstance(document, dict):
raise TypeError(f"{hooks_path} debe contener un objeto JSON")
else:
document = {
"description": "Local lifecycle hooks for Codex.",
"hooks": {},
}
hooks = document.setdefault("hooks", {})
if not isinstance(hooks, dict):
raise TypeError(f"El campo hooks de {hooks_path} debe ser un objeto")
groups = hooks.setdefault("UserPromptSubmit", [])
if not isinstance(groups, list):
raise TypeError("hooks.UserPromptSubmit debe ser una lista")
preserved_groups: list[object] = []
for group in groups:
if not isinstance(group, dict):
preserved_groups.append(group)
continue
handlers = group.get("hooks")
if not isinstance(handlers, list):
preserved_groups.append(group)
continue
kept_handlers = [handler for handler in handlers if not _is_notifier_handler(handler)]
if kept_handlers:
copied_group = dict(group)
copied_group["hooks"] = kept_handlers
preserved_groups.append(copied_group)
hook_arguments = [*python_command, str(notifier_path), "record-start"]
handler = {
"type": "command",
"command": _command_text(hook_arguments, platform_name),
"timeout": 5,
}
preserved_groups.append({"hooks": [handler]})
hooks["UserPromptSubmit"] = preserved_groups
updated = json.dumps(document, ensure_ascii=False, indent=2) + os.linesep
existing = hooks_path.read_text(encoding="utf-8") if hooks_path.exists() else ""
if updated == existing:
return False, None
backup = _backup(hooks_path, timestamp) if hooks_path.exists() else None
atomic_write_text(hooks_path, updated, mode=0o600, platform_name=platform_name)
return True, backup
def install_local_config(
example_path: Path,
destination: Path,
*,
force: bool,
platform_name: str,
timestamp: str,
) -> tuple[bool, Path | None]:
if destination.exists() and not force:
return False, None
destination.parent.mkdir(parents=True, exist_ok=True)
backup = _backup(destination, timestamp) if destination.exists() else None
atomic_copy(example_path, destination, mode=0o600, platform_name=platform_name)
return True, backup
def install(
*,
codex_home: Path,
local_config_path: Path,
python_command: Sequence[str],
notifier_path: Path = NOTIFIER_PATH,
example_path: Path = EXAMPLE_CONFIG_PATH,
platform_name: str | None = None,
force_config: bool = False,
timestamp: str | None = None,
) -> dict[str, object]:
platform = os.name if platform_name is None else platform_name
stamp = timestamp or datetime.now().strftime("%Y%m%d-%H%M%S")
config_changed, config_backup = update_codex_config(
codex_home / "config.toml",
python_command,
notifier_path,
timestamp=stamp,
platform_name=platform,
)
hooks_changed, hooks_backup = update_hooks(
codex_home / "hooks.json",
python_command,
notifier_path,
platform_name=platform,
timestamp=stamp,
)
local_changed, local_backup = install_local_config(
example_path,
local_config_path,
force=force_config,
platform_name=platform,
timestamp=stamp,
)
return {
"config_changed": config_changed,
"config_backup": config_backup,
"hooks_changed": hooks_changed,
"hooks_backup": hooks_backup,
"local_config_changed": local_changed,
"local_config_backup": local_backup,
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Instala Codex Notifier y crea su configuración local."
)
parser.add_argument(
"--codex-home",
type=Path,
default=default_codex_home(),
help="Ruta de CODEX_HOME (predeterminado: ~/.codex).",
)
parser.add_argument(
"--config-path",
type=Path,
default=default_local_config_path(),
help="Ruta del config.json local del notificador.",
)
parser.add_argument(
"--python-executable",
help="Ejecutable de Python 3 que usarán notify y el hook.",
)
parser.add_argument(
"--force-config",
action="store_true",
help="Reemplaza config.json con config.example.json (crea backup).",
)
return parser.parse_args()
def main() -> int:
args = parse_args()
if not NOTIFIER_PATH.is_file() or not EXAMPLE_CONFIG_PATH.is_file():
print("Faltan notifier.py o config.example.json.", file=sys.stderr)
return 1
try:
python_command = resolve_python_command(
explicit_executable=args.python_executable
)
result = install(
codex_home=args.codex_home.expanduser().resolve(),
local_config_path=args.config_path.expanduser().resolve(),
python_command=python_command,
force_config=args.force_config,
)
except (OSError, ValueError, TypeError, RuntimeError, json.JSONDecodeError) as exc:
print(f"No se pudo instalar: {exc}", file=sys.stderr)
return 1
print("Python:", _command_text(python_command, os.name))
print("Codex config:", args.codex_home.expanduser() / "config.toml")
print("Codex hooks:", args.codex_home.expanduser() / "hooks.json")
print("Notifier config:", args.config_path.expanduser())
if not result["local_config_changed"]:
print("Se conservó el config.json existente.")
if result["hooks_changed"]:
print("Abre un chat nuevo y usa /hooks para revisar y confiar en el hook.")
return 0
if __name__ == "__main__":
raise SystemExit(main())