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,537 @@
1
+ """Ecosystem color sync (fzf, LS_COLORS, tmux, WezTerm), Starship export, SSH deploy & external palette importer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ import re
8
+ import shlex
9
+ import shutil
10
+ import subprocess
11
+ from pathlib import Path
12
+
13
+ from synth_shell_theme.paths import get_config_dir
14
+ from synth_shell_theme.themes import (
15
+ color_index,
16
+ find_theme,
17
+ load_themes,
18
+ normalize_hex_color,
19
+ save_custom_theme,
20
+ token_to_hex,
21
+ )
22
+
23
+
24
+ def _contrast_fg(hex_bg: str) -> str:
25
+ """Return `#000000` or `#ffffff` based on perceptual luminance of `hex_bg`."""
26
+ norm = normalize_hex_color(hex_bg) or "#222222"
27
+ r = int(norm[1:3], 16)
28
+ g = int(norm[3:5], 16)
29
+ b = int(norm[5:7], 16)
30
+ lum = 0.299 * r + 0.587 * g + 0.114 * b
31
+ return "black" if lum >= 140 else "white"
32
+
33
+
34
+ def sync_ecosystem(
35
+ theme: dict[str, object] | None = None,
36
+ config_dir: Path | None = None,
37
+ ) -> dict[str, object]:
38
+ """Generate `theme-env.sh` (`FZF_DEFAULT_OPTS` + `LS_COLORS`) and `tmux-theme.conf` matching active theme."""
39
+ from synth_shell_theme.core import _atomic_write, read_current_state
40
+
41
+ base = config_dir if config_dir is not None else get_config_dir()
42
+ catalog = load_themes(config_dir=base)
43
+ state = read_current_state(catalog, base)
44
+
45
+ if theme is None:
46
+ active_id = state.get("active_theme_id")
47
+ if isinstance(active_id, int) and 1 <= active_id <= len(catalog):
48
+ theme = catalog[active_id - 1]
49
+ else:
50
+ tokyo, _ = find_theme("tokyo-night", catalog)
51
+ theme = tokyo or catalog[0]
52
+
53
+ theme_name = str(theme.get("name", "Active Theme"))
54
+ host_bg = token_to_hex(str(theme.get("background_host", "237")), "#3b4261") or "#3b4261"
55
+ pwd_bg = token_to_hex(str(theme.get("background_pwd", "255")), "#7aa2f7") or "#7aa2f7"
56
+ git_bg = token_to_hex(str(theme.get("background_git", "71")), "#9ece6a") or "#9ece6a"
57
+ pyenv_bg = token_to_hex(str(theme.get("background_pyenv", "63")), "#bb9af7") or "#bb9af7"
58
+ tf_bg = token_to_hex(str(theme.get("background_tf", "228")), "#e0af68") or "#e0af68"
59
+ kube_bg = token_to_hex(str(theme.get("background_kube", "135")), "#7dcfff") or "#7dcfff"
60
+ input_fg = token_to_hex(str(theme.get("font_color_input", "white")), "#eef2f8") or "#eef2f8"
61
+
62
+ # 256-color indices for LS_COLORS compatibility across all terminals
63
+ i_dir = color_index(pwd_bg) or 75
64
+ i_exec = color_index(git_bg) or 114
65
+ i_link = color_index(kube_bg) or 117
66
+ i_arch = color_index(tf_bg) or 214
67
+ i_code = color_index(pyenv_bg) or 141
68
+
69
+ fzf_colors = (
70
+ f"bg+:{host_bg},fg+:{input_fg},"
71
+ f"hl:{tf_bg},hl+:{git_bg},"
72
+ f"info:{kube_bg},prompt:{pwd_bg},"
73
+ f"pointer:{pyenv_bg},marker:{git_bg},"
74
+ f"spinner:{tf_bg},header:{pwd_bg},border:{host_bg}"
75
+ )
76
+
77
+ ls_colors = (
78
+ f"di=1;38;5;{i_dir}:"
79
+ f"ln=1;38;5;{i_link}:"
80
+ f"ex=1;38;5;{i_exec}:"
81
+ f"*.py=38;5;{i_code}:*.sh=38;5;{i_exec}:*.json=38;5;{i_arch}:"
82
+ f"*.yaml=38;5;{i_arch}:*.yml=38;5;{i_arch}:*.md=38;5;{i_link}:"
83
+ f"*.tar=38;5;{i_arch}:*.gz=38;5;{i_arch}:*.zip=38;5;{i_arch}"
84
+ )
85
+
86
+ env_path = base / "theme-env.sh"
87
+ env_content = (
88
+ f"# Synth-Shell Ecosystem Theme Env — synced with {theme_name}\n"
89
+ f"# Add to ~/.bashrc: source ~/.config/synth-shell/theme-env.sh\n"
90
+ f'export FZF_DEFAULT_OPTS="${{FZF_DEFAULT_OPTS:+${{FZF_DEFAULT_OPTS}} }}--color={fzf_colors}"\n'
91
+ f'export LS_COLORS="{ls_colors}"\n'
92
+ )
93
+ _atomic_write(env_path, env_content)
94
+
95
+ tmux_path = base / "tmux-theme.conf"
96
+ tmux_fg_host = "#000000" if _contrast_fg(host_bg) == "black" else "#ffffff"
97
+ tmux_fg_pwd = "#000000" if _contrast_fg(pwd_bg) == "black" else "#ffffff"
98
+ tmux_content = (
99
+ f"# Synth-Shell tmux Theme — synced with {theme_name}\n"
100
+ f"# Add to ~/.tmux.conf: source-file ~/.config/synth-shell/tmux-theme.conf\n"
101
+ f'set -g status-style "bg=#12161f,fg={input_fg}"\n'
102
+ f'set -g status-left "#[bg={host_bg},fg={tmux_fg_host},bold] #S #[bg=#12161f,fg={host_bg}] "\n'
103
+ f'set -g status-right "#[fg={git_bg}]#[bg={git_bg},fg=#000000,bold] %H:%M "\n'
104
+ f'setw -g window-status-current-style "bg={pwd_bg},fg={tmux_fg_pwd},bold"\n'
105
+ f'setw -g window-status-current-format " #I:#W "\n'
106
+ f'set -g pane-active-border-style "fg={pwd_bg}"\n'
107
+ f'set -g pane-border-style "fg={host_bg}"\n'
108
+ )
109
+ _atomic_write(tmux_path, tmux_content)
110
+
111
+ wezterm_path = base / "wezterm-theme.lua"
112
+ status_bg = token_to_hex(str(theme.get("background_status", "196")), "#f7768e") or "#f7768e"
113
+ wezterm_content = (
114
+ f"-- Synth-Shell WezTerm Theme — synced with {theme_name}\n"
115
+ f"-- Add to ~/.wezterm.lua: config.colors = dofile(wezterm.home_dir .. '/.config/synth-shell/wezterm-theme.lua')\n"
116
+ f"return {{\n"
117
+ f' foreground = "{input_fg}",\n'
118
+ f' background = "#11151d",\n'
119
+ f' cursor_bg = "{pwd_bg}",\n'
120
+ f' cursor_fg = "{tmux_fg_pwd}",\n'
121
+ f' cursor_border = "{pwd_bg}",\n'
122
+ f' selection_bg = "{host_bg}",\n'
123
+ f' selection_fg = "{input_fg}",\n'
124
+ f" ansi = {{\n"
125
+ f' "{host_bg}", "{status_bg}", "{git_bg}", "{tf_bg}",\n'
126
+ f' "{pwd_bg}", "{pyenv_bg}", "{kube_bg}", "{input_fg}",\n'
127
+ f" }},\n"
128
+ f" brights = {{\n"
129
+ f' "{host_bg}", "{status_bg}", "{git_bg}", "{tf_bg}",\n'
130
+ f' "{pwd_bg}", "{pyenv_bg}", "{kube_bg}", "#ffffff",\n'
131
+ f" }},\n"
132
+ f" tab_bar = {{\n"
133
+ f' background = "#0b0e14",\n'
134
+ f' active_tab = {{ bg_color = "{pwd_bg}", fg_color = "{tmux_fg_pwd}", intensity = "Bold" }},\n'
135
+ f' inactive_tab = {{ bg_color = "{host_bg}", fg_color = "{tmux_fg_host}" }},\n'
136
+ f' new_tab = {{ bg_color = "#12161f", fg_color = "{input_fg}" }},\n'
137
+ f" }},\n"
138
+ f"}}\n"
139
+ )
140
+ _atomic_write(wezterm_path, wezterm_content)
141
+
142
+ return {
143
+ "theme": theme_name,
144
+ "env_script": str(env_path),
145
+ "tmux_conf": str(tmux_path),
146
+ "wezterm_lua": str(wezterm_path),
147
+ "fzf_colors": fzf_colors,
148
+ "ls_colors": ls_colors,
149
+ }
150
+
151
+
152
+ def export_starship_toml(
153
+ dest_path: Path,
154
+ theme: dict[str, object] | None = None,
155
+ config_dir: Path | None = None,
156
+ ) -> dict[str, object]:
157
+ """Export the active synth-shell theme & dual Powerline separators to a ready-to-use `starship.toml`."""
158
+ from synth_shell_theme.core import _atomic_write, read_current_state
159
+
160
+ base = config_dir if config_dir is not None else get_config_dir()
161
+ catalog = load_themes(config_dir=base)
162
+ state = read_current_state(catalog, base)
163
+
164
+ if theme is None:
165
+ active_id = state.get("active_theme_id")
166
+ if isinstance(active_id, int) and 1 <= active_id <= len(catalog):
167
+ theme = catalog[active_id - 1]
168
+ else:
169
+ tokyo, _ = find_theme("tokyo-night", catalog)
170
+ theme = tokyo or catalog[0]
171
+
172
+ theme_name = str(theme.get("name", "Active Theme"))
173
+ int_sep = str((state.get("internal_separator") or {}).get("glyph", "\ue0b4")) # type: ignore[union-attr]
174
+ end_sep = str((state.get("end_separator") or {}).get("glyph", "\ue0b0")) # type: ignore[union-attr]
175
+
176
+ def _hex(key: str, fb: str) -> str:
177
+ return token_to_hex(str(theme.get(key, fb)), fb) or fb # type: ignore[union-attr]
178
+
179
+ host_bg, host_fg = _hex("background_host", "#3b4261"), _hex("font_color_host", "#ffffff")
180
+ pwd_bg, pwd_fg = _hex("background_pwd", "#7aa2f7"), _hex("font_color_pwd", "#000000")
181
+ git_bg, git_fg = _hex("background_git", "#9ece6a"), _hex("font_color_git", "#000000")
182
+ py_bg, py_fg = _hex("background_pyenv", "#bb9af7"), _hex("font_color_pyenv", "#000000")
183
+ kube_bg, kube_fg = _hex("background_kube", "#7dcfff"), _hex("font_color_kube", "#000000")
184
+ dur_bg, dur_fg = _hex("background_duration", "#e0af68"), _hex("font_color_duration", "#000000")
185
+ input_fg = _hex("font_color_input", "#eef2f8")
186
+ nl = "\\n" if state.get("enable_command_on_new_line", True) else " "
187
+
188
+ toml = (
189
+ f"# Starship preset generated by synth-shell-theme — Theme: {theme_name}\n"
190
+ f'"$schema" = "https://starship.rs/config-schema.json"\n\n'
191
+ f'format = """\n'
192
+ f"$hostname\\\n"
193
+ f"[ {int_sep}](fg:{host_bg} bg:{pwd_bg})\\\n"
194
+ f"$directory\\\n"
195
+ f"[{int_sep}](fg:{pwd_bg} bg:{git_bg})\\\n"
196
+ f"$git_branch$git_status\\\n"
197
+ f"[{int_sep}](fg:{git_bg} bg:{py_bg})\\\n"
198
+ f"$python\\\n"
199
+ f"[{int_sep}](fg:{py_bg} bg:{kube_bg})\\\n"
200
+ f"$kubernetes\\\n"
201
+ f"[{end_sep}](fg:{kube_bg})\\\n"
202
+ f"{nl}$character\"\"\"\n\n"
203
+ f"[hostname]\n"
204
+ f"ssh_only = false\n"
205
+ f'style = "bg:{host_bg} fg:{host_fg} bold"\n'
206
+ f'format = "[ $hostname ]($style)"\n\n'
207
+ f"[directory]\n"
208
+ f'style = "bg:{pwd_bg} fg:{pwd_fg} bold"\n'
209
+ f'format = "[ $path ]($style)"\n'
210
+ f"truncation_length = 3\n\n"
211
+ f"[git_branch]\n"
212
+ f'style = "bg:{git_bg} fg:{git_fg} bold"\n'
213
+ f'format = "[ $symbol$branch ]($style)"\n\n'
214
+ f"[git_status]\n"
215
+ f'style = "bg:{git_bg} fg:{git_fg} bold"\n'
216
+ f'format = "[$all_status$ahead_behind ]($style)"\n\n'
217
+ f"[python]\n"
218
+ f'style = "bg:{py_bg} fg:{py_fg} bold"\n'
219
+ f'format = "[ $virtualenv ]($style)"\n\n'
220
+ f"[kubernetes]\n"
221
+ f"disabled = false\n"
222
+ f'style = "bg:{kube_bg} fg:{kube_fg} bold"\n'
223
+ f'format = "[ ☸ $context ($namespace) ]($style)"\n\n'
224
+ f"[cmd_duration]\n"
225
+ f"min_time = {int(state.get('min_duration_ms', 2000))}\n"
226
+ f'style = "bg:{dur_bg} fg:{dur_fg} bold"\n'
227
+ f'format = "[ ⏱ $duration ]($style)"\n\n'
228
+ f"[character]\n"
229
+ f'success_symbol = "[❯](bold {input_fg})"\n'
230
+ f'error_symbol = "[✗](bold #f7768e)"\n'
231
+ )
232
+ dest = Path(dest_path).expanduser()
233
+ _atomic_write(dest, toml)
234
+ return {"theme": theme_name, "dest": str(dest)}
235
+
236
+
237
+ def ssh_install_remote(
238
+ target: str,
239
+ ascii_safe: bool = False,
240
+ ssh_port: int | None = None,
241
+ ssh_host_color: bool = True,
242
+ dry_run: bool = False,
243
+ config_dir: Path | None = None,
244
+ ) -> dict[str, object]:
245
+ """Deploy the patched `synth-shell-prompt.sh` + active config to a remote host over SSH (zero Python/Git needed remotely)."""
246
+ from synth_shell_theme.paths import get_config_path, get_prompt_script_path
247
+
248
+ base = config_dir if config_dir is not None else get_config_dir()
249
+ prompt_sh = get_prompt_script_path(base)
250
+ cfg_path = get_config_path(base)
251
+ if not prompt_sh.is_file():
252
+ raise FileNotFoundError(f"Local prompt script not found: {prompt_sh} (run `synth-shell-theme init` first).")
253
+ if not cfg_path.is_file():
254
+ raise FileNotFoundError(f"Local prompt config not found: {cfg_path}.")
255
+
256
+ sh_bytes = prompt_sh.read_text(encoding="utf-8", errors="replace").replace("\r\n", "\n").encode("utf-8")
257
+ cfg_text = cfg_path.read_text(encoding="utf-8", errors="replace").replace("\r\n", "\n")
258
+
259
+ extra_lines: list[str] = []
260
+ if ssh_host_color and "ssh_host_color=" not in cfg_text:
261
+ extra_lines.append('ssh_host_color="true"')
262
+ if ascii_safe:
263
+ cfg_text = re.sub(r'^separator_char=.*$', 'separator_char=">"', cfg_text, flags=re.MULTILINE)
264
+ cfg_text = re.sub(r'^separator_char_end=.*$', 'separator_char_end=">"', cfg_text, flags=re.MULTILINE)
265
+ extra_lines.append('git_symbol_dirty=" *"')
266
+ if extra_lines:
267
+ cfg_text = cfg_text.rstrip() + "\n" + "\n".join(extra_lines) + "\n"
268
+ cfg_bytes = cfg_text.encode("utf-8")
269
+
270
+ b64_sh = base64.b64encode(sh_bytes).decode("ascii")
271
+ b64_cfg = base64.b64encode(cfg_bytes).decode("ascii")
272
+
273
+ remote_script = (
274
+ "set -e\n"
275
+ 'mkdir -p "$HOME/.config/synth-shell"\n'
276
+ f"printf '%s' {shlex.quote(b64_sh)} | base64 -d > \"$HOME/.config/synth-shell/synth-shell-prompt.sh\"\n"
277
+ f"printf '%s' {shlex.quote(b64_cfg)} | base64 -d > \"$HOME/.config/synth-shell/synth-shell-prompt.config\"\n"
278
+ 'chmod +x "$HOME/.config/synth-shell/synth-shell-prompt.sh"\n'
279
+ 'HOOK=\'if [ -f "$HOME/.config/synth-shell/synth-shell-prompt.sh" ] && [ -n "$( echo $- | grep i )" ]; then source "$HOME/.config/synth-shell/synth-shell-prompt.sh"; fi\'\n'
280
+ 'touch "$HOME/.bashrc"\n'
281
+ 'grep -q "synth-shell-prompt.sh" "$HOME/.bashrc" || printf "\\n# synth-shell-theme remote prompt\\n%s\\n" "$HOOK" >> "$HOME/.bashrc"\n'
282
+ 'echo "SYNTH_SSH_DEPLOY_OK"\n'
283
+ )
284
+
285
+ ssh_cmd = ["ssh"]
286
+ if ssh_port is not None:
287
+ ssh_cmd.extend(["-p", str(int(ssh_port))])
288
+ ssh_cmd.extend([target, "bash -s"])
289
+
290
+ if dry_run:
291
+ return {
292
+ "ok": True,
293
+ "dry_run": True,
294
+ "target": target,
295
+ "ssh_cmd": ssh_cmd,
296
+ "script_bytes": len(sh_bytes),
297
+ "config_bytes": len(cfg_bytes),
298
+ "ascii_safe": ascii_safe,
299
+ "ssh_host_color": ssh_host_color,
300
+ }
301
+
302
+ if not shutil.which("ssh"):
303
+ raise RuntimeError("`ssh` binary not found in PATH.")
304
+
305
+ res = subprocess.run(ssh_cmd, input=remote_script, capture_output=True, text=True, check=False)
306
+ if res.returncode != 0:
307
+ raise RuntimeError(f"SSH deploy failed (exit {res.returncode}): {res.stderr.strip() or res.stdout.strip()}")
308
+ return {
309
+ "ok": True,
310
+ "dry_run": False,
311
+ "target": target,
312
+ "script_bytes": len(sh_bytes),
313
+ "config_bytes": len(cfg_bytes),
314
+ "ascii_safe": ascii_safe,
315
+ "ssh_host_color": ssh_host_color,
316
+ }
317
+
318
+
319
+ def _extract_palette_from_pywal(path: Path) -> tuple[str, dict[str, str]]:
320
+ """Parse Pywal `~/.cache/wal/colors.json` or `colors.sh` into a 16-color map."""
321
+ text = path.read_text(encoding="utf-8", errors="replace")
322
+ colors: dict[str, str] = {}
323
+ name = "Pywal Wallpaper"
324
+ if path.suffix.lower() == ".json" or text.lstrip().startswith("{"):
325
+ data = json.loads(text)
326
+ wp = data.get("wallpaper")
327
+ if isinstance(wp, str) and wp.strip():
328
+ name = f"Pywal ({Path(wp).stem})"
329
+ cmap = data.get("colors", {})
330
+ if isinstance(cmap, dict):
331
+ for k, v in cmap.items():
332
+ hx = normalize_hex_color(str(v))
333
+ if hx:
334
+ colors[k.lower()] = hx
335
+ special = data.get("special", {})
336
+ if isinstance(special, dict):
337
+ for k in ("background", "foreground"):
338
+ hx = normalize_hex_color(str(special.get(k, "")))
339
+ if hx:
340
+ colors[k] = hx
341
+ else:
342
+ for m in re.finditer(r"^(color\d+|background|foreground)\s*=\s*['\"]?(#[0-9a-fA-F]{6})['\"]?", text, re.MULTILINE):
343
+ colors[m.group(1).lower()] = m.group(2).lower()
344
+ return name, colors
345
+
346
+
347
+ def _extract_palette_from_base16(text: str, stem: str) -> tuple[str, dict[str, str]]:
348
+ """Parse Base16 YAML (`base00:` .. `base0F:`) without external YAML dependencies."""
349
+ name = stem.replace("-", " ").replace("_", " ").title()
350
+ m_scheme = re.search(r'^scheme\s*:\s*["\']?([^"\'\n]+)["\']?', text, re.MULTILINE)
351
+ if m_scheme:
352
+ name = m_scheme.group(1).strip()
353
+
354
+ b: dict[str, str] = {}
355
+ for m in re.finditer(r'^(base0[0-9A-Fa-f])\s*:\s*["\']?#?([0-9a-fA-F]{6})["\']?', text, re.MULTILINE):
356
+ b[m.group(1).lower()] = f"#{m.group(2).lower()}"
357
+
358
+ if not b:
359
+ return name, {}
360
+
361
+ # Standard Base16 semantic mapping
362
+ return name, {
363
+ "background": b.get("base00", "#1a1b26"),
364
+ "foreground": b.get("base05", "#c0caf5"),
365
+ "color0": b.get("base01", b.get("base00", "#24283b")),
366
+ "color1": b.get("base08", "#f7768e"),
367
+ "color2": b.get("base0b", "#9ece6a"),
368
+ "color3": b.get("base0a", "#e0af68"),
369
+ "color4": b.get("base0d", "#7aa2f7"),
370
+ "color5": b.get("base0e", "#bb9af7"),
371
+ "color6": b.get("base0c", "#7dcfff"),
372
+ "color7": b.get("base05", "#c0caf5"),
373
+ "color8": b.get("base02", "#414868"),
374
+ }
375
+
376
+
377
+ def _extract_palette_from_windows_terminal(text: str, stem: str) -> tuple[str, dict[str, str]]:
378
+ data = json.loads(text)
379
+ if isinstance(data, dict) and isinstance(data.get("schemes"), list) and data["schemes"]:
380
+ data = data["schemes"][0]
381
+ if not isinstance(data, dict):
382
+ return stem, {}
383
+ name = str(data.get("name") or stem.replace("-", " ").title())
384
+ key_map = {
385
+ "background": "background",
386
+ "foreground": "foreground",
387
+ "black": "color0",
388
+ "red": "color1",
389
+ "green": "color2",
390
+ "yellow": "color3",
391
+ "blue": "color4",
392
+ "purple": "color5",
393
+ "cyan": "color6",
394
+ "white": "color7",
395
+ "brightBlack": "color8",
396
+ "brightBlue": "color12",
397
+ }
398
+ colors: dict[str, str] = {}
399
+ for src_k, dst_k in key_map.items():
400
+ hx = normalize_hex_color(str(data.get(src_k, "")))
401
+ if hx:
402
+ colors[dst_k] = hx
403
+ return name, colors
404
+
405
+
406
+ def _extract_palette_from_terminal_conf(text: str, stem: str) -> tuple[str, dict[str, str]]:
407
+ """Parse Ghostty (`palette = N=#hex`), Kitty (`colorN #hex`), and Alacritty TOML/YAML color configs."""
408
+ name = stem.replace("-", " ").replace("_", " ").title()
409
+ colors: dict[str, str] = {}
410
+
411
+ # Ghostty: palette = 4=#7aa2f7
412
+ for m in re.finditer(r"^\s*palette\s*=\s*(\d+)\s*=\s*(#[0-9a-fA-F]{6})", text, re.MULTILINE):
413
+ colors[f"color{m.group(1)}"] = m.group(2).lower()
414
+
415
+ # Kitty: color4 #7aa2f7 / background #1a1b26
416
+ for m in re.finditer(r"^\s*(color\d+|background|foreground)\s*[=:]?\s*['\"]?(#[0-9a-fA-F]{6})['\"]?", text, re.MULTILINE):
417
+ colors[m.group(1).lower()] = m.group(2).lower()
418
+
419
+ # Alacritty TOML/YAML named keys: blue = "#7aa2f7" or blue: '0x7aa2f7'
420
+ name_map = {
421
+ "black": "color0",
422
+ "red": "color1",
423
+ "green": "color2",
424
+ "yellow": "color3",
425
+ "blue": "color4",
426
+ "magenta": "color5",
427
+ "cyan": "color6",
428
+ "white": "color7",
429
+ }
430
+ for key_name, dst in name_map.items():
431
+ if dst in colors:
432
+ continue
433
+ m = re.search(rf"^\s*{key_name}\s*[=:]\s*['\"]?(?:#|0x)([0-9a-fA-F]{{6}})['\"]?", text, re.MULTILINE)
434
+ if m:
435
+ colors[dst] = f"#{m.group(1).lower()}"
436
+
437
+ return name, colors
438
+
439
+
440
+ def import_external_theme(
441
+ source_path: Path | None = None,
442
+ *,
443
+ from_pywal: bool = False,
444
+ custom_name: str | None = None,
445
+ apply_now: bool = True,
446
+ config_dir: Path | None = None,
447
+ ) -> dict[str, object]:
448
+ """Import a palette from Pywal, Base16 YAML, Ghostty, Kitty, Alacritty, or Windows Terminal JSON."""
449
+ from synth_shell_theme.core import apply_theme
450
+
451
+ base = config_dir if config_dir is not None else get_config_dir()
452
+ if from_pywal:
453
+ candidates = [
454
+ source_path if source_path is not None else Path.home() / ".cache" / "wal" / "colors.json",
455
+ Path.home() / ".cache" / "wal" / "colors.sh",
456
+ ]
457
+ target = next((p for p in candidates if p.is_file()), None)
458
+ if target is None:
459
+ raise FileNotFoundError("Pywal cache not found (~/.cache/wal/colors.json or colors.sh).")
460
+ inferred_name, pal = _extract_palette_from_pywal(target)
461
+ src_fmt = "pywal"
462
+ else:
463
+ if source_path is None or not Path(source_path).expanduser().is_file():
464
+ raise FileNotFoundError(f"Palette file not found: {source_path}")
465
+ target = Path(source_path).expanduser()
466
+ text = target.read_text(encoding="utf-8", errors="replace")
467
+ stem = target.stem
468
+ if re.search(r"^base0[0-9a-fA-F]\s*:", text, re.MULTILINE):
469
+ inferred_name, pal = _extract_palette_from_base16(text, stem)
470
+ src_fmt = "base16"
471
+ elif target.suffix.lower() == ".json" or text.lstrip().startswith("{"):
472
+ try:
473
+ parsed_json = json.loads(text)
474
+ except json.JSONDecodeError:
475
+ parsed_json = {}
476
+ if isinstance(parsed_json, dict) and "colors" in parsed_json and "special" in parsed_json:
477
+ inferred_name, pal = _extract_palette_from_pywal(target)
478
+ src_fmt = "pywal"
479
+ else:
480
+ inferred_name, pal = _extract_palette_from_windows_terminal(text, stem)
481
+ src_fmt = "windows-terminal"
482
+ else:
483
+ inferred_name, pal = _extract_palette_from_terminal_conf(text, stem)
484
+ src_fmt = "terminal-conf"
485
+
486
+ if len(pal) < 3:
487
+ raise ValueError(f"Could not extract enough colors from {target} (detected format: {src_fmt}).")
488
+
489
+ host_bg = pal.get("color8") or pal.get("color0") or pal.get("background") or "#2a2e3f"
490
+ pwd_bg = pal.get("color4") or pal.get("color12") or "#7aa2f7"
491
+ git_bg = pal.get("color2") or "#9ece6a"
492
+ pyenv_bg = pal.get("color5") or "#bb9af7"
493
+ tf_bg = pal.get("color3") or "#e0af68"
494
+ kube_bg = pal.get("color6") or "#7dcfff"
495
+ status_bg = pal.get("color1") or "#f7768e"
496
+ input_fg = pal.get("foreground") or pal.get("color7") or "#eef2f8"
497
+
498
+ segment_colors = {
499
+ "font_color_user": _contrast_fg(pwd_bg),
500
+ "background_user": pwd_bg,
501
+ "font_color_host": _contrast_fg(host_bg),
502
+ "background_host": host_bg,
503
+ "font_color_pwd": _contrast_fg(pwd_bg),
504
+ "background_pwd": pwd_bg,
505
+ "font_color_git": _contrast_fg(git_bg),
506
+ "background_git": git_bg,
507
+ "font_color_pyenv": _contrast_fg(pyenv_bg),
508
+ "background_pyenv": pyenv_bg,
509
+ "font_color_tf": _contrast_fg(tf_bg),
510
+ "background_tf": tf_bg,
511
+ "font_color_kube": _contrast_fg(kube_bg),
512
+ "background_kube": kube_bg,
513
+ "font_color_status": _contrast_fg(status_bg),
514
+ "background_status": status_bg,
515
+ "font_color_input": input_fg,
516
+ "background_input": "none",
517
+ }
518
+
519
+ final_name = (custom_name or inferred_name).strip()
520
+ saved = save_custom_theme(
521
+ name=final_name,
522
+ colors=segment_colors,
523
+ description=f"Imported from {src_fmt} ({target.name}).",
524
+ badge=src_fmt.capitalize(),
525
+ config_dir=base,
526
+ )
527
+ if apply_now:
528
+ apply_theme(saved, config_dir=base)
529
+
530
+ return {
531
+ "format": src_fmt,
532
+ "source": str(target),
533
+ "theme": saved["name"],
534
+ "slug": saved["slug"],
535
+ "saved_path": str(saved["_path"]),
536
+ "applied": apply_now,
537
+ }