synth-shell-theme 1.3.9__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.
Files changed (82) hide show
  1. synth_shell_theme/__init__.py +7 -0
  2. synth_shell_theme/__main__.py +8 -0
  3. synth_shell_theme/assets/studio.html +1920 -0
  4. synth_shell_theme/cli.py +887 -0
  5. synth_shell_theme/core.py +1695 -0
  6. synth_shell_theme/ecosystem.py +537 -0
  7. synth_shell_theme/patches.py +1853 -0
  8. synth_shell_theme/paths.py +363 -0
  9. synth_shell_theme/separators.py +320 -0
  10. synth_shell_theme/server.py +506 -0
  11. synth_shell_theme/themes/01-screenshot-match.conf +30 -0
  12. synth_shell_theme/themes/02-current-live-theme.conf +30 -0
  13. synth_shell_theme/themes/03-dracula-punch.conf +30 -0
  14. synth_shell_theme/themes/04-nord-ice.conf +30 -0
  15. synth_shell_theme/themes/05-matrix-green.conf +30 -0
  16. synth_shell_theme/themes/06-amber-heat.conf +30 -0
  17. synth_shell_theme/themes/07-cloud-ops.conf +30 -0
  18. synth_shell_theme/themes/08-catppuccin-mauve.conf +30 -0
  19. synth_shell_theme/themes/09-solarized-night.conf +30 -0
  20. synth_shell_theme/themes/10-gruvbox-dark.conf +30 -0
  21. synth_shell_theme/themes/11-monokai-neon.conf +30 -0
  22. synth_shell_theme/themes/12-tokyo-night.conf +30 -0
  23. synth_shell_theme/themes/13-synthwave-pink.conf +30 -0
  24. synth_shell_theme/themes/14-forest-mint.conf +30 -0
  25. synth_shell_theme/themes/15-ruby-steel.conf +30 -0
  26. synth_shell_theme/themes/16-ice-gold.conf +30 -0
  27. synth_shell_theme/themes/17-aqua-slate.conf +30 -0
  28. synth_shell_theme/themes/18-cyber-lime.conf +30 -0
  29. synth_shell_theme/themes/19-lavender-sunset.conf +30 -0
  30. synth_shell_theme/themes/20-minimal-mono.conf +30 -0
  31. synth_shell_theme/themes/21-rose-pine.conf +30 -0
  32. synth_shell_theme/themes/22-kanagawa.conf +30 -0
  33. synth_shell_theme/themes/23-everforest.conf +30 -0
  34. synth_shell_theme/themes/24-one-dark.conf +30 -0
  35. synth_shell_theme/themes/25-ayu-dark.conf +30 -0
  36. synth_shell_theme/themes/26-nightfox.conf +30 -0
  37. synth_shell_theme/themes/27-palenight.conf +30 -0
  38. synth_shell_theme/themes/28-cyberdream.conf +30 -0
  39. synth_shell_theme/themes/29-moonlight.conf +30 -0
  40. synth_shell_theme/themes/30-poimandres.conf +30 -0
  41. synth_shell_theme/themes/31-tokyo-storm.conf +30 -0
  42. synth_shell_theme/themes/32-catppuccin-mocha.conf +30 -0
  43. synth_shell_theme/themes/33-nordic-aurora.conf +30 -0
  44. synth_shell_theme/themes/34-horizon-synth.conf +30 -0
  45. synth_shell_theme/themes/35-gruvbox-material.conf +30 -0
  46. synth_shell_theme/themes/36-oxocarbon.conf +30 -0
  47. synth_shell_theme/themes/37-catppuccin-latte.conf +30 -0
  48. synth_shell_theme/themes/38-tokyo-twilight.conf +30 -0
  49. synth_shell_theme/themes/39-solarized-ocean.conf +30 -0
  50. synth_shell_theme/themes/40-vaporwave-sunset.conf +30 -0
  51. synth_shell_theme/themes/41-deep-abyss.conf +30 -0
  52. synth_shell_theme/themes/42-sakura-blossom.conf +30 -0
  53. synth_shell_theme/themes/43-emerald-forest.conf +30 -0
  54. synth_shell_theme/themes/44-vesper.conf +30 -0
  55. synth_shell_theme/themes/45-cobalt-neon.conf +30 -0
  56. synth_shell_theme/themes/46-desert-dunes.conf +30 -0
  57. synth_shell_theme/themes/47-cyber-samurai.conf +30 -0
  58. synth_shell_theme/themes/48-glacier-mint.conf +30 -0
  59. synth_shell_theme/themes/49-carbon-titanium.conf +30 -0
  60. synth_shell_theme/themes/50-matcha-latte.conf +30 -0
  61. synth_shell_theme/themes/51-volcanic-magma.conf +30 -0
  62. synth_shell_theme/themes/52-catppuccin-frappe.conf +30 -0
  63. synth_shell_theme/themes/53-bioluminescence.conf +30 -0
  64. synth_shell_theme/themes/54-mocha-caramel.conf +30 -0
  65. synth_shell_theme/themes/55-neon-genesis.conf +30 -0
  66. synth_shell_theme/themes/56-midnight-amethyst.conf +30 -0
  67. synth_shell_theme/themes/57-andromeda.conf +30 -0
  68. synth_shell_theme/themes/58-golden-velvet.conf +30 -0
  69. synth_shell_theme/themes/59-miami-vice.conf +30 -0
  70. synth_shell_theme/themes/60-zen-garden.conf +30 -0
  71. synth_shell_theme/themes/61-google-cloud.conf +30 -0
  72. synth_shell_theme/themes/62-github-dark.conf +30 -0
  73. synth_shell_theme/themes/63-cyberpunk-edgerunners.conf +30 -0
  74. synth_shell_theme/themes/64-vscode-dark.conf +30 -0
  75. synth_shell_theme/themes.py +580 -0
  76. synth_shell_theme/tui.py +632 -0
  77. synth_shell_theme-1.3.9.dist-info/METADATA +261 -0
  78. synth_shell_theme-1.3.9.dist-info/RECORD +82 -0
  79. synth_shell_theme-1.3.9.dist-info/WHEEL +5 -0
  80. synth_shell_theme-1.3.9.dist-info/entry_points.txt +3 -0
  81. synth_shell_theme-1.3.9.dist-info/licenses/LICENSE +21 -0
  82. synth_shell_theme-1.3.9.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1695 @@
1
+ """Atomic configuration reader/writer, backups, layout controls, root/greeter sync, and JSON presets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import shutil
9
+ import statistics
10
+ import subprocess
11
+ import tempfile
12
+ import time
13
+ from datetime import datetime
14
+ from pathlib import Path
15
+
16
+ from synth_shell_theme.patches import apply_runtime_patches, ensure_dual_separator_support, inspect_patches
17
+ from synth_shell_theme.paths import (
18
+ get_backup_dir,
19
+ get_config_dir,
20
+ get_config_path,
21
+ get_greeter_config_path,
22
+ get_prompt_script_path,
23
+ get_root_config_path,
24
+ )
25
+ from synth_shell_theme.separators import (
26
+ ALL_PRESETS,
27
+ format_separator_assignment,
28
+ get_separator_key,
29
+ parse_separator_value,
30
+ resolve_separator_input,
31
+ )
32
+ from synth_shell_theme.themes import (
33
+ DEFAULT_SEGMENT_COLORS,
34
+ SEGMENT_KEYS,
35
+ find_theme,
36
+ is_color_key,
37
+ load_themes,
38
+ token_to_hex,
39
+ )
40
+
41
+ VALID_FORMAT_TOKENS: tuple[str, ...] = (
42
+ "USER",
43
+ "HOST",
44
+ "PWD",
45
+ "GIT",
46
+ "PYENV",
47
+ "TF",
48
+ "KUBE",
49
+ "CLOCK",
50
+ "STATUS",
51
+ "DURATION",
52
+ "AWS",
53
+ "GCP",
54
+ "DOCKER",
55
+ "NODE",
56
+ "SSH",
57
+ "JOBS",
58
+ "DIRENV",
59
+ "SHLVL",
60
+ "RUST",
61
+ "GO",
62
+ "BATTERY",
63
+ "SUDO",
64
+ "JJ",
65
+ "CUSTOM",
66
+ )
67
+
68
+ VALID_FONT_EFFECTS: tuple[str, ...] = (
69
+ "bold",
70
+ "regular",
71
+ "italic",
72
+ "dim",
73
+ "none",
74
+ )
75
+
76
+ GREETER_ALL_MONITORS: tuple[str, ...] = (
77
+ "OS",
78
+ "KERNEL",
79
+ "CPU",
80
+ "GPU",
81
+ "SHELL",
82
+ "DATE",
83
+ "UPTIME",
84
+ "USER",
85
+ "LOCALIPV4",
86
+ "EXTERNALIPV4",
87
+ "SERVICES",
88
+ "CPUTEMP",
89
+ "SYSLOAD_MON%",
90
+ "MEMORY_MON",
91
+ "SWAP_MON",
92
+ "HDDROOT_MON",
93
+ "HDDHOME_MON",
94
+ "PALETTE",
95
+ )
96
+
97
+ DEFAULT_GREETER_MONITORS: tuple[str, ...] = (
98
+ "OS",
99
+ "KERNEL",
100
+ "CPU",
101
+ "GPU",
102
+ "SHELL",
103
+ "DATE",
104
+ "UPTIME",
105
+ "LOCALIPV4",
106
+ "SERVICES",
107
+ "CPUTEMP",
108
+ "SYSLOAD_MON%",
109
+ "MEMORY_MON",
110
+ "SWAP_MON",
111
+ "HDDROOT_MON",
112
+ "HDDHOME_MON",
113
+ "PALETTE",
114
+ )
115
+
116
+ ASCII_SAFE_GIT_SYMBOLS: dict[str, str] = {
117
+ "git_symbol_synced": "",
118
+ "git_symbol_unpushed": " +",
119
+ "git_symbol_unpulled": " -",
120
+ "git_symbol_unpushedunpulled": " <>",
121
+ "git_symbol_dirty": " *",
122
+ "git_symbol_dirty_unpushed": " *+",
123
+ "git_symbol_dirty_unpulled": " *-",
124
+ "git_symbol_dirty_unpushedunpulled": " *<>",
125
+ "git_symbol_stash": "#",
126
+ "pwd_trunc_symbol": "...",
127
+ "status_symbol": "! ",
128
+ }
129
+
130
+
131
+ def _atomic_write(target: Path, content: str) -> None:
132
+ """Write `content` atomically to `target`, preserving file permissions if it already exists."""
133
+ target.parent.mkdir(parents=True, exist_ok=True)
134
+ mode = target.stat().st_mode if target.exists() else None
135
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{target.name}.", dir=str(target.parent))
136
+ tmp_path = Path(tmp_name)
137
+ try:
138
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as fh:
139
+ fh.write(content)
140
+ if mode is not None:
141
+ try:
142
+ os.chmod(tmp_path, mode)
143
+ except OSError:
144
+ pass
145
+ os.replace(tmp_path, target)
146
+ finally:
147
+ if tmp_path.exists():
148
+ try:
149
+ tmp_path.unlink()
150
+ except OSError:
151
+ pass
152
+
153
+
154
+ def _strip_inline_comment(val: str) -> str:
155
+ """Strip unquoted `# ...` inline Bash comments from a config assignment RHS."""
156
+ in_single = False
157
+ in_double = False
158
+ escaped = False
159
+ for idx, ch in enumerate(val):
160
+ if escaped:
161
+ escaped = False
162
+ continue
163
+ if ch == "\\" and not in_single:
164
+ escaped = True
165
+ continue
166
+ if ch == "'" and not in_double:
167
+ in_single = not in_single
168
+ elif ch == '"' and not in_single:
169
+ in_double = not in_double
170
+ elif ch == "#" and not in_single and not in_double:
171
+ return val[:idx].strip()
172
+ return val.strip()
173
+
174
+
175
+ def _unquote(val: str) -> str:
176
+ """Remove surrounding Bash quotes (`\"...\"`, `'...'`, or `$'...'`)."""
177
+ s = _strip_inline_comment(val)
178
+ if s.startswith("$'") and s.endswith("'"):
179
+ return s[2:-1]
180
+ if len(s) >= 2 and s[0] == s[-1] and s[0] in ('"', "'"):
181
+ return s[1:-1]
182
+ return s
183
+
184
+
185
+ def _escape_bash_dq(val: str) -> str:
186
+ return val.replace("\\", "\\\\").replace('"', '\\"')
187
+
188
+
189
+ def _upsert_kv_lines(lines: list[str], updates: dict[str, str]) -> list[str]:
190
+ """Update existing `key=...` lines in-place and append any missing keys cleanly."""
191
+ new_lines: list[str] = []
192
+ seen: set[str] = set()
193
+ for line in lines:
194
+ m = re.match(r"^(\w+)\s*=", line)
195
+ key = m.group(1) if m else ""
196
+ if key in updates:
197
+ new_lines.append(f'{key}="{_escape_bash_dq(updates[key])}"')
198
+ seen.add(key)
199
+ else:
200
+ new_lines.append(line)
201
+ for key, val in updates.items():
202
+ if key not in seen:
203
+ new_lines.append(f'{key}="{_escape_bash_dq(val)}"')
204
+ return new_lines
205
+
206
+
207
+ def backup_config(config_dir: Path | None = None) -> Path | None:
208
+ """Create a timestamped backup of `synth-shell-prompt.config` in `backups/`."""
209
+ base = config_dir if config_dir is not None else get_config_dir()
210
+ cfg = get_config_path(base)
211
+ if not cfg.is_file():
212
+ return None
213
+ bdir = get_backup_dir(base)
214
+ bdir.mkdir(parents=True, exist_ok=True)
215
+ stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
216
+ dest = bdir / f"synth-shell-prompt.config.{stamp}.bak"
217
+ counter = 1
218
+ while dest.exists():
219
+ dest = bdir / f"synth-shell-prompt.config.{stamp}-{counter}.bak"
220
+ counter += 1
221
+ shutil.copy2(cfg, dest)
222
+
223
+ # Keep at most 40 config backups so `backups/` stays tidy
224
+ all_baks = sorted(bdir.glob("synth-shell-prompt.config.*.bak"))
225
+ if len(all_baks) > 40:
226
+ for old in all_baks[:-40]:
227
+ try:
228
+ old.unlink()
229
+ except OSError:
230
+ pass
231
+ return dest
232
+
233
+
234
+ def list_backups(config_dir: Path | None = None) -> list[dict[str, object]]:
235
+ """Return available config backups sorted newest-first."""
236
+ base = config_dir if config_dir is not None else get_config_dir()
237
+ bdir = get_backup_dir(base)
238
+ if not bdir.is_dir():
239
+ return []
240
+ files = sorted(
241
+ bdir.glob("synth-shell-prompt.config.*.bak"),
242
+ key=lambda p: p.stat().st_mtime,
243
+ reverse=True,
244
+ )
245
+ out: list[dict[str, object]] = []
246
+ for idx, f in enumerate(files, 1):
247
+ stat = f.stat()
248
+ out.append(
249
+ {
250
+ "id": idx,
251
+ "name": f.name,
252
+ "path": str(f),
253
+ "size": stat.st_size,
254
+ "modified": datetime.fromtimestamp(stat.st_mtime).strftime("%Y-%m-%d %H:%M:%S"),
255
+ }
256
+ )
257
+ return out
258
+
259
+
260
+ def restore_backup(
261
+ target: int | str | None = None,
262
+ config_dir: Path | None = None,
263
+ ) -> Path | None:
264
+ """Restore a backup by 1-based index (default `1` = latest) or filename."""
265
+ base = config_dir if config_dir is not None else get_config_dir()
266
+ cfg = get_config_path(base)
267
+ bdir = get_backup_dir(base)
268
+ if not bdir.is_dir():
269
+ return None
270
+ files = sorted(
271
+ bdir.glob("synth-shell-prompt.config.*.bak"),
272
+ key=lambda p: p.stat().st_mtime,
273
+ reverse=True,
274
+ )
275
+ if not files:
276
+ return None
277
+
278
+ chosen: Path | None = None
279
+ if target is None or target == "" or target == 1 or target == "1":
280
+ chosen = files[0]
281
+ elif isinstance(target, int) or (isinstance(target, str) and target.strip().isdigit()):
282
+ idx = int(str(target).strip())
283
+ if 1 <= idx <= len(files):
284
+ chosen = files[idx - 1]
285
+ else:
286
+ t_str = str(target).strip()
287
+ for f in files:
288
+ if f.name == t_str or str(f) == t_str:
289
+ chosen = f
290
+ break
291
+
292
+ if chosen is None or not chosen.is_file():
293
+ return None
294
+
295
+ content = chosen.read_text(encoding="utf-8", errors="replace")
296
+ _atomic_write(cfg, content)
297
+ return chosen
298
+
299
+
300
+ def detect_current_separators(
301
+ config_dir: Path | None = None,
302
+ ) -> tuple[tuple[str, str], tuple[str, str] | None]:
303
+ """Return `((internal_glyph, internal_code), (end_glyph, end_code) | None)` from live config."""
304
+ base = config_dir if config_dir is not None else get_config_dir()
305
+ cfg = get_config_path(base)
306
+ internal_res = ("\ue0b4", "\\uE0B4")
307
+ end_res: tuple[str, str] | None = None
308
+ if not cfg.is_file():
309
+ return internal_res, end_res
310
+
311
+ for raw_line in cfg.read_text(encoding="utf-8", errors="replace").splitlines():
312
+ line = raw_line.strip()
313
+ m_main = re.match(r"^separator_char\s*=\s*(.+)$", line)
314
+ if m_main:
315
+ rhs = _strip_inline_comment(m_main.group(1))
316
+ parsed = parse_separator_value(rhs)
317
+ if parsed[0]:
318
+ internal_res = parsed
319
+ continue
320
+ m_end = re.match(r"^separator_char_end\s*=\s*(.+)$", line)
321
+ if m_end:
322
+ rhs = _strip_inline_comment(m_end.group(1))
323
+ parsed = parse_separator_value(rhs)
324
+ if parsed[0]:
325
+ end_res = parsed
326
+ continue
327
+
328
+ return internal_res, end_res
329
+
330
+
331
+ def detect_current_theme(
332
+ themes: list[dict[str, object]],
333
+ config_dir: Path | None = None,
334
+ ) -> tuple[str | None, int | None]:
335
+ """Detect the currently active theme name and 1-based index from `synth-shell-prompt.config`."""
336
+ base = config_dir if config_dir is not None else get_config_dir()
337
+ cfg = get_config_path(base)
338
+ if not cfg.is_file():
339
+ return None, None
340
+
341
+ lines = cfg.read_text(encoding="utf-8", errors="replace").splitlines()
342
+ current: dict[str, str] = {}
343
+ header_title: str | None = None
344
+
345
+ for raw_line in lines:
346
+ line = raw_line.strip()
347
+ m_hdr = re.match(r"^#\s*Theme\s+\d+:\s*(.+)$", line)
348
+ if m_hdr and header_title is None:
349
+ header_title = m_hdr.group(1).strip()
350
+ continue
351
+ m_kv = re.match(r"^(font_color_\w+|background_\w+)\s*=\s*(.+)$", line)
352
+ if m_kv:
353
+ current[m_kv.group(1)] = _unquote(m_kv.group(2)).strip()
354
+
355
+ if not current and not header_title:
356
+ return None, None
357
+
358
+ color_keys = [
359
+ "font_color_host",
360
+ "background_host",
361
+ "font_color_pwd",
362
+ "background_pwd",
363
+ "font_color_git",
364
+ "background_git",
365
+ "font_color_input",
366
+ "background_input",
367
+ ]
368
+ best_score = 0
369
+ best_match: tuple[str | None, int | None] = (None, None)
370
+ for idx, t in enumerate(themes, 1):
371
+ score = sum(
372
+ 1
373
+ for k in color_keys
374
+ if str(t.get(k, "")).lower() == current.get(k, "").lower()
375
+ )
376
+ if score > best_score:
377
+ best_score = score
378
+ best_match = (str(t.get("name", "")), idx)
379
+
380
+ if best_score >= 6:
381
+ return best_match
382
+
383
+ bg_keys = [
384
+ "background_host",
385
+ "background_pwd",
386
+ "background_git",
387
+ "background_pyenv",
388
+ "background_tf",
389
+ "background_kube",
390
+ ]
391
+ for idx, t in enumerate(themes, 1):
392
+ bg_matches = sum(
393
+ 1
394
+ for k in bg_keys
395
+ if k in current and str(t.get(k, "")).lower() == current.get(k, "").lower()
396
+ )
397
+ if bg_matches >= 5:
398
+ return str(t.get("name", "")), idx
399
+
400
+ if header_title:
401
+ found_t, found_idx = find_theme(header_title, themes)
402
+ if found_t and found_idx:
403
+ return str(found_t.get("name", "")), found_idx
404
+
405
+ return None, None
406
+
407
+
408
+ def read_current_state(
409
+ themes: list[dict[str, object]] | None = None,
410
+ config_dir: Path | None = None,
411
+ ) -> dict[str, object]:
412
+ """Read complete active prompt configuration state (v1.0 + v1.1 fields)."""
413
+ base = config_dir if config_dir is not None else get_config_dir()
414
+ cfg = get_config_path(base)
415
+ catalog = themes if themes is not None else load_themes()
416
+
417
+ (int_glyph, int_code), end_tuple = detect_current_separators(base)
418
+ end_glyph = end_tuple[0] if end_tuple else int_glyph
419
+ end_code = end_tuple[1] if end_tuple else int_code
420
+ active_name, active_id = detect_current_theme(catalog, base)
421
+
422
+ format_str = "HOST PWD GIT PYENV TF KUBE"
423
+ right_format_str = ""
424
+ right_fill_char = "─"
425
+ enable_osc133 = True
426
+ enable_osc7 = True
427
+ enable_terminal_sanitize = True
428
+ kube_show_namespace = True
429
+ kube_prod_warning = True
430
+ kube_prod_pattern = "prod|production|prd|live"
431
+ git_dynamic_color = False
432
+ ssh_host_color = False
433
+ pwd_style = "default"
434
+ notify_duration_sec = 0
435
+ custom_segment_text = ""
436
+ git_show_state = True
437
+ battery_threshold = 100
438
+ new_line = True
439
+ vertical_padding = True
440
+ max_pwd_char = 35
441
+ max_git_char = 0
442
+ max_pyenv_char = 0
443
+ max_kube_char = 28
444
+ compact_width = 90
445
+ git_show_counts = True
446
+ transient_prompt = False
447
+ light_theme = "catppuccin-latte"
448
+ dark_theme = "tokyo-night"
449
+ prompt_prefix = ""
450
+ font_effect = "bold"
451
+ enable_terminal_title = True
452
+ git_skip_untracked_on_slow_fs = True
453
+ git_timeout_ms = 0
454
+ git_async_cache = False
455
+ min_duration_ms = 2000
456
+ colors: dict[str, str] = {}
457
+
458
+ if cfg.is_file():
459
+ for raw_line in cfg.read_text(encoding="utf-8", errors="replace").splitlines():
460
+ line = raw_line.strip()
461
+ if not line or line.startswith("#"):
462
+ continue
463
+ m_kv = re.match(r"^(\w+)\s*=\s*(.+)$", line)
464
+ if not m_kv:
465
+ continue
466
+ key = m_kv.group(1)
467
+ val = _unquote(m_kv.group(2))
468
+ if key == "format":
469
+ format_str = " ".join(tok for tok in val.upper().split() if tok in VALID_FORMAT_TOKENS) or format_str
470
+ elif key == "right_format":
471
+ right_format_str = " ".join(tok for tok in val.upper().split() if tok in VALID_FORMAT_TOKENS)
472
+ elif key == "right_fill_char":
473
+ right_fill_char = val or " "
474
+ elif key == "enable_osc133":
475
+ enable_osc133 = val.lower() in ("true", "1", "yes")
476
+ elif key == "enable_osc7":
477
+ enable_osc7 = val.lower() in ("true", "1", "yes")
478
+ elif key == "enable_terminal_sanitize":
479
+ enable_terminal_sanitize = val.lower() in ("true", "1", "yes")
480
+ elif key == "kube_show_namespace":
481
+ kube_show_namespace = val.lower() in ("true", "1", "yes")
482
+ elif key == "kube_prod_warning":
483
+ kube_prod_warning = val.lower() in ("true", "1", "yes")
484
+ elif key == "kube_prod_pattern":
485
+ kube_prod_pattern = val or "prod|production|prd|live"
486
+ elif key == "git_dynamic_color":
487
+ git_dynamic_color = val.lower() in ("true", "1", "yes")
488
+ elif key == "ssh_host_color":
489
+ ssh_host_color = val.lower() in ("true", "1", "yes")
490
+ elif key == "pwd_style":
491
+ pwd_style = val.lower() if val.lower() in ("default", "fish") else "default"
492
+ elif key == "notify_duration_sec" and val.isdigit():
493
+ notify_duration_sec = int(val)
494
+ elif key == "custom_segment_text":
495
+ custom_segment_text = val
496
+ elif key == "git_show_state":
497
+ git_show_state = val.lower() in ("true", "1", "yes")
498
+ elif key == "battery_threshold" and val.isdigit():
499
+ battery_threshold = int(val)
500
+ elif key == "enable_command_on_new_line":
501
+ new_line = val.lower() in ("true", "1", "yes")
502
+ elif key == "enable_vertical_padding":
503
+ vertical_padding = val.lower() in ("true", "1", "yes")
504
+ elif key == "max_pwd_char" and val.isdigit():
505
+ max_pwd_char = int(val)
506
+ elif key == "max_git_char" and val.isdigit():
507
+ max_git_char = int(val)
508
+ elif key == "max_pyenv_char" and val.isdigit():
509
+ max_pyenv_char = int(val)
510
+ elif key == "max_kube_char" and val.isdigit():
511
+ max_kube_char = int(val)
512
+ elif key == "compact_width" and val.isdigit():
513
+ compact_width = int(val)
514
+ elif key == "git_show_counts":
515
+ git_show_counts = val.lower() in ("true", "1", "yes")
516
+ elif key == "transient_prompt":
517
+ transient_prompt = val.lower() in ("true", "1", "yes")
518
+ elif key == "synth_light_theme" and val:
519
+ light_theme = val
520
+ elif key == "synth_dark_theme" and val:
521
+ dark_theme = val
522
+ elif key == "prompt_prefix":
523
+ prompt_prefix = val
524
+ elif key == "font_effect_override" and val.lower() in VALID_FONT_EFFECTS:
525
+ font_effect = val.lower()
526
+ elif key == "enable_terminal_title":
527
+ enable_terminal_title = val.lower() in ("true", "1", "yes")
528
+ elif key == "git_skip_untracked_on_slow_fs":
529
+ git_skip_untracked_on_slow_fs = val.lower() in ("true", "1", "yes")
530
+ elif key == "git_timeout_ms" and val.isdigit():
531
+ git_timeout_ms = int(val)
532
+ elif key == "git_async_cache":
533
+ git_async_cache = val.lower() in ("true", "1", "yes")
534
+ elif key == "min_duration_ms" and val.isdigit():
535
+ min_duration_ms = int(val)
536
+ elif is_color_key(key):
537
+ colors[key] = val
538
+
539
+ segments_css: dict[str, dict[str, str | None]] = {}
540
+ for seg in SEGMENT_KEYS:
541
+ def_fg, def_bg = DEFAULT_SEGMENT_COLORS[seg]
542
+ fg_tok = colors.get(f"font_color_{seg}", def_fg)
543
+ bg_tok = colors.get(f"background_{seg}", def_bg)
544
+ segments_css[seg] = {
545
+ "fg": token_to_hex(fg_tok, "#ffffff"),
546
+ "bg": token_to_hex(bg_tok, None),
547
+ "fg_token": fg_tok,
548
+ "bg_token": bg_tok,
549
+ }
550
+
551
+ return {
552
+ "config_exists": cfg.is_file(),
553
+ "config_path": str(cfg),
554
+ "root_config_exists": get_root_config_path(base).is_file(),
555
+ "active_theme": active_name,
556
+ "active_theme_id": active_id,
557
+ "internal_separator": {
558
+ "glyph": int_glyph,
559
+ "code": int_code,
560
+ "key": get_separator_key(int_glyph),
561
+ },
562
+ "end_separator": {
563
+ "glyph": end_glyph,
564
+ "code": end_code,
565
+ "key": get_separator_key(end_glyph),
566
+ "explicit": end_tuple is not None,
567
+ },
568
+ "format": format_str,
569
+ "format_segments": format_str.split(),
570
+ "right_format": right_format_str,
571
+ "right_format_segments": right_format_str.split() if right_format_str else [],
572
+ "right_fill_char": right_fill_char,
573
+ "enable_osc133": enable_osc133,
574
+ "enable_osc7": enable_osc7,
575
+ "enable_terminal_sanitize": enable_terminal_sanitize,
576
+ "kube_show_namespace": kube_show_namespace,
577
+ "kube_prod_warning": kube_prod_warning,
578
+ "kube_prod_pattern": kube_prod_pattern,
579
+ "git_dynamic_color": git_dynamic_color,
580
+ "ssh_host_color": ssh_host_color,
581
+ "pwd_style": pwd_style,
582
+ "notify_duration_sec": notify_duration_sec,
583
+ "custom_segment_text": custom_segment_text,
584
+ "git_show_state": git_show_state,
585
+ "battery_threshold": battery_threshold,
586
+ "enable_command_on_new_line": new_line,
587
+ "enable_vertical_padding": vertical_padding,
588
+ "max_pwd_char": max_pwd_char,
589
+ "max_git_char": max_git_char,
590
+ "max_pyenv_char": max_pyenv_char,
591
+ "max_kube_char": max_kube_char,
592
+ "compact_width": compact_width,
593
+ "git_show_counts": git_show_counts,
594
+ "transient_prompt": transient_prompt,
595
+ "light_theme": light_theme,
596
+ "dark_theme": dark_theme,
597
+ "prompt_prefix": prompt_prefix,
598
+ "font_effect": font_effect,
599
+ "enable_terminal_title": enable_terminal_title,
600
+ "git_skip_untracked_on_slow_fs": git_skip_untracked_on_slow_fs,
601
+ "git_timeout_ms": git_timeout_ms,
602
+ "git_async_cache": git_async_cache,
603
+ "min_duration_ms": min_duration_ms,
604
+ "colors": colors,
605
+ "segments_css": segments_css,
606
+ "patches": inspect_patches(base),
607
+ }
608
+
609
+
610
+ def apply_theme(
611
+ theme: dict[str, object],
612
+ force_white: bool = False,
613
+ keep_input: bool = False,
614
+ create_backup: bool = True,
615
+ config_dir: Path | None = None,
616
+ ) -> dict[str, object]:
617
+ """Apply `theme` colors to `synth-shell-prompt.config` while preserving layout & separator settings."""
618
+ base = config_dir if config_dir is not None else get_config_dir()
619
+ cfg = get_config_path(base)
620
+
621
+ patch_state = inspect_patches(base)
622
+ if patch_state["prompt_script_found"] and not patch_state["color_256_parity"]:
623
+ apply_runtime_patches(base, tune_defaults=False)
624
+
625
+ bak = backup_config(base) if (create_backup and cfg.is_file()) else None
626
+
627
+ theme_id = int(theme.get("id", 0) or 0)
628
+ theme_title = str(theme.get("name") or theme.get("_name") or "Custom")
629
+ header_comment = (
630
+ f"# Theme {theme_id}: {theme_title}" if theme_id else f"# Theme: {theme_title}"
631
+ )
632
+ swatches = theme.get("swatch256")
633
+ swatch_comment = (
634
+ f"# swatch256: {' '.join(str(x) for x in swatches)}"
635
+ if isinstance(swatches, list) and swatches
636
+ else ""
637
+ )
638
+
639
+ theme_keys = {k for k in theme if is_color_key(k)}
640
+
641
+ if not cfg.is_file():
642
+ src_path = theme.get("_path")
643
+ if isinstance(src_path, Path) and src_path.is_file():
644
+ raw_lines = src_path.read_text(encoding="utf-8").splitlines()
645
+ else:
646
+ raw_lines = [
647
+ header_comment,
648
+ 'format="HOST PWD GIT PYENV TF KUBE"',
649
+ 'separator_char="\\uE0B4"',
650
+ 'separator_char_end="\\uE0B0"',
651
+ 'enable_vertical_padding="true"',
652
+ 'enable_command_on_new_line="true"',
653
+ 'max_pwd_char="35"',
654
+ "",
655
+ ] + [f'{k}="{theme[k]}"' for k in sorted(theme_keys)]
656
+
657
+ fresh_lines: list[str] = []
658
+ for line in raw_lines:
659
+ m = re.match(r"^(\w+)\s*=", line)
660
+ if m and m.group(1) in theme_keys:
661
+ key = m.group(1)
662
+ val = str(theme[key])
663
+ if force_white and key.startswith("font_color_") and key != "font_color_input":
664
+ val = "white"
665
+ fresh_lines.append(f'{key}="{val}"')
666
+ else:
667
+ fresh_lines.append(line)
668
+ _atomic_write(cfg, "\n".join(fresh_lines) + "\n")
669
+ return {
670
+ "theme": theme_title,
671
+ "theme_id": theme_id,
672
+ "backup": str(bak) if bak else None,
673
+ "config_path": str(cfg),
674
+ }
675
+
676
+ lines = cfg.read_text(encoding="utf-8", errors="replace").splitlines()
677
+ new_lines: list[str] = []
678
+ updated: set[str] = set()
679
+ first_comment_updated = False
680
+ swatch_comment_updated = False
681
+
682
+ for line in lines:
683
+ if line.startswith("# Theme") and not first_comment_updated:
684
+ new_lines.append(header_comment)
685
+ first_comment_updated = True
686
+ continue
687
+ if line.startswith("# swatch256:") and not swatch_comment_updated:
688
+ new_lines.append(swatch_comment or line)
689
+ swatch_comment_updated = True
690
+ continue
691
+
692
+ m = re.match(r"^(\w+)\s*=", line)
693
+ if m and m.group(1) in theme_keys:
694
+ key = m.group(1)
695
+ if keep_input and key == "font_color_input":
696
+ new_lines.append(line)
697
+ updated.add(key)
698
+ continue
699
+ val = str(theme[key])
700
+ if force_white and key.startswith("font_color_") and key != "font_color_input":
701
+ val = "white"
702
+ if "'" in line and '"' not in line:
703
+ new_lines.append(f"{key}='{val}'")
704
+ else:
705
+ new_lines.append(f'{key}="{val}"')
706
+ updated.add(key)
707
+ else:
708
+ new_lines.append(line)
709
+
710
+ if not first_comment_updated:
711
+ prefix = [header_comment]
712
+ if swatch_comment and not swatch_comment_updated:
713
+ prefix.append(swatch_comment)
714
+ new_lines = prefix + new_lines
715
+
716
+ missing = theme_keys - updated
717
+ if missing:
718
+ new_lines.append("")
719
+ for key in sorted(missing):
720
+ if keep_input and key == "font_color_input":
721
+ continue
722
+ val = str(theme[key])
723
+ if force_white and key.startswith("font_color_") and key != "font_color_input":
724
+ val = "white"
725
+ new_lines.append(f'{key}="{val}"')
726
+
727
+ _atomic_write(cfg, "\n".join(new_lines) + "\n")
728
+ return {
729
+ "theme": theme_title,
730
+ "theme_id": theme_id,
731
+ "backup": str(bak) if bak else None,
732
+ "config_path": str(cfg),
733
+ }
734
+
735
+
736
+ def apply_separators(
737
+ internal: tuple[str, str] | None = None,
738
+ end: tuple[str, str] | None = None,
739
+ create_backup: bool = True,
740
+ config_dir: Path | None = None,
741
+ ) -> dict[str, object]:
742
+ """Write internal (`separator_char`) and/or ending (`separator_char_end`) glyphs atomically."""
743
+ base = config_dir if config_dir is not None else get_config_dir()
744
+ cfg = get_config_path(base)
745
+
746
+ ensure_dual_separator_support(base)
747
+
748
+ if not cfg.is_file():
749
+ themes = load_themes()
750
+ apply_theme(themes[1] if len(themes) > 1 else themes[0], create_backup=False, config_dir=base)
751
+
752
+ bak = backup_config(base) if create_backup else None
753
+ lines = cfg.read_text(encoding="utf-8", errors="replace").splitlines()
754
+ new_lines: list[str] = []
755
+ found_main = False
756
+ found_end = False
757
+
758
+ for line in lines:
759
+ if re.match(r"^separator_char\s*=", line):
760
+ if internal is not None:
761
+ new_lines.append(format_separator_assignment("separator_char", internal[1]))
762
+ else:
763
+ new_lines.append(line)
764
+ found_main = True
765
+ elif re.match(r"^separator_char_end\s*=", line):
766
+ if end is not None:
767
+ new_lines.append(format_separator_assignment("separator_char_end", end[1]))
768
+ else:
769
+ new_lines.append(line)
770
+ found_end = True
771
+ else:
772
+ new_lines.append(line)
773
+
774
+ if not found_main and internal is not None:
775
+ new_lines.append(format_separator_assignment("separator_char", internal[1]))
776
+ if not found_end and end is not None:
777
+ new_lines.append(format_separator_assignment("separator_char_end", end[1]))
778
+
779
+ _atomic_write(cfg, "\n".join(new_lines) + "\n")
780
+ return {
781
+ "internal": {"glyph": internal[0], "code": internal[1]} if internal else None,
782
+ "end": {"glyph": end[0], "code": end[1]} if end else None,
783
+ "backup": str(bak) if bak else None,
784
+ "config_path": str(cfg),
785
+ }
786
+
787
+
788
+ def apply_layout_options(
789
+ format_str: str | None = None,
790
+ right_format_str: str | None = None,
791
+ right_fill_char: str | None = None,
792
+ enable_osc133: bool | None = None,
793
+ enable_osc7: bool | None = None,
794
+ enable_terminal_sanitize: bool | None = None,
795
+ kube_show_namespace: bool | None = None,
796
+ kube_prod_warning: bool | None = None,
797
+ kube_prod_pattern: str | None = None,
798
+ git_dynamic_color: bool | None = None,
799
+ ssh_host_color: bool | None = None,
800
+ pwd_style: str | None = None,
801
+ notify_duration_sec: int | None = None,
802
+ custom_segment_text: str | None = None,
803
+ git_show_state: bool | None = None,
804
+ battery_threshold: int | None = None,
805
+ new_line: bool | None = None,
806
+ vertical_padding: bool | None = None,
807
+ max_pwd_char: int | None = None,
808
+ max_git_char: int | None = None,
809
+ max_pyenv_char: int | None = None,
810
+ max_kube_char: int | None = None,
811
+ compact_width: int | None = None,
812
+ git_show_counts: bool | None = None,
813
+ transient_prompt: bool | None = None,
814
+ light_theme: str | None = None,
815
+ dark_theme: str | None = None,
816
+ prompt_prefix: str | None = None,
817
+ font_effect: str | None = None,
818
+ enable_terminal_title: bool | None = None,
819
+ git_skip_untracked_on_slow_fs: bool | None = None,
820
+ git_timeout_ms: int | None = None,
821
+ git_async_cache: bool | None = None,
822
+ min_duration_ms: int | None = None,
823
+ create_backup: bool = True,
824
+ config_dir: Path | None = None,
825
+ ) -> dict[str, object]:
826
+ """Update prompt layout, truncation, responsive width, prefix, text effect, titlebar, and Git/duration settings."""
827
+ base = config_dir if config_dir is not None else get_config_dir()
828
+ cfg = get_config_path(base)
829
+
830
+ if not cfg.is_file():
831
+ themes = load_themes(config_dir=base)
832
+ apply_theme(themes[1] if len(themes) > 1 else themes[0], create_backup=False, config_dir=base)
833
+
834
+ updates: dict[str, str] = {}
835
+ clean_format: str | None = None
836
+ if format_str is not None:
837
+ tokens = [t for t in format_str.upper().replace(",", " ").split() if t in VALID_FORMAT_TOKENS]
838
+ if tokens:
839
+ clean_format = " ".join(tokens)
840
+ updates["format"] = clean_format
841
+
842
+ clean_right_format: str | None = None
843
+ if right_format_str is not None:
844
+ rtokens = [t for t in right_format_str.upper().replace(",", " ").split() if t in VALID_FORMAT_TOKENS]
845
+ clean_right_format = " ".join(rtokens)
846
+ updates["right_format"] = clean_right_format
847
+ if right_fill_char is not None:
848
+ updates["right_fill_char"] = right_fill_char[:1] if right_fill_char else " "
849
+ if enable_osc133 is not None:
850
+ updates["enable_osc133"] = "true" if enable_osc133 else "false"
851
+ if enable_osc7 is not None:
852
+ updates["enable_osc7"] = "true" if enable_osc7 else "false"
853
+ if enable_terminal_sanitize is not None:
854
+ updates["enable_terminal_sanitize"] = "true" if enable_terminal_sanitize else "false"
855
+ if kube_show_namespace is not None:
856
+ updates["kube_show_namespace"] = "true" if kube_show_namespace else "false"
857
+ if kube_prod_warning is not None:
858
+ updates["kube_prod_warning"] = "true" if kube_prod_warning else "false"
859
+ if kube_prod_pattern is not None and kube_prod_pattern.strip():
860
+ updates["kube_prod_pattern"] = kube_prod_pattern.strip()
861
+ if git_dynamic_color is not None:
862
+ updates["git_dynamic_color"] = "true" if git_dynamic_color else "false"
863
+ if ssh_host_color is not None:
864
+ updates["ssh_host_color"] = "true" if ssh_host_color else "false"
865
+ if pwd_style is not None:
866
+ ps = pwd_style.strip().lower()
867
+ updates["pwd_style"] = ps if ps in ("default", "fish") else "default"
868
+ if notify_duration_sec is not None:
869
+ updates["notify_duration_sec"] = str(max(0, min(3600, int(notify_duration_sec))))
870
+ if custom_segment_text is not None:
871
+ updates["custom_segment_text"] = custom_segment_text
872
+ if git_show_state is not None:
873
+ updates["git_show_state"] = "true" if git_show_state else "false"
874
+ if battery_threshold is not None:
875
+ battery_threshold = max(5, min(100, int(battery_threshold)))
876
+ updates["battery_threshold"] = str(battery_threshold)
877
+
878
+ if new_line is not None:
879
+ updates["enable_command_on_new_line"] = "true" if new_line else "false"
880
+ if vertical_padding is not None:
881
+ updates["enable_vertical_padding"] = "true" if vertical_padding else "false"
882
+ if max_pwd_char is not None:
883
+ max_pwd_char = max(10, min(120, int(max_pwd_char)))
884
+ updates["max_pwd_char"] = str(max_pwd_char)
885
+ if max_git_char is not None:
886
+ max_git_char = max(0, min(80, int(max_git_char)))
887
+ updates["max_git_char"] = str(max_git_char)
888
+ if max_pyenv_char is not None:
889
+ max_pyenv_char = max(0, min(60, int(max_pyenv_char)))
890
+ updates["max_pyenv_char"] = str(max_pyenv_char)
891
+ if max_kube_char is not None:
892
+ max_kube_char = max(0, min(60, int(max_kube_char)))
893
+ updates["max_kube_char"] = str(max_kube_char)
894
+ if compact_width is not None:
895
+ compact_width = max(0, min(200, int(compact_width)))
896
+ updates["compact_width"] = str(compact_width)
897
+ if git_show_counts is not None:
898
+ updates["git_show_counts"] = "true" if git_show_counts else "false"
899
+ if transient_prompt is not None:
900
+ updates["transient_prompt"] = "true" if transient_prompt else "false"
901
+ if light_theme is not None and light_theme.strip():
902
+ updates["synth_light_theme"] = light_theme.strip()
903
+ if dark_theme is not None and dark_theme.strip():
904
+ updates["synth_dark_theme"] = dark_theme.strip()
905
+ if prompt_prefix is not None:
906
+ updates["prompt_prefix"] = prompt_prefix
907
+ if font_effect is not None:
908
+ eff = font_effect.strip().lower()
909
+ if eff not in VALID_FONT_EFFECTS:
910
+ raise ValueError(f"Invalid font effect '{font_effect}'. Expected one of: {', '.join(VALID_FONT_EFFECTS)}")
911
+ updates["font_effect_override"] = "" if eff == "bold" else ("none" if eff == "regular" else eff)
912
+ if enable_terminal_title is not None:
913
+ updates["enable_terminal_title"] = "true" if enable_terminal_title else "false"
914
+ if git_skip_untracked_on_slow_fs is not None:
915
+ updates["git_skip_untracked_on_slow_fs"] = "true" if git_skip_untracked_on_slow_fs else "false"
916
+ if git_timeout_ms is not None:
917
+ git_timeout_ms = max(0, min(10000, int(git_timeout_ms)))
918
+ updates["git_timeout_ms"] = str(git_timeout_ms)
919
+ if git_async_cache is not None:
920
+ updates["git_async_cache"] = "true" if git_async_cache else "false"
921
+ if min_duration_ms is not None:
922
+ min_duration_ms = max(100, min(60000, int(min_duration_ms)))
923
+ updates["min_duration_ms"] = str(min_duration_ms)
924
+
925
+ bak = backup_config(base) if (create_backup and updates) else None
926
+ if updates:
927
+ lines = cfg.read_text(encoding="utf-8", errors="replace").splitlines()
928
+ new_lines = _upsert_kv_lines(lines, updates)
929
+ _atomic_write(cfg, "\n".join(new_lines) + "\n")
930
+
931
+ return {
932
+ "format": clean_format,
933
+ "enable_command_on_new_line": new_line,
934
+ "enable_vertical_padding": vertical_padding,
935
+ "max_pwd_char": max_pwd_char,
936
+ "max_git_char": max_git_char,
937
+ "max_pyenv_char": max_pyenv_char,
938
+ "max_kube_char": max_kube_char,
939
+ "compact_width": compact_width,
940
+ "git_show_counts": git_show_counts,
941
+ "transient_prompt": transient_prompt,
942
+ "light_theme": light_theme,
943
+ "dark_theme": dark_theme,
944
+ "prompt_prefix": prompt_prefix,
945
+ "font_effect": font_effect,
946
+ "enable_terminal_title": enable_terminal_title,
947
+ "git_skip_untracked_on_slow_fs": git_skip_untracked_on_slow_fs,
948
+ "git_timeout_ms": git_timeout_ms,
949
+ "git_async_cache": git_async_cache,
950
+ "min_duration_ms": min_duration_ms,
951
+ "backup": str(bak) if bak else None,
952
+ "config_path": str(cfg),
953
+ }
954
+
955
+
956
+ def apply_ascii_safe_mode(
957
+ separator: str = ">",
958
+ create_backup: bool = True,
959
+ config_dir: Path | None = None,
960
+ ) -> dict[str, object]:
961
+ """Configure ASCII-safe separators and Git/truncation symbols for hosts without Nerd Fonts."""
962
+ base = config_dir if config_dir is not None else get_config_dir()
963
+ cfg = get_config_path(base)
964
+
965
+ if not cfg.is_file():
966
+ themes = load_themes()
967
+ apply_theme(themes[1] if len(themes) > 1 else themes[0], create_backup=False, config_dir=base)
968
+
969
+ bak = backup_config(base) if create_backup else None
970
+ sep_clean = separator if separator in (">", "|", "/", "»") else ">"
971
+ apply_separators(
972
+ internal=(sep_clean, sep_clean),
973
+ end=(sep_clean, sep_clean),
974
+ create_backup=False,
975
+ config_dir=base,
976
+ )
977
+ lines = cfg.read_text(encoding="utf-8", errors="replace").splitlines()
978
+ new_lines = _upsert_kv_lines(lines, ASCII_SAFE_GIT_SYMBOLS)
979
+ _atomic_write(cfg, "\n".join(new_lines) + "\n")
980
+ return {
981
+ "separator": sep_clean,
982
+ "symbols_updated": len(ASCII_SAFE_GIT_SYMBOLS),
983
+ "backup": str(bak) if bak else None,
984
+ "config_path": str(cfg),
985
+ }
986
+
987
+
988
+ def sync_root_config(
989
+ theme: dict[str, object] | None = None,
990
+ root_accent: str = "196",
991
+ config_dir: Path | None = None,
992
+ ) -> dict[str, object]:
993
+ """Generate/sync `synth-shell-prompt.root.config` matching active theme with a root warning accent."""
994
+ base = config_dir if config_dir is not None else get_config_dir()
995
+ root_cfg = get_root_config_path(base)
996
+ catalog = load_themes()
997
+ state = read_current_state(catalog, base)
998
+
999
+ if theme is None:
1000
+ active_id = state.get("active_theme_id")
1001
+ if isinstance(active_id, int) and 1 <= active_id <= len(catalog):
1002
+ theme = catalog[active_id - 1]
1003
+ else:
1004
+ tokyo, _ = find_theme("tokyo-night", catalog)
1005
+ theme = tokyo or catalog[0]
1006
+
1007
+ theme_title = str(theme.get("name", "Active Theme"))
1008
+ int_code = str(state["internal_separator"]["code"]) # type: ignore[index]
1009
+ end_code = str(state["end_separator"]["code"]) # type: ignore[index]
1010
+ fmt = str(state.get("format") or "USER HOST PWD GIT")
1011
+ if "USER" not in fmt.split():
1012
+ fmt = f"USER {fmt}"
1013
+
1014
+ lines = [
1015
+ f"# Root Prompt Sync — based on {theme_title} (synth-shell-theme)",
1016
+ f'format="{fmt}"',
1017
+ format_separator_assignment("separator_char", int_code),
1018
+ format_separator_assignment("separator_char_end", end_code),
1019
+ f'enable_vertical_padding="{"true" if state["enable_vertical_padding"] else "false"}"',
1020
+ f'enable_command_on_new_line="{"true" if state["enable_command_on_new_line"] else "false"}"',
1021
+ f'max_pwd_char="{state["max_pwd_char"]}"',
1022
+ "",
1023
+ "# High-visibility root warning accent on USER & HOST",
1024
+ 'font_color_user="white"',
1025
+ f'background_user="{root_accent}"',
1026
+ 'texteffect_user="bold"',
1027
+ 'font_color_host="white"',
1028
+ 'background_host="52"',
1029
+ 'texteffect_host="bold"',
1030
+ "",
1031
+ "# Remaining segments synced from active theme",
1032
+ ]
1033
+ for seg in ("pwd", "git", "pyenv", "tf", "kube", "clock", "status", "duration", "aws", "gcp", "docker", "node", "ssh"):
1034
+ def_fg, def_bg = DEFAULT_SEGMENT_COLORS[seg]
1035
+ fg = str(theme.get(f"font_color_{seg}", def_fg))
1036
+ bg = str(theme.get(f"background_{seg}", def_bg))
1037
+ lines.append(f'font_color_{seg}="{fg}"')
1038
+ lines.append(f'background_{seg}="{bg}"')
1039
+
1040
+ lines.extend(
1041
+ [
1042
+ f'font_color_input="{root_accent}"',
1043
+ 'background_input="none"',
1044
+ 'texteffect_input="bold"',
1045
+ ]
1046
+ )
1047
+ _atomic_write(root_cfg, "\n".join(lines) + "\n")
1048
+ return {
1049
+ "theme": theme_title,
1050
+ "root_accent": root_accent,
1051
+ "root_config_path": str(root_cfg),
1052
+ }
1053
+
1054
+
1055
+ def _system_has_swap() -> bool:
1056
+ """Return True if Linux `/proc/swaps` reports at least one active swap device."""
1057
+ swaps = Path("/proc/swaps")
1058
+ if not swaps.is_file():
1059
+ return True
1060
+ try:
1061
+ lines = [ln for ln in swaps.read_text(encoding="utf-8", errors="replace").splitlines() if ln.strip()]
1062
+ return len(lines) > 1
1063
+ except OSError:
1064
+ return True
1065
+
1066
+
1067
+ def read_greeter_state(config_dir: Path | None = None) -> dict[str, object]:
1068
+ """Read current `synth-shell-greeter.config` monitors and format accents."""
1069
+ base = config_dir if config_dir is not None else get_config_dir()
1070
+ gcfg = get_greeter_config_path(base)
1071
+ monitors = list(DEFAULT_GREETER_MONITORS)
1072
+ formats: dict[str, str] = {}
1073
+
1074
+ if gcfg.is_file():
1075
+ text = gcfg.read_text(encoding="utf-8", errors="replace")
1076
+ m_pi = re.search(r'print_info\s*=\s*"([^"]*)"', text, re.DOTALL)
1077
+ if m_pi:
1078
+ parsed = [tok.strip() for tok in m_pi.group(1).split() if tok.strip()]
1079
+ if parsed:
1080
+ monitors = parsed
1081
+ for key in ("format_info", "format_highlight", "format_crit", "format_deco", "format_ok", "format_error", "format_logo"):
1082
+ m_f = re.search(rf'^{key}\s*=\s*"([^"]*)"', text, re.MULTILINE)
1083
+ if m_f:
1084
+ formats[key] = " ".join(m_f.group(1).split())
1085
+
1086
+ return {
1087
+ "config_exists": gcfg.is_file(),
1088
+ "config_path": str(gcfg),
1089
+ "monitors": monitors,
1090
+ "available_monitors": list(GREETER_ALL_MONITORS),
1091
+ "formats": formats,
1092
+ "has_swap": _system_has_swap(),
1093
+ }
1094
+
1095
+
1096
+ def sync_greeter_theme(
1097
+ theme: dict[str, object] | None = None,
1098
+ monitors: list[str] | None = None,
1099
+ hide_swap_if_unavailable: bool = False,
1100
+ config_dir: Path | None = None,
1101
+ ) -> dict[str, object]:
1102
+ """Sync active prompt theme colors and/or monitor visibility into `synth-shell-greeter.config`."""
1103
+ base = config_dir if config_dir is not None else get_config_dir()
1104
+ gcfg = get_greeter_config_path(base)
1105
+ catalog = load_themes()
1106
+ state = read_current_state(catalog, base)
1107
+
1108
+ if theme is None:
1109
+ active_id = state.get("active_theme_id")
1110
+ if isinstance(active_id, int) and 1 <= active_id <= len(catalog):
1111
+ theme = catalog[active_id - 1]
1112
+ else:
1113
+ tokyo, _ = find_theme("tokyo-night", catalog)
1114
+ theme = tokyo or catalog[0]
1115
+
1116
+ theme_title = str(theme.get("name", "Active Theme"))
1117
+ accent_primary = str(theme.get("background_host") or "blue")
1118
+ accent_ok = str(theme.get("background_git") or "green")
1119
+ accent_deco = str(theme.get("font_color_input") or theme.get("background_pwd") or "white")
1120
+ accent_crit = str(theme.get("background_tf") or "208")
1121
+
1122
+ fmt_updates = {
1123
+ "format_info": "-c white",
1124
+ "format_highlight": f"-c {accent_primary} -e bold",
1125
+ "format_crit": f"-c {accent_crit} -e bold",
1126
+ "format_deco": f"-c {accent_deco} -e bold",
1127
+ "format_ok": f"-c {accent_ok} -e bold",
1128
+ "format_error": "-c 196 -e bold",
1129
+ "format_logo": f"-c {accent_primary} -e bold",
1130
+ }
1131
+
1132
+ current_greeter = read_greeter_state(base)
1133
+ final_monitors = list(monitors) if monitors is not None else list(current_greeter["monitors"]) # type: ignore[arg-type]
1134
+ if hide_swap_if_unavailable and not _system_has_swap():
1135
+ final_monitors = [m for m in final_monitors if not m.startswith("SWAP_MON")]
1136
+
1137
+ print_info_block = 'print_info="\n' + "\n".join(f"\t{m}" for m in final_monitors) + '\n"'
1138
+
1139
+ if gcfg.is_file():
1140
+ bdir = get_backup_dir(base)
1141
+ bdir.mkdir(parents=True, exist_ok=True)
1142
+ stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
1143
+ shutil.copy2(gcfg, bdir / f"{gcfg.name}.{stamp}.bak")
1144
+ text = gcfg.read_text(encoding="utf-8", errors="replace")
1145
+ if re.search(r'print_info\s*=\s*"[^"]*"', text, re.DOTALL):
1146
+ text = re.sub(r'print_info\s*=\s*"[^"]*"', lambda _: print_info_block, text, count=1, flags=re.DOTALL)
1147
+ else:
1148
+ text = text.rstrip() + "\n\n" + print_info_block + "\n"
1149
+ lines = _upsert_kv_lines(text.splitlines(), fmt_updates)
1150
+ _atomic_write(gcfg, "\n".join(lines) + "\n")
1151
+ else:
1152
+ header = [
1153
+ f"# Synth-Shell Greeter Config — synced with {theme_title} (synth-shell-theme)",
1154
+ "",
1155
+ print_info_block,
1156
+ "",
1157
+ ]
1158
+ for k, v in fmt_updates.items():
1159
+ header.append(f'{k}="{v}"')
1160
+ _atomic_write(gcfg, "\n".join(header) + "\n")
1161
+
1162
+ return {
1163
+ "theme": theme_title,
1164
+ "config_path": str(gcfg),
1165
+ "monitors": final_monitors,
1166
+ "formats": fmt_updates,
1167
+ }
1168
+
1169
+
1170
+ def export_preset(dest_path: Path, config_dir: Path | None = None) -> Path:
1171
+ """Export active colors, dual separators, layout, truncation, and speed options into a JSON preset."""
1172
+ state = read_current_state(config_dir=config_dir)
1173
+ payload = {
1174
+ "schema": "synth-shell-theme-preset/v2",
1175
+ "active_theme": state["active_theme"],
1176
+ "active_theme_id": state["active_theme_id"],
1177
+ "internal_separator": state["internal_separator"],
1178
+ "end_separator": state["end_separator"],
1179
+ "format": state["format"],
1180
+ "right_format": state["right_format"],
1181
+ "right_fill_char": state["right_fill_char"],
1182
+ "enable_osc133": state["enable_osc133"],
1183
+ "enable_osc7": state["enable_osc7"],
1184
+ "enable_terminal_sanitize": state["enable_terminal_sanitize"],
1185
+ "kube_show_namespace": state["kube_show_namespace"],
1186
+ "kube_prod_warning": state["kube_prod_warning"],
1187
+ "kube_prod_pattern": state["kube_prod_pattern"],
1188
+ "git_dynamic_color": state["git_dynamic_color"],
1189
+ "ssh_host_color": state["ssh_host_color"],
1190
+ "pwd_style": state["pwd_style"],
1191
+ "notify_duration_sec": state["notify_duration_sec"],
1192
+ "custom_segment_text": state["custom_segment_text"],
1193
+ "git_show_state": state["git_show_state"],
1194
+ "battery_threshold": state["battery_threshold"],
1195
+ "enable_command_on_new_line": state["enable_command_on_new_line"],
1196
+ "enable_vertical_padding": state["enable_vertical_padding"],
1197
+ "max_pwd_char": state["max_pwd_char"],
1198
+ "max_git_char": state["max_git_char"],
1199
+ "max_pyenv_char": state["max_pyenv_char"],
1200
+ "max_kube_char": state["max_kube_char"],
1201
+ "prompt_prefix": state["prompt_prefix"],
1202
+ "font_effect": state["font_effect"],
1203
+ "enable_terminal_title": state["enable_terminal_title"],
1204
+ "git_skip_untracked_on_slow_fs": state["git_skip_untracked_on_slow_fs"],
1205
+ "git_timeout_ms": state["git_timeout_ms"],
1206
+ "git_async_cache": state["git_async_cache"],
1207
+ "min_duration_ms": state["min_duration_ms"],
1208
+ "colors": state["colors"],
1209
+ }
1210
+ dest = Path(dest_path).expanduser()
1211
+ _atomic_write(dest, json.dumps(payload, indent=2, ensure_ascii=False) + "\n")
1212
+ return dest
1213
+
1214
+
1215
+ def import_preset(src_path: Path, config_dir: Path | None = None) -> dict[str, object]:
1216
+ """Import and apply a JSON preset file (supports both v1 and v2 schemas)."""
1217
+ base = config_dir if config_dir is not None else get_config_dir()
1218
+ src = Path(src_path).expanduser()
1219
+ data = json.loads(src.read_text(encoding="utf-8"))
1220
+ if not isinstance(data, dict):
1221
+ raise ValueError("Invalid preset JSON: expected a JSON object.")
1222
+
1223
+ bak = backup_config(base)
1224
+ colors = data.get("colors", {})
1225
+ if isinstance(colors, dict) and colors:
1226
+ pseudo_theme: dict[str, object] = {
1227
+ "id": data.get("active_theme_id") or 0,
1228
+ "name": data.get("active_theme") or src.stem,
1229
+ "_name": data.get("active_theme") or src.stem,
1230
+ }
1231
+ for k, v in colors.items():
1232
+ if is_color_key(str(k)):
1233
+ pseudo_theme[str(k)] = str(v)
1234
+ apply_theme(pseudo_theme, create_backup=False, config_dir=base)
1235
+ elif data.get("active_theme"):
1236
+ themes = load_themes()
1237
+ found, _ = find_theme(str(data["active_theme"]), themes)
1238
+ if found:
1239
+ apply_theme(found, create_backup=False, config_dir=base)
1240
+
1241
+ int_sep = data.get("internal_separator")
1242
+ end_sep = data.get("end_separator")
1243
+ int_tuple: tuple[str, str] | None = None
1244
+ end_tuple: tuple[str, str] | None = None
1245
+ if isinstance(int_sep, dict) and int_sep.get("code"):
1246
+ g, c, _ = resolve_separator_input(str(int_sep["code"]))
1247
+ int_tuple = (g, c)
1248
+ if isinstance(end_sep, dict) and end_sep.get("code"):
1249
+ g, c, _ = resolve_separator_input(str(end_sep["code"]))
1250
+ end_tuple = (g, c)
1251
+ if int_tuple or end_tuple:
1252
+ apply_separators(internal=int_tuple, end=end_tuple, create_backup=False, config_dir=base)
1253
+
1254
+ apply_layout_options(
1255
+ format_str=str(data["format"]) if "format" in data else None,
1256
+ right_format_str=str(data["right_format"]) if "right_format" in data else None,
1257
+ right_fill_char=str(data["right_fill_char"]) if "right_fill_char" in data else None,
1258
+ enable_osc133=bool(data["enable_osc133"]) if "enable_osc133" in data else None,
1259
+ enable_osc7=bool(data["enable_osc7"]) if "enable_osc7" in data else None,
1260
+ enable_terminal_sanitize=bool(data["enable_terminal_sanitize"]) if "enable_terminal_sanitize" in data else None,
1261
+ kube_show_namespace=bool(data["kube_show_namespace"]) if "kube_show_namespace" in data else None,
1262
+ kube_prod_warning=bool(data["kube_prod_warning"]) if "kube_prod_warning" in data else None,
1263
+ kube_prod_pattern=str(data["kube_prod_pattern"]) if "kube_prod_pattern" in data else None,
1264
+ git_dynamic_color=bool(data["git_dynamic_color"]) if "git_dynamic_color" in data else None,
1265
+ ssh_host_color=bool(data["ssh_host_color"]) if "ssh_host_color" in data else None,
1266
+ pwd_style=str(data["pwd_style"]) if "pwd_style" in data else None,
1267
+ notify_duration_sec=int(data["notify_duration_sec"]) if "notify_duration_sec" in data else None,
1268
+ custom_segment_text=str(data["custom_segment_text"]) if "custom_segment_text" in data else None,
1269
+ git_show_state=bool(data["git_show_state"]) if "git_show_state" in data else None,
1270
+ battery_threshold=int(data["battery_threshold"]) if "battery_threshold" in data else None,
1271
+ new_line=bool(data["enable_command_on_new_line"]) if "enable_command_on_new_line" in data else None,
1272
+ vertical_padding=bool(data["enable_vertical_padding"]) if "enable_vertical_padding" in data else None,
1273
+ max_pwd_char=int(data["max_pwd_char"]) if "max_pwd_char" in data else None,
1274
+ max_git_char=int(data["max_git_char"]) if "max_git_char" in data else None,
1275
+ max_pyenv_char=int(data["max_pyenv_char"]) if "max_pyenv_char" in data else None,
1276
+ max_kube_char=int(data["max_kube_char"]) if "max_kube_char" in data else None,
1277
+ compact_width=int(data["compact_width"]) if "compact_width" in data else None,
1278
+ git_show_counts=bool(data["git_show_counts"]) if "git_show_counts" in data else None,
1279
+ transient_prompt=bool(data["transient_prompt"]) if "transient_prompt" in data else None,
1280
+ light_theme=str(data["light_theme"]) if "light_theme" in data else None,
1281
+ dark_theme=str(data["dark_theme"]) if "dark_theme" in data else None,
1282
+ prompt_prefix=str(data["prompt_prefix"]) if "prompt_prefix" in data else None,
1283
+ font_effect=str(data["font_effect"]) if "font_effect" in data else None,
1284
+ enable_terminal_title=bool(data["enable_terminal_title"]) if "enable_terminal_title" in data else None,
1285
+ git_skip_untracked_on_slow_fs=(
1286
+ bool(data["git_skip_untracked_on_slow_fs"]) if "git_skip_untracked_on_slow_fs" in data else None
1287
+ ),
1288
+ git_timeout_ms=int(data["git_timeout_ms"]) if "git_timeout_ms" in data else None,
1289
+ git_async_cache=bool(data["git_async_cache"]) if "git_async_cache" in data else None,
1290
+ min_duration_ms=int(data["min_duration_ms"]) if "min_duration_ms" in data else None,
1291
+ create_backup=False,
1292
+ config_dir=base,
1293
+ )
1294
+ return {
1295
+ "imported_from": str(src),
1296
+ "backup": str(bak) if bak else None,
1297
+ "state": read_current_state(config_dir=base),
1298
+ }
1299
+
1300
+
1301
+ def toggle_light_dark_theme(
1302
+ light_slug: str | None = None,
1303
+ dark_slug: str | None = None,
1304
+ config_dir: Path | None = None,
1305
+ ) -> dict[str, object]:
1306
+ """Toggle between the configured Light and Dark theme pair in 1 command."""
1307
+ base = config_dir if config_dir is not None else get_config_dir()
1308
+ catalog = load_themes(config_dir=base)
1309
+ state = read_current_state(catalog, base)
1310
+
1311
+ light_choice = (light_slug or str(state.get("light_theme") or "catppuccin-latte")).strip()
1312
+ dark_choice = (dark_slug or str(state.get("dark_theme") or "tokyo-night")).strip()
1313
+
1314
+ light_t, _ = find_theme(light_choice, catalog)
1315
+ dark_t, _ = find_theme(dark_choice, catalog)
1316
+ if not light_t:
1317
+ raise ValueError(f"Light theme not found: {light_choice}")
1318
+ if not dark_t:
1319
+ raise ValueError(f"Dark theme not found: {dark_choice}")
1320
+
1321
+ active_name = str(state.get("active_theme") or "").lower()
1322
+ is_currently_light = (
1323
+ active_name == str(light_t.get("name", "")).lower()
1324
+ or "latte" in active_name
1325
+ or "light" in active_name
1326
+ )
1327
+ target_theme = dark_t if is_currently_light else light_t
1328
+ target_mode = "dark" if is_currently_light else "light"
1329
+
1330
+ res = apply_theme(target_theme, config_dir=base)
1331
+ apply_layout_options(
1332
+ light_theme=str(light_t.get("slug") or light_choice),
1333
+ dark_theme=str(dark_t.get("slug") or dark_choice),
1334
+ create_backup=False,
1335
+ config_dir=base,
1336
+ )
1337
+ return {
1338
+ "mode": target_mode,
1339
+ "theme": res["theme"],
1340
+ "theme_id": res["theme_id"],
1341
+ "light_theme": str(light_t.get("name")),
1342
+ "dark_theme": str(dark_t.get("name")),
1343
+ "backup": res["backup"],
1344
+ "config_path": res["config_path"],
1345
+ }
1346
+
1347
+
1348
+ def apply_auto_system_theme(
1349
+ light_theme: str | None = None,
1350
+ dark_theme: str | None = None,
1351
+ config_dir: Path | None = None,
1352
+ ) -> dict[str, object]:
1353
+ """Detect OS dark/light preference and apply the corresponding configured theme."""
1354
+ from synth_shell_theme.paths import detect_system_color_scheme
1355
+
1356
+ base = config_dir if config_dir is not None else get_config_dir()
1357
+ catalog = load_themes(config_dir=base)
1358
+ state = read_current_state(catalog, base)
1359
+
1360
+ scheme = detect_system_color_scheme()
1361
+ light_choice = light_theme or str(state.get("light_theme") or "catppuccin-latte")
1362
+ dark_choice = dark_theme or str(state.get("dark_theme") or "tokyo-night")
1363
+ target_slug = light_choice if scheme == "light" else dark_choice
1364
+ found, _ = find_theme(target_slug, catalog)
1365
+ target_theme = found or catalog[0]
1366
+
1367
+ res = apply_theme(target_theme, config_dir=base)
1368
+ return {
1369
+ "detected_scheme": scheme,
1370
+ "theme": res["theme"],
1371
+ "theme_id": res["theme_id"],
1372
+ "backup": res["backup"],
1373
+ "config_path": res["config_path"],
1374
+ }
1375
+
1376
+
1377
+ def benchmark_prompt(
1378
+ iterations: int = 15,
1379
+ config_dir: Path | None = None,
1380
+ cwd: Path | None = None,
1381
+ ) -> dict[str, object]:
1382
+ """Measure live Bash `prompt_command_hook` latency (min, p50, p95, max in ms)."""
1383
+ base = config_dir if config_dir is not None else get_config_dir()
1384
+ prompt_sh = get_prompt_script_path(base)
1385
+ runs = max(3, min(100, int(iterations)))
1386
+
1387
+ if not prompt_sh.is_file():
1388
+ return {
1389
+ "ok": False,
1390
+ "error": f"Prompt script not found: {prompt_sh}",
1391
+ "iterations": 0,
1392
+ "patches": inspect_patches(base),
1393
+ }
1394
+
1395
+ if shutil.which("bash") is None:
1396
+ return {
1397
+ "ok": False,
1398
+ "error": "Bash executable not found on PATH.",
1399
+ "iterations": 0,
1400
+ "patches": inspect_patches(base),
1401
+ }
1402
+
1403
+ probe = subprocess.run(["bash", "-c", "true"], capture_output=True, text=True, check=False)
1404
+ if probe.returncode != 0:
1405
+ return {
1406
+ "ok": False,
1407
+ "error": "Bash is unavailable on this host.",
1408
+ "iterations": 0,
1409
+ "patches": inspect_patches(base),
1410
+ }
1411
+
1412
+ raw_script = prompt_sh.read_text(encoding="utf-8", errors="replace")
1413
+ stripped = "\n".join(
1414
+ ln for ln in raw_script.splitlines() if "synth-shell-theme: interactive_guard" not in ln
1415
+ )
1416
+ # Replace the interactive source check at the bottom so benchmark can invoke synth_shell_prompt() cleanly
1417
+ stripped = re.sub(
1418
+ r'elif \[ -n "\$\( echo \$- \| grep i \)" \]; then',
1419
+ "elif true; then",
1420
+ stripped,
1421
+ )
1422
+
1423
+ with tempfile.TemporaryDirectory(prefix="synth-shell-bench-") as tmp:
1424
+ bench_sh = Path(tmp) / "bench_prompt.sh"
1425
+ bench_sh.write_text(stripped + "\n", encoding="utf-8", newline="\n")
1426
+ driver = (
1427
+ f'source "{bench_sh}" >/dev/null 2>&1; '
1428
+ 'declare -F prompt_command_hook >/dev/null 2>&1 || exit 2; '
1429
+ "prompt_command_hook; " # warm-up
1430
+ f"for ((i=0; i<{runs}; i++)); do "
1431
+ 't0="${EPOCHREALTIME:-}"; '
1432
+ "prompt_command_hook; "
1433
+ 't1="${EPOCHREALTIME:-}"; '
1434
+ 'if [[ -n "$t0" && -n "$t1" ]]; then '
1435
+ 'echo "$(( (${t1/./} - ${t0/./}) ))"; '
1436
+ "else echo 0; fi; "
1437
+ "done"
1438
+ )
1439
+ bench_env = dict(os.environ)
1440
+ if not bench_env.get("TERM") or bench_env.get("TERM") == "dumb":
1441
+ bench_env["TERM"] = "xterm-256color"
1442
+ t_wall0 = time.perf_counter()
1443
+ proc = subprocess.run(
1444
+ ["bash", "-c", driver],
1445
+ cwd=str(cwd) if cwd else None,
1446
+ env=bench_env,
1447
+ capture_output=True,
1448
+ text=True,
1449
+ timeout=25,
1450
+ check=False,
1451
+ )
1452
+ t_wall_ms = (time.perf_counter() - t_wall0) * 1000.0
1453
+
1454
+ if proc.returncode != 0:
1455
+ return {
1456
+ "ok": False,
1457
+ "error": (proc.stderr or "Failed to execute prompt_command_hook").strip(),
1458
+ "iterations": 0,
1459
+ "patches": inspect_patches(base),
1460
+ }
1461
+
1462
+ samples_ms: list[float] = []
1463
+ for ln in proc.stdout.splitlines():
1464
+ s = ln.strip()
1465
+ if s.isdigit() and int(s) > 0:
1466
+ samples_ms.append(int(s) / 1000.0)
1467
+
1468
+ if not samples_ms:
1469
+ per_run = round(t_wall_ms / runs, 2)
1470
+ samples_ms = [per_run] * runs
1471
+
1472
+ samples_ms.sort()
1473
+ p50 = round(statistics.median(samples_ms), 2)
1474
+ p95_idx = min(len(samples_ms) - 1, int(round(0.95 * (len(samples_ms) - 1))))
1475
+ p95 = round(samples_ms[p95_idx], 2)
1476
+
1477
+ return {
1478
+ "ok": True,
1479
+ "iterations": len(samples_ms),
1480
+ "min_ms": round(samples_ms[0], 2),
1481
+ "p50_ms": p50,
1482
+ "p95_ms": p95,
1483
+ "max_ms": round(samples_ms[-1], 2),
1484
+ "cwd": str(cwd or Path.cwd()),
1485
+ "patches": inspect_patches(base),
1486
+ }
1487
+
1488
+
1489
+ def generate_bash_completion(config_dir: Path | None = None) -> str:
1490
+ """Generate a self-contained Bash tab-completion script for `synth-shell-theme` & `synth-shell-separator`."""
1491
+ themes = load_themes(config_dir=config_dir)
1492
+ theme_slugs = " ".join(str(t.get("slug", "")) for t in themes if t.get("slug"))
1493
+ sep_keys = " ".join(key for key, *_ in ALL_PRESETS)
1494
+ seg_tokens = " ".join(VALID_FORMAT_TOKENS)
1495
+ effects = " ".join(VALID_FONT_EFFECTS)
1496
+
1497
+ return f"""# Bash completion for synth-shell-theme & synth-shell-separator
1498
+ # Activate with: eval "$(synth-shell-theme completion bash)"
1499
+ _synth_shell_theme_complete()
1500
+ {{
1501
+ local cur prev words cword
1502
+ cur="${{COMP_WORDS[COMP_CWORD]}}"
1503
+ prev="${{COMP_WORDS[COMP_CWORD-1]}}"
1504
+
1505
+ local subcmds="tui web studio sep init doctor bench export import import-theme export-web export-starship ssh-install completion"
1506
+ local opts="--version --list --current --apply --force-white-text --keep-input --separators --palette --separator --dual --internal --end --format --right-format --right-fill --osc133 --no-osc133 --osc7 --no-osc7 --terminal-sanitize --no-terminal-sanitize --kube-ns --no-kube-ns --kube-prod-warn --no-kube-prod-warn --kube-prod-pattern --git-dynamic-color --no-git-dynamic-color --ssh-host-color --no-ssh-host-color --pwd-style --notify-sec --custom-badge --git-state --no-git-state --battery-threshold --two-line --single-line --max-pwd --max-git --max-pyenv --max-kube --compact-width --prefix --text-effect --terminal-title --no-terminal-title --fast-git-wsl --no-fast-git-wsl --git-timeout --async-git --no-async-git --git-counts --no-git-counts --min-duration --transient --no-transient --ascii-safe --toggle-theme --auto-theme --light-theme --dark-theme --sync-root --sync-greeter --sync-ecosystem --greeter-monitors --hide-swap --random --search --web --port --no-browser --backup --backups --restore --no-clear"
1507
+ local themes="{theme_slugs}"
1508
+ local seps="{sep_keys}"
1509
+ local segs="{seg_tokens}"
1510
+ local effects="{effects}"
1511
+
1512
+ case "$prev" in
1513
+ -a|--apply|--light-theme|--dark-theme)
1514
+ COMPREPLY=( $(compgen -W "$themes" -- "$cur") )
1515
+ return 0
1516
+ ;;
1517
+ -t|--separator|-i|--internal|-e|--end|-d|--dual)
1518
+ COMPREPLY=( $(compgen -W "$seps" -- "$cur") )
1519
+ return 0
1520
+ ;;
1521
+ --text-effect)
1522
+ COMPREPLY=( $(compgen -W "$effects" -- "$cur") )
1523
+ return 0
1524
+ ;;
1525
+ --format)
1526
+ COMPREPLY=( $(compgen -W "$segs" -- "$cur") )
1527
+ return 0
1528
+ ;;
1529
+ completion)
1530
+ COMPREPLY=( $(compgen -W "bash" -- "$cur") )
1531
+ return 0
1532
+ ;;
1533
+ esac
1534
+
1535
+ if [[ "$COMP_CWORD" -eq 1 && "$cur" != -* ]]; then
1536
+ COMPREPLY=( $(compgen -W "$subcmds" -- "$cur") )
1537
+ return 0
1538
+ fi
1539
+ COMPREPLY=( $(compgen -W "$opts" -- "$cur") )
1540
+ }}
1541
+ complete -F _synth_shell_theme_complete synth-shell-theme synth-shell-separator
1542
+ """
1543
+
1544
+
1545
+ def doctor_fix(
1546
+ config_dir: Path | None = None,
1547
+ auto_ascii: bool = False,
1548
+ ) -> dict[str, object]:
1549
+ """Auto-repair common synth-shell issues: apply pending patches, fix CRLF line endings, optional ASCII fallback."""
1550
+ from synth_shell_theme.paths import detect_nerd_fonts, detect_utf8_locale
1551
+
1552
+ base = config_dir if config_dir is not None else get_config_dir()
1553
+ actions: list[str] = []
1554
+
1555
+ # 1. Normalize CRLF -> LF on managed shell scripts and configs
1556
+ for fname in (
1557
+ "synth-shell-prompt.sh",
1558
+ "synth-shell-prompt.config",
1559
+ "synth-shell-prompt.root.config",
1560
+ "alias.sh",
1561
+ "better-ls.sh",
1562
+ "better-history.sh",
1563
+ "synth-shell-greeter.sh",
1564
+ "synth-shell-greeter.config",
1565
+ ):
1566
+ fpath = base / fname
1567
+ if not fpath.is_file():
1568
+ continue
1569
+ raw = fpath.read_bytes()
1570
+ if b"\r\n" in raw:
1571
+ fpath.write_bytes(raw.replace(b"\r\n", b"\n"))
1572
+ actions.append(f"normalized_lf:{fname}")
1573
+
1574
+ # 2. Apply all missing runtime patches
1575
+ patch_res = apply_runtime_patches(config_dir=base, tune_defaults=False)
1576
+ for ch in patch_res["changes"]: # type: ignore[union-attr]
1577
+ actions.append(f"patch:{ch}")
1578
+
1579
+ # 3. Optional ASCII-safe fallback if locale is not UTF-8 or no Nerd Fonts detected
1580
+ loc = detect_utf8_locale()
1581
+ nf = detect_nerd_fonts()
1582
+ if auto_ascii and (not loc.get("utf8") or not nf.get("detected")):
1583
+ apply_ascii_safe_mode(config_dir=base)
1584
+ actions.append("applied:ascii_safe_fallback")
1585
+
1586
+ return {
1587
+ "actions": actions,
1588
+ "patches": patch_res["status"],
1589
+ "locale_utf8": bool(loc.get("utf8")),
1590
+ "nerd_fonts_detected": bool(nf.get("detected")),
1591
+ }
1592
+
1593
+
1594
+ def export_static_studio(dest_path: Path, config_dir: Path | None = None) -> Path:
1595
+ """Build a standalone static HTML demo of the Web Studio (ideal for GitHub Pages)."""
1596
+ from synth_shell_theme import __version__
1597
+ from synth_shell_theme.paths import get_assets_dir
1598
+ from synth_shell_theme.separators import serialize_separators_for_web
1599
+ from synth_shell_theme.themes import serialize_theme_for_web
1600
+
1601
+ studio_src = (get_assets_dir() / "studio.html").read_text(encoding="utf-8")
1602
+ catalog = load_themes(include_user_themes=False)
1603
+ serialized = [serialize_theme_for_web(t, idx) for idx, t in enumerate(catalog, 1)]
1604
+ static_boot = {
1605
+ "static_demo": True,
1606
+ "version": __version__,
1607
+ "themes": serialized,
1608
+ "separators": serialize_separators_for_web(),
1609
+ "valid_segments": list(VALID_FORMAT_TOKENS),
1610
+ "valid_font_effects": list(VALID_FONT_EFFECTS),
1611
+ "state": {
1612
+ "active_theme": "Tokyo Night",
1613
+ "active_theme_id": 12,
1614
+ "internal_separator": {"glyph": "\ue0b4", "code": "\\uE0B4", "key": "round"},
1615
+ "end_separator": {"glyph": "\ue0b0", "code": "\\uE0B0", "key": "arrow", "explicit": True},
1616
+ "format": "HOST PWD GIT PYENV TF",
1617
+ "format_segments": ["HOST", "PWD", "GIT", "PYENV", "TF"],
1618
+ "right_format": "KUBE DURATION CLOCK",
1619
+ "right_format_segments": ["KUBE", "DURATION", "CLOCK"],
1620
+ "right_fill_char": "─",
1621
+ "enable_osc133": True,
1622
+ "enable_osc7": True,
1623
+ "enable_terminal_sanitize": True,
1624
+ "kube_show_namespace": True,
1625
+ "kube_prod_warning": True,
1626
+ "kube_prod_pattern": "prod|production|prd|live",
1627
+ "git_dynamic_color": False,
1628
+ "ssh_host_color": False,
1629
+ "pwd_style": "default",
1630
+ "notify_duration_sec": 0,
1631
+ "custom_segment_text": "",
1632
+ "git_show_state": True,
1633
+ "battery_threshold": 100,
1634
+ "enable_command_on_new_line": True,
1635
+ "enable_vertical_padding": True,
1636
+ "max_pwd_char": 35,
1637
+ "max_git_char": 0,
1638
+ "max_pyenv_char": 0,
1639
+ "max_kube_char": 28,
1640
+ "compact_width": 90,
1641
+ "git_show_counts": True,
1642
+ "transient_prompt": False,
1643
+ "prompt_prefix": "",
1644
+ "font_effect": "bold",
1645
+ "enable_terminal_title": True,
1646
+ "git_skip_untracked_on_slow_fs": True,
1647
+ "git_timeout_ms": 0,
1648
+ "git_async_cache": False,
1649
+ "min_duration_ms": 2000,
1650
+ "root_config_exists": True,
1651
+ "patches": {
1652
+ "kube_fast": True,
1653
+ "kube_namespace_prod": True,
1654
+ "git_single_pass": True,
1655
+ "git_wsl_fast": True,
1656
+ "git_ahead_behind_counts": True,
1657
+ "git_advanced_state": True,
1658
+ "dual_separator": True,
1659
+ "color_256_parity": True,
1660
+ "truecolor_24bit": True,
1661
+ "zero_fork_render": True,
1662
+ "v11_segments": True,
1663
+ "v12_segments": True,
1664
+ "v13_segments": True,
1665
+ "osc133_semantic": True,
1666
+ "osc7_cwd": True,
1667
+ "v139_smart_features": True,
1668
+ "terminal_sanitize": True,
1669
+ "right_prompt": True,
1670
+ "responsive_width": True,
1671
+ "hook_chaining": True,
1672
+ "pyenv_enhanced": True,
1673
+ "utf8_ps1_guard": True,
1674
+ "interactive_guard": True,
1675
+ },
1676
+ },
1677
+ "greeter": {
1678
+ "config_exists": True,
1679
+ "monitors": list(DEFAULT_GREETER_MONITORS),
1680
+ "available_monitors": list(GREETER_ALL_MONITORS),
1681
+ "has_swap": True,
1682
+ },
1683
+ "diagnostics": {
1684
+ "locale": {"utf8": True, "effective": "en_US.UTF-8"},
1685
+ "nerd_fonts": {"detected": True, "count": 4, "samples": ["JetBrainsMono Nerd Font", "FiraCode Nerd Font"]},
1686
+ "terminal": {"term": "xterm-256color", "colorterm": "truecolor", "truecolor": True, "term_256": True},
1687
+ },
1688
+ "backups": [],
1689
+ }
1690
+ boot_json = json.dumps(static_boot, ensure_ascii=False).replace("</", "<\\/")
1691
+ inject = f"<script>window.__SYNTH_STATIC_BOOTSTRAP__ = {boot_json};</script>\n</head>"
1692
+ out_html = studio_src.replace("</head>", inject, 1)
1693
+ dest = Path(dest_path).expanduser()
1694
+ _atomic_write(dest, out_html)
1695
+ return dest