1 +import assert from "node:assert/strict";
2 +import { spawnSync } from "node:child_process";
3 +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
4 +import { tmpdir } from "node:os";
5 +import { dirname, join, resolve } from "node:path";
6 +import { fileURLToPath } from "node:url";
7 +import test from "node:test";
9 +const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
10 +const justArgs = ["--shell", "nu", "--clear-shell-args", "--shell-arg=--no-config-file", "--shell-arg=--commands", "termux"];
12 +function run(command, args, options = {}) {
13 + const result = spawnSync(command, args, { encoding: "utf8", timeout: 120_000, ...options });
14 + assert.equal(result.error, undefined);
18 +function success(result) {
19 + assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
20 + return result.stdout;
23 +function failure(result, message) {
24 + assert.notEqual(result.status, 0);
25 + assert.match(result.stderr, message);
28 +const nu = success(run("nu", ["--no-config-file", "-c", "$nu.current-exe"])).trim();
30 +function weztermColors(palette) {
31 + const lua = readFileSync(join(root, "wezterm/bugabinga/nugu/init.lua"), "utf8");
32 + const lookup = (role) => role.split(".").reduce((value, key) => value[key], palette);
34 + for (const [termux, wezterm] of [["foreground", "foreground"], ["background", "background"], ["cursor", "cursor_bg"]]) {
35 + result[termux] = lookup(lua.match(new RegExp(`\\b${wezterm} = palette\\.([\\w.]+),`))[1]);
37 + for (const [section, offset, count] of [["ansi", 0, 8], ["brights", 8, 8], ["indexed", 16, 7]]) {
38 + const body = lua.match(new RegExp(`\\b${section} = \\{([\\s\\S]*?)\\},`))[1];
39 + const roles = [...body.matchAll(/palette\.([\w.]+),/g)].map((match) => match[1]);
40 + assert.equal(roles.length, count);
41 + roles.forEach((role, index) => { result[`color${offset + index}`] = lookup(role); });
46 +test("Termux palettes and manual switching", async (t) => {
47 + const workspace = mkdtempSync(join(tmpdir(), "termux-theme-test-"));
48 + t.after(() => rmSync(workspace, { recursive: true, force: true }));
49 + const nugu = join(workspace, "nugu");
50 + const modules = join(workspace, "nushell/modules");
51 + const home = join(workspace, "home");
52 + const settings = join(home, ".termux");
53 + const bin = join(workspace, "bin");
54 + for (const directory of [nugu, modules, settings, bin, join(home, ".config")]) mkdirSync(directory, { recursive: true });
55 + for (const file of ["base.toml", "nugu.nu", "termux.nu", "justfile"]) cpSync(join(root, "nugu", file), join(nugu, file));
56 + cpSync(join(root, "nushell/modules/termux-theme.nu"), join(modules, "termux-theme.nu"));
57 + symlinkSync(join(workspace, "nushell"), join(home, ".config/nushell"), "junction");
58 + const module = join(home, ".config/nushell/modules/termux-theme.nu");
59 + const active = join(settings, "colors.properties");
60 + const backup = `${active}.before-nugu`;
61 + const keyboard = join(settings, "termux.properties");
62 + const log = join(workspace, "reload.log");
63 + const original = "# original palette\nbackground=#20201d\n";
64 + writeFileSync(active, original);
65 + writeFileSync(keyboard, "extra-keys = []\nfullscreen = true\n");
66 + const env = { ...process.env, HOME: home, USERPROFILE: home, TERMUX_VERSION: "test", PATH: bin, RELOAD_LOG: log };
67 + const invoke = (mode, extraEnv = {}) => run(nu, ["--no-config-file", "-c", `use ${JSON.stringify(module)}; termux-theme ${mode}`], { cwd: home, env: { ...env, ...extraEnv } });
70 + await t.test("generate both variants from source, matching WezTerm, without selecting a mode", () => {
71 + success(run("just", justArgs, { cwd: nugu }));
72 + assert.equal(readFileSync(active, "utf8"), original);
73 + assert.equal(existsSync(backup), false);
74 + assert.equal(existsSync(join(workspace, "termux/colors.properties")), false);
75 + for (const mode of ["dark", "light"]) {
76 + const filename = `nugu-${mode}.properties`;
77 + const text = readFileSync(join(nugu, "output/termux", filename), "utf8");
78 + themes[mode] = text;
79 + assert.equal(readFileSync(join(workspace, "termux/themes", filename), "utf8"), text);
80 + assert.equal(readFileSync(join(root, "termux/themes", filename), "utf8"), text);
81 + const lines = text.trim().split(/\r?\n/).filter((line) => !line.startsWith("#"));
82 + for (const line of lines) assert.match(line, /^(foreground|background|cursor|color\d+)=#[0-9a-f]{6}$/);
83 + const properties = Object.fromEntries(lines.map((line) => line.split("=")));
84 + assert.equal(Object.keys(properties).length, lines.length, "no duplicate properties");
85 + const palette = JSON.parse(success(run(nu, ["--no-config-file", "-c", `use nugu.nu; nugu ${mode} | get palette | to json`], { cwd: nugu })));
86 + assert.deepEqual(properties, weztermColors(palette));
88 + assert.notEqual(themes.dark, themes.light);
89 + failure(run(nu, ["--no-config-file", "-c", "use termux.nu; termux theme invalid"], { cwd: nugu }), /Expected dark or light/);
92 + await t.test("login.nu loads the command without a config.nu import", () => {
93 + const login = readFileSync(join(root, "nushell/login.nu"), "utf8");
94 + const imports = login.match(/^use termux-theme\.nu$/gm);
95 + assert.equal(imports?.length, 1);
96 + assert.doesNotMatch(readFileSync(join(root, "nushell/config.nu"), "utf8"), /^use termux-theme\.nu$/m);
97 + const code = `const NU_LIB_DIRS = [${JSON.stringify(join(home, ".config/nushell/modules"))}]; ${imports[0]}; help termux-theme`;
98 + assert.match(success(run(nu, ["--no-config-file", "-c", code], { env })), /termux-theme/);
99 + assert.equal(existsSync(log), false);
102 + await t.test("invalid modes and missing Termux support do not write anything", () => {
103 + failure(invoke("invalid"), /Expected dark or light/);
104 + failure(invoke("dark"), /inside Termux/);
105 + assert.equal(readFileSync(active, "utf8"), original);
106 + assert.equal(existsSync(backup), false);
109 + const fake = join(bin, "reload.cjs");
110 + writeFileSync(fake, 'require("node:fs").appendFileSync(process.env.RELOAD_LOG, "reload\\n"); process.exit(Number(process.env.RELOAD_EXIT ?? 0));\n');
111 + if (process.platform === "win32") {
112 + writeFileSync(join(bin, "termux-reload-settings.cmd"), `@"${process.execPath}" "${fake}"\r\n`);
114 + writeFileSync(join(bin, "termux-reload-settings"), `#!${process.execPath}\nrequire(${JSON.stringify(fake)});\n`, { mode: 0o755 });
117 + await t.test("import is inert and non-Termux use is rejected even with a reload executable", () => {
118 + success(run(nu, ["--no-config-file", "-c", `use ${JSON.stringify(module)}`], { env }));
119 + failure(invoke("dark", { TERMUX_VERSION: "" }), /inside Termux/);
120 + assert.equal(existsSync(log), false);
121 + assert.equal(readFileSync(active, "utf8"), original);
124 + await t.test("switch both ways, retain the original backup, and preserve touch settings", () => {
125 + for (const mode of ["dark", "light", "dark"]) {
126 + assert.match(success(invoke(mode)), new RegExp(`Termux: Nugu ${mode}`));
127 + assert.equal(readFileSync(active, "utf8"), themes[mode]);
128 + assert.equal(readFileSync(backup, "utf8"), original);
130 + assert.equal(readFileSync(log, "utf8"), "reload\nreload\nreload\n");
131 + assert.equal(readFileSync(keyboard, "utf8"), "extra-keys = []\nfullscreen = true\n");
132 + success(run("just", justArgs, { cwd: nugu }));
133 + assert.equal(readFileSync(active, "utf8"), themes.dark, "regeneration must not select a mode");
136 + await t.test("missing palette fails before touching the current theme", () => {
137 + const source = join(workspace, "termux/themes/nugu-light.properties");
139 + failure(invoke("light"), /nugu-light/);
140 + assert.equal(readFileSync(active, "utf8"), themes.dark);
141 + writeFileSync(source, themes.light);
144 + await t.test("reload failures report that the file was saved, preserving the backup", () => {
145 + failure(invoke("light", { RELOAD_EXIT: "7" }), /saved, but Termux reload failed/);
146 + assert.equal(readFileSync(active, "utf8"), themes.light);
147 + assert.equal(readFileSync(backup, "utf8"), original);
150 + await t.test("refuse non-regular active files and backup paths", () => {
151 + for (const file of [active, backup]) {
152 + const content = readFileSync(file, "utf8");
155 + failure(invoke("dark"), /Refusing non-regular file/);
156 + rmSync(file, { recursive: true });
157 + writeFileSync(file, content);
159 + assert.equal(readFileSync(active, "utf8"), themes.light);
162 + await t.test("refuse an active symlink instead of overwriting a palette source", { skip: process.platform === "win32" }, () => {
164 + const target = join(workspace, "termux/themes/nugu-light.properties");
165 + symlinkSync(target, active);
166 + failure(invoke("dark"), /Refusing non-regular file/);
167 + assert.equal(readFileSync(target, "utf8"), themes.light);
171 + await t.test("refuse a symlinked settings directory without touching its target", () => {
172 + rmSync(settings, { recursive: true });
173 + const target = join(workspace, "other-settings");
175 + writeFileSync(join(target, "colors.properties"), original);
176 + symlinkSync(target, settings, "junction");
177 + failure(invoke("dark"), /regular directory/);
178 + assert.equal(readFileSync(join(target, "colors.properties"), "utf8"), original);
182 + await t.test("initialize absent settings without inventing a backup", () => {
183 + success(invoke("light"));
184 + assert.equal(readFileSync(active, "utf8"), themes.light);
185 + assert.equal(existsSync(backup), false);