termux: nugu theme
e414b5d87335588a0012665f9e2e0740751a5349
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: ab5c7708c4f3
bugabingas dorkfiles
e414b5d87335588a0012665f9e2e0740751a5349
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+414 / −1 text lines
+14 / −0 text lines
[tasks.nugu-termux]description = "Generate both Nugu Termux palettes without selecting a mode"run = '''cd("nugu");run("just", "--shell", "nu", "--clear-shell-args", "--shell-arg=--no-config-file", "--shell-arg=--commands", "termux");'''[tasks.termux-test]description = "Test Nugu Termux generation and manual theme switching"run = '''run("nu", "--no-config-file", "-c", "for file in [nugu/termux.nu nushell/modules/termux-theme.nu] { if not (nu-check --as-module $file) { error make {msg: $'Parse failed: ($file)'} } }");run("node", "--test", "termux/theme.test.mjs");'''+9 / −0 text lines
## Termux`base.toml` → `nugu.nu` → `termux.nu` → `output/termux/nugu-{dark,light}.properties`.Run `mise run nugu-termux` from the dotfiles root to generate both variants into `../termux/themes/`.Generation does not select a theme.The Nushell command `termux-theme dark` or `termux-theme light` selects one manually and reloads Termux.See [Termux setup and recovery](../termux/README.md).Validate generation and switching with `mise run termux-test` from the dotfiles root.+11 / −1 text lines
open termux.nu | nu-check --as-module --debug termux.nu# Generate both modes without changing Termux's active colors.properties.termux: mkdir {{output}}/termux use termux.nu; termux theme dark | save --force --raw {{output}}/termux/nugu-dark.properties use termux.nu; termux theme light | save --force --raw {{output}}/termux/nugu-light.properties mkdir ../termux/themes cp {{output}}/termux/nugu-dark.properties ../termux/themes/nugu-dark.properties cp {{output}}/termux/nugu-light.properties ../termux/themes/nugu-light.propertiesnew file mode 100644+46 / −0 text lines
use nugu.nu# Match WezTerm's Nugu mapping, using only Termux-supported properties.export def theme [mode: string] { let p = (match $mode { dark => (nugu dark) light => (nugu light) _ => { error make {msg: "Expected dark or light"} } } | get palette) let colors = [ $p.content.backdrop $p.error $p.content.focus $p.warning $p.content.important_local $p.content.accent $p.info $p.content.normal $p.content.minor $p.error $p.ui.focus $p.warning $p.content.important_global $p.ui.accent $p.ui.important_local $p.ui.important_global # Nugu semantic extras, indexed 16-22. $p.debug $p.ui.normal $p.ui.backdrop $p.ui.minor $p.ui.focus $p.ui.unfocus $p.content.unfocus ] [ "# Generated by nugu/termux.nu. Do not edit." $"foreground=($p.content.normal)" $"background=($p.content.backdrop)" $"cursor=($p.ui.accent)" ...($colors | enumerate | each {|c| $"color($c.index)=($c.item)" }) "" ] | str join (char nl)}+1 / −0 text lines
new file mode 100644+42 / −0 text lines
# Resolve the module itself first because ~/.config/nushell is a symlink.const themes = (path self | path expand | path dirname | path join ".." ".." "termux" "themes" | path expand)def modes [] { [dark light] }# Select a generated Nugu palette and reload Termux without restarting sessions.export def main [mode: string@modes] { if $mode not-in [dark light] { error make {msg: "Expected dark or light"} } if ($env.TERMUX_VERSION? | is-empty) or (which termux-reload-settings | is-empty) { error make {msg: "Run termux-theme inside Termux with termux-reload-settings available"} } let source = ($themes | path join $"nugu-($mode).properties") # Read before touching the active configuration, failing on missing palettes. let colors = (open --raw $source) let directory = ($nu.home-dir | path join ".termux") let active = ($directory | path join "colors.properties") let backup = ($directory | path join "colors.properties.before-nugu") # Do not follow links into managed palettes or outside HOME. if ($directory | path type) not-in [null dir] { error make {msg: "~/.termux must be a regular directory, not a symlink"} } for file in [$active $backup] { if ($file | path type) not-in [null file] { error make {msg: $"Refusing non-regular file: ($file)"} } } mkdir $directory if ($active | path exists) and not ($backup | path exists) { cp --preserve [mode timestamps] $active $backup } $colors | save --raw --force $active let result = (^termux-reload-settings | complete) if $result.exit_code != 0 { error make {msg: $"Nugu ($mode) saved, but Termux reload failed with exit code ($result.exit_code)"} } print $"Termux: Nugu ($mode)"}new file mode 100644+50 / −0 text lines
# Termux Nugu themes`nugu/termux.nu` generates dark and light palettes from `nugu/nugu.nu` and `nugu/base.toml`.Foreground, background, cursor, ANSI colors, and indexed colors 16-22 match WezTerm's Nugu mapping.Only properties supported by Termux are emitted; WezTerm's selection and window styling are not portable.From the dotfiles root:```shmise run nugu-termuxmise run termux-test```Generation writes both variants to `nugu/output/termux/` and `termux/themes/` without selecting an active theme.The command reads the tracked palettes relative to its module, so no new HOME symlink is needed.## Manual selection`nushell/login.nu` loads `nushell/modules/termux-theme.nu` in new login shells.For an already-running Nushell, import it once:```nuuse ~/.config/nushell/modules/termux-theme.nu```Choose a palette:```nutermux-theme darktermux-theme light```The command copies the selected palette into `~/.termux/colors.properties` and runs `termux-reload-settings`.It requires Termux and its existing reload command, not an extra APK.There is no schedule, background process, startup selection, or system-theme integration.Keyboard settings, font, fullscreen, and app UI settings remain untouched.## Backup and recoveryBefore the first switch, an existing palette is copied to `~/.termux/colors.properties.before-nugu`.Later switches preserve that backup.If reload fails, the command reports failure, but the selected palette remains saved.Symlinked settings directories, active palettes, and backups are refused rather than modifying their targets.To restore the original palette, if the backup exists:```nucp ~/.termux/colors.properties.before-nugu ~/.termux/colors.propertiestermux-reload-settings```new file mode 100644+187 / −0 text lines
import assert from "node:assert/strict";import { spawnSync } from "node:child_process";import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";import test from "node:test";const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");const justArgs = ["--shell", "nu", "--clear-shell-args", "--shell-arg=--no-config-file", "--shell-arg=--commands", "termux"];function run(command, args, options = {}) { const result = spawnSync(command, args, { encoding: "utf8", timeout: 120_000, ...options }); assert.equal(result.error, undefined); return result;}function success(result) { assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`); return result.stdout;}function failure(result, message) { assert.notEqual(result.status, 0); assert.match(result.stderr, message);}const nu = success(run("nu", ["--no-config-file", "-c", "$nu.current-exe"])).trim();function weztermColors(palette) { const lua = readFileSync(join(root, "wezterm/bugabinga/nugu/init.lua"), "utf8"); const lookup = (role) => role.split(".").reduce((value, key) => value[key], palette); const result = {}; for (const [termux, wezterm] of [["foreground", "foreground"], ["background", "background"], ["cursor", "cursor_bg"]]) { result[termux] = lookup(lua.match(new RegExp(`\\b${wezterm} = palette\\.([\\w.]+),`))[1]); } for (const [section, offset, count] of [["ansi", 0, 8], ["brights", 8, 8], ["indexed", 16, 7]]) { const body = lua.match(new RegExp(`\\b${section} = \\{([\\s\\S]*?)\\},`))[1]; const roles = [...body.matchAll(/palette\.([\w.]+),/g)].map((match) => match[1]); assert.equal(roles.length, count); roles.forEach((role, index) => { result[`color${offset + index}`] = lookup(role); }); } return result;}test("Termux palettes and manual switching", async (t) => { const workspace = mkdtempSync(join(tmpdir(), "termux-theme-test-")); t.after(() => rmSync(workspace, { recursive: true, force: true })); const nugu = join(workspace, "nugu"); const modules = join(workspace, "nushell/modules"); const home = join(workspace, "home"); const settings = join(home, ".termux"); const bin = join(workspace, "bin"); for (const directory of [nugu, modules, settings, bin, join(home, ".config")]) mkdirSync(directory, { recursive: true }); for (const file of ["base.toml", "nugu.nu", "termux.nu", "justfile"]) cpSync(join(root, "nugu", file), join(nugu, file)); cpSync(join(root, "nushell/modules/termux-theme.nu"), join(modules, "termux-theme.nu")); symlinkSync(join(workspace, "nushell"), join(home, ".config/nushell"), "junction"); const module = join(home, ".config/nushell/modules/termux-theme.nu"); const active = join(settings, "colors.properties"); const backup = `${active}.before-nugu`; const keyboard = join(settings, "termux.properties"); const log = join(workspace, "reload.log"); const original = "# original palette\nbackground=#20201d\n"; writeFileSync(active, original); writeFileSync(keyboard, "extra-keys = []\nfullscreen = true\n"); const env = { ...process.env, HOME: home, USERPROFILE: home, TERMUX_VERSION: "test", PATH: bin, RELOAD_LOG: log }; const invoke = (mode, extraEnv = {}) => run(nu, ["--no-config-file", "-c", `use ${JSON.stringify(module)}; termux-theme ${mode}`], { cwd: home, env: { ...env, ...extraEnv } }); const themes = {}; await t.test("generate both variants from source, matching WezTerm, without selecting a mode", () => { success(run("just", justArgs, { cwd: nugu })); assert.equal(readFileSync(active, "utf8"), original); assert.equal(existsSync(backup), false); assert.equal(existsSync(join(workspace, "termux/colors.properties")), false); for (const mode of ["dark", "light"]) { const filename = `nugu-${mode}.properties`; const text = readFileSync(join(nugu, "output/termux", filename), "utf8"); themes[mode] = text; assert.equal(readFileSync(join(workspace, "termux/themes", filename), "utf8"), text); assert.equal(readFileSync(join(root, "termux/themes", filename), "utf8"), text); const lines = text.trim().split(/\r?\n/).filter((line) => !line.startsWith("#")); for (const line of lines) assert.match(line, /^(foreground|background|cursor|color\d+)=#[0-9a-f]{6}$/); const properties = Object.fromEntries(lines.map((line) => line.split("="))); assert.equal(Object.keys(properties).length, lines.length, "no duplicate properties"); const palette = JSON.parse(success(run(nu, ["--no-config-file", "-c", `use nugu.nu; nugu ${mode} | get palette | to json`], { cwd: nugu }))); assert.deepEqual(properties, weztermColors(palette)); } assert.notEqual(themes.dark, themes.light); failure(run(nu, ["--no-config-file", "-c", "use termux.nu; termux theme invalid"], { cwd: nugu }), /Expected dark or light/); }); await t.test("login.nu loads the command without a config.nu import", () => { const login = readFileSync(join(root, "nushell/login.nu"), "utf8"); const imports = login.match(/^use termux-theme\.nu$/gm); assert.equal(imports?.length, 1); assert.doesNotMatch(readFileSync(join(root, "nushell/config.nu"), "utf8"), /^use termux-theme\.nu$/m); const code = `const NU_LIB_DIRS = [${JSON.stringify(join(home, ".config/nushell/modules"))}]; ${imports[0]}; help termux-theme`; assert.match(success(run(nu, ["--no-config-file", "-c", code], { env })), /termux-theme/); assert.equal(existsSync(log), false); }); await t.test("invalid modes and missing Termux support do not write anything", () => { failure(invoke("invalid"), /Expected dark or light/); failure(invoke("dark"), /inside Termux/); assert.equal(readFileSync(active, "utf8"), original); assert.equal(existsSync(backup), false); }); const fake = join(bin, "reload.cjs"); writeFileSync(fake, 'require("node:fs").appendFileSync(process.env.RELOAD_LOG, "reload\\n"); process.exit(Number(process.env.RELOAD_EXIT ?? 0));\n'); if (process.platform === "win32") { writeFileSync(join(bin, "termux-reload-settings.cmd"), `@"${process.execPath}" "${fake}"\r\n`); } else { writeFileSync(join(bin, "termux-reload-settings"), `#!${process.execPath}\nrequire(${JSON.stringify(fake)});\n`, { mode: 0o755 }); } await t.test("import is inert and non-Termux use is rejected even with a reload executable", () => { success(run(nu, ["--no-config-file", "-c", `use ${JSON.stringify(module)}`], { env })); failure(invoke("dark", { TERMUX_VERSION: "" }), /inside Termux/); assert.equal(existsSync(log), false); assert.equal(readFileSync(active, "utf8"), original); }); await t.test("switch both ways, retain the original backup, and preserve touch settings", () => { for (const mode of ["dark", "light", "dark"]) { assert.match(success(invoke(mode)), new RegExp(`Termux: Nugu ${mode}`)); assert.equal(readFileSync(active, "utf8"), themes[mode]); assert.equal(readFileSync(backup, "utf8"), original); } assert.equal(readFileSync(log, "utf8"), "reload\nreload\nreload\n"); assert.equal(readFileSync(keyboard, "utf8"), "extra-keys = []\nfullscreen = true\n"); success(run("just", justArgs, { cwd: nugu })); assert.equal(readFileSync(active, "utf8"), themes.dark, "regeneration must not select a mode"); }); await t.test("missing palette fails before touching the current theme", () => { const source = join(workspace, "termux/themes/nugu-light.properties"); rmSync(source); failure(invoke("light"), /nugu-light/); assert.equal(readFileSync(active, "utf8"), themes.dark); writeFileSync(source, themes.light); }); await t.test("reload failures report that the file was saved, preserving the backup", () => { failure(invoke("light", { RELOAD_EXIT: "7" }), /saved, but Termux reload failed/); assert.equal(readFileSync(active, "utf8"), themes.light); assert.equal(readFileSync(backup, "utf8"), original); }); await t.test("refuse non-regular active files and backup paths", () => { for (const file of [active, backup]) { const content = readFileSync(file, "utf8"); rmSync(file); mkdirSync(file); failure(invoke("dark"), /Refusing non-regular file/); rmSync(file, { recursive: true }); writeFileSync(file, content); } assert.equal(readFileSync(active, "utf8"), themes.light); }); await t.test("refuse an active symlink instead of overwriting a palette source", { skip: process.platform === "win32" }, () => { rmSync(active); const target = join(workspace, "termux/themes/nugu-light.properties"); symlinkSync(target, active); failure(invoke("dark"), /Refusing non-regular file/); assert.equal(readFileSync(target, "utf8"), themes.light); rmSync(active); }); await t.test("refuse a symlinked settings directory without touching its target", () => { rmSync(settings, { recursive: true }); const target = join(workspace, "other-settings"); mkdirSync(target); writeFileSync(join(target, "colors.properties"), original); symlinkSync(target, settings, "junction"); failure(invoke("dark"), /regular directory/); assert.equal(readFileSync(join(target, "colors.properties"), "utf8"), original); rmSync(settings); }); await t.test("initialize absent settings without inventing a backup", () => { success(invoke("light")); assert.equal(readFileSync(active, "utf8"), themes.light); assert.equal(existsSync(backup), false); });});new file mode 100644+27 / −0 text lines
# Generated by nugu/termux.nu. Do not edit.foreground=#edededbackground=#121212cursor=#d86dd8color0=#121212color1=#ec6376color2=#7ba1aacolor3=#f0ee69color4=#b59ae4color5=#d151d1color6=#3ec5e3color7=#edededcolor8=#8b8b8bcolor9=#ec6376color10=#9aabaecolor11=#f0ee69color12=#dfd3f3color13=#d86dd8color14=#c9b6ebcolor15=#f3effbcolor16=#ed5eedcolor17=#dbdbdbcolor18=#242424color19=#9d9d9dcolor20=#9aabaecolor21=#6f6f6fcolor22=#5d5d5dnew file mode 100644+27 / −0 text lines
# Generated by nugu/termux.nu. Do not edit.foreground=#121212background=#edededcursor=#922792color0=#edededcolor1=#bd172ecolor2=#184e5bcolor3=#6e6c10color4=#715696color5=#ae2eaecolor6=#116477color7=#121212color8=#3b3b3bcolor9=#bd172ecolor10=#15333bcolor11=#6e6c10color12=#4f3c69color13=#922792color14=#604980color15=#3e2f53color16=#a112a1color17=#242424color18=#dbdbdbcolor19=#292929color20=#15333bcolor21=#5d5d5dcolor22=#6f6f6f