mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-24 12:06:17 +01:00
Compare commits
4 Commits
5a27acd9d0
...
0aa78ea7aa
| Author | SHA1 | Date | |
|---|---|---|---|
| 0aa78ea7aa | |||
| 63650fbc45 | |||
| ebe56f0419 | |||
| 776e04db89 |
18
docs/superpowers/contracts/kcd2-test-split-2026-08-16.json
Normal file
18
docs/superpowers/contracts/kcd2-test-split-2026-08-16.json
Normal file
@ -0,0 +1,18 @@
|
||||
{
|
||||
"title": "Split the kcd2_dice_solver test files under the 250-line cap",
|
||||
"objective": "Bring every kcd2 test file under the cap by partitioning at describe boundaries, taking the package from twelve violations to four source files.",
|
||||
"acceptance_criteria": [
|
||||
"No kcd2_dice_solver test file is over 250 lines.",
|
||||
"The suite still reports exactly 288 passing tests -- the same as before the split, though spread across 24 files instead of 15.",
|
||||
"Coverage stays at 100% for statements, branches, functions and lines.",
|
||||
"npm run lint passes with no new suppression and no eslint-disable.",
|
||||
"A fixture shared by two split halves goes in src/test/, which vite.config.ts excludes from coverage. A fixture placed beside the source would be counted as production code and break the 100% gate.",
|
||||
"No test is deleted, skipped or weakened; whole describe blocks move verbatim.",
|
||||
"No empty test file is left behind: a file whose last describe moved out is removed, since vitest fails on 'No test suite found'."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"search.ts, scoring.ts, badgeValue.ts and App.tsx, which are source files.",
|
||||
"Changing what any test asserts."
|
||||
],
|
||||
"verifier": "npm test -- --run (expects exactly 288 passed), npm run coverage (100% on all four metrics), npm run lint, and check_file_length.sh over kcd2_dice_solver."
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
{
|
||||
"title": "Split setup_offline_docs.sh and optimize_arch_desktop.sh, deferring libre_translate.sh",
|
||||
"objective": "Bring setup_offline_docs.sh (713) and optimize_arch_desktop.sh (623) under the 250-line cap, and confirm that a script with many globals written in one half and read in the other cannot be split cleanly.",
|
||||
"acceptance_criteria": [
|
||||
"Both entry scripts and all seven new libs are at most 250 lines.",
|
||||
"The pre-commit shellcheck hook passes on every touched file, with no new suppression and no disable directive.",
|
||||
"No lib sources a sibling: each entry sources every lib directly.",
|
||||
"The stubbed run reports every moved function as defined for both scripts.",
|
||||
"No script is executed. One downloads documentation archives, the other writes sysctl and udev settings.",
|
||||
"libre_translate.sh is fully restored to 488 lines, leaving the unrelated lib already in that directory in place."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Executing any download or tuning step.",
|
||||
"libre_translate.sh, which has nineteen globals crossing any seam.",
|
||||
"Changing what any script does when run."
|
||||
],
|
||||
"verifier": "meta/scripts/verify_shell_split.sh per script, plus pre-commit run --files, plus check_file_length.sh, plus ls of the shared lib/ directory after the revert."
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
{
|
||||
"title": "Split three more linux_configuration scripts and harden the split verifier",
|
||||
"objective": "Bring transcribe.sh (473), setup_activitywatch.sh (457) and setup_wireguard_ssh.sh (464) under the 250-line cap, and make the verifier catch a split that lands inside a heredoc.",
|
||||
"acceptance_criteria": [
|
||||
"All three entry scripts and all nine new libs are at most 250 lines.",
|
||||
"The pre-commit shellcheck hook passes on every touched file, with no new suppression and no disable directive.",
|
||||
"No lib sources a sibling.",
|
||||
"meta/scripts/verify_shell_split.sh parses every lib with bash -n BEFORE linting the entry script, and reports the lib by name when it fails. A heredoc cut otherwise surfaces as a confusing SC1094 on the caller.",
|
||||
"That new check is proven in both directions: it fails on a deliberately unterminated heredoc and passes once restored.",
|
||||
"No script is executed. These install CUDA runtimes, start services and rewrite sshd and nftables config.",
|
||||
"enforce_vbox_hosts.sh is fully restored, leaving no partial split and no orphan lib directory."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Executing any install or firewall step.",
|
||||
"enforce_vbox_hosts.sh, whose seam fell inside a heredoc.",
|
||||
"Changing what any script does when run, beyond the cd guard."
|
||||
],
|
||||
"verifier": "meta/scripts/verify_shell_split.sh per script, plus a deliberate heredoc-corruption test of the verifier itself, plus pre-commit run --files and check_file_length.sh."
|
||||
}
|
||||
46
docs/superpowers/evidence/kcd2-test-split-2026-08-16.json
Normal file
46
docs/superpowers/evidence/kcd2-test-split-2026-08-16.json
Normal file
@ -0,0 +1,46 @@
|
||||
{
|
||||
"intent": "Clear every over-cap kcd2_dice_solver test file by partitioning at describe boundaries.",
|
||||
"scope": [
|
||||
"components.test.tsx (532) -> componentRows, componentPickers, componentResult, componentInventory",
|
||||
"App.test.tsx (512) -> AppShell, AppLinks, AppRecovery, AppStorage; the original shell was deleted",
|
||||
"inventoryIo.test.ts (302) -> inventoryHash.test.ts",
|
||||
"simulate.test.ts (272) -> simulateTurns.test.ts",
|
||||
"src/test/fixtures.ts (new, coverage-excluded by path)",
|
||||
"Non-goal: no assertion changed, no test deleted or skipped"
|
||||
],
|
||||
"changes": [
|
||||
"Nine new test modules, each carrying the original preamble so imports and local helpers resolve; the unused ones were then pruned by tsc's own TS6133/TS6192 output driving an iterative cleanup, rather than guessed.",
|
||||
"App.test.tsx ended up with no describe blocks at all and vitest failed the run with 'No test suite found in file'. The empty shell was deleted - a split that empties a file has to remove it, not leave it.",
|
||||
"The `response` and `ordinary` fixtures were used by two halves of the component split, so they moved to src/test/fixtures.ts. That directory is in vite.config.ts's coverage exclude list; putting a fixture beside the source would have counted it as production code and broken the 100% gate - the same trap recorded for poker-stakes."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "npm test -- --run",
|
||||
"result": "fail twice, then pass",
|
||||
"evidence": "288 passed across 24 files, identical to the 288 in 15 files before. The two failures were real: the empty App.test.tsx, and 7 tests failing with 'Cannot find name response' when a shared fixture stayed behind in one half."
|
||||
},
|
||||
{
|
||||
"command": "npm run coverage",
|
||||
"result": "pass",
|
||||
"evidence": "100% statements (863/863), branches (375/375), functions (181/181), lines (810/810) - unchanged, confirming src/test/fixtures.ts is excluded rather than counted."
|
||||
},
|
||||
{
|
||||
"command": "npm run lint",
|
||||
"result": "pass",
|
||||
"evidence": "tsc --noEmit and eslint clean, with no eslint-disable added. Roughly 40 imports and several orphaned local helpers were removed across the new files."
|
||||
},
|
||||
{
|
||||
"command": "bash ~/utils/scripts/check_file_length.sh --all | grep kcd2",
|
||||
"result": "pass",
|
||||
"evidence": "Four entries remain, all source files: search.ts, scoring.ts, badgeValue.ts and App.tsx. Every test file is under the cap."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Carrying the whole preamble into each new file then pruning by compiler output is reliable for imports but not for local helpers: tsc only flags a helper as unused, it cannot tell you the other half needed it. The `response` fixture was caught by the test run, not the compiler.",
|
||||
"24 test files where there were 15 means more preamble duplication. The shared fixtures module offsets some of it, but each file still repeats its render helpers."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; the four originals return and the nine new modules plus src/test/fixtures.ts disappear.",
|
||||
"After rollback, re-run npm test and expect 288 passed in 15 files."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,45 @@
|
||||
{
|
||||
"intent": "Split two more linux_configuration scripts under the cap, and defer a third whose globals cross every candidate seam.",
|
||||
"scope": [
|
||||
"single_use/utils/setup_offline_docs.sh (713 -> 121) + offline_python, offline_cpp, offline_js, offline_rust, offline_index, offline_status",
|
||||
"single_use/fixes/optimize_arch_desktop.sh (623 -> 118) + arch_cpu, arch_sysctl, arch_hardware",
|
||||
"Deferred and fully restored: misc/testsAndMisc-bash/libre_translate.sh (488)",
|
||||
"Non-goal: no script executed"
|
||||
],
|
||||
"changes": [
|
||||
"setup_offline_docs.sh needed six libs, carved one language at a time: the first cut left offline_cpp at 545 lines because it had swallowed JS and Rust too.",
|
||||
"setup_offline_docs.sh had no SCRIPT_DIR at all - the second script in this effort where the split had to add one.",
|
||||
"optimize_arch_desktop.sh's libs had chained (arch_cpu sourcing the other two); flattened so the entry sources all three. Fourth instance of that bug.",
|
||||
"libre_translate.sh was reverted. Its API_KEY, GENERATED and seventeen other globals are written on one side of any seam and read on the other. Exporting GENERATED fixed one warning and revealed eighteen more, which is the signal that the seam is imaginary rather than that the fix is wrong."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "meta/scripts/verify_shell_split.sh per script",
|
||||
"result": "fail then pass",
|
||||
"evidence": "Both now report 'libs sourced, functions defined'. Three real failures first: a missing SCRIPT_DIR, the chained arch libs, and the libre_translate globals."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <11 changed files>",
|
||||
"result": "pass",
|
||||
"evidence": "shellcheck - which lints each lib in isolation - shfmt, the shebang hook and jscpd all pass."
|
||||
},
|
||||
{
|
||||
"command": "git checkout HEAD -- libre_translate.sh, rm its libs, shellcheck -x, ls the lib dir",
|
||||
"result": "pass",
|
||||
"evidence": "Restored to 488 lines and clean, with unity_handler.sh from an earlier commit still present - checked by listing rather than assumed."
|
||||
},
|
||||
{
|
||||
"command": "bash ~/utils/scripts/check_file_length.sh --all",
|
||||
"result": "pass",
|
||||
"evidence": "Neither entry script nor any of the seven libs is listed. Repo total is 90, down from 183."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Neither script was run: one downloads documentation archives over the network, the other writes sysctl, udev and NVIDIA settings. The stubbed run proves reachability, not behaviour.",
|
||||
"libre_translate.sh joins the deferred list. Unlike the others it is not one shared array but a broad style - nearly twenty globals - so splitting it means converting them to parameters or accepting a suppression."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; both scripts return to 713 and 623 lines and the seven libs disappear.",
|
||||
"After rollback, re-run bash -n and shellcheck on the restored scripts."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,49 @@
|
||||
{
|
||||
"intent": "Split three more linux_configuration scripts, and harden the verifier after a split silently corrupted a file.",
|
||||
"scope": [
|
||||
"misc/testsAndMisc-bash/transcribe.sh (473 -> 39) + transcribe_pkgmgr, transcribe_deps, transcribe_venv",
|
||||
"single_use/features/setup_activitywatch.sh (457 -> 102) + aw_install, aw_service, aw_autostart",
|
||||
"single_use/features/setup_wireguard_ssh.sh (464 -> 136) + wg_keys, wg_firewall, wg_sshd",
|
||||
"meta/scripts/verify_shell_split.sh (lib parse check moved ahead of the entry lint)",
|
||||
"Deferred and fully restored: virtualbox/enforce_vbox_hosts.sh (443)",
|
||||
"Non-goal: no script executed"
|
||||
],
|
||||
"changes": [
|
||||
"Nine libs across three scripts, each needing a second carve after the first pass.",
|
||||
"enforce_vbox_hosts.sh was reverted because the split landed INSIDE a heredoc: the resulting lib had an unterminated here-document and bash -n rejected it outright. This is the first split in the whole effort to produce a file that does not parse, and it is the most dangerous failure mode yet - shellcheck reported it only as SC1094 'parsing of sourced file failed' on the caller, which reads like a linting nicety rather than a broken file.",
|
||||
"The verifier now runs bash -n over every lib BEFORE linting the entry, and names the offending lib with a hint about heredocs. Proven in both directions on a deliberately corrupted copy.",
|
||||
"Fixed another unguarded cd, this one before `git clone ... .` - a failed cd would have cloned an AUR repo into the caller's working directory.",
|
||||
"ALLOW_WEB and ALLOW_DNS are declared in the entry, set by the arg parser in one lib and read by the ruleset builder in another; exported, which is what SC2034 asks for and makes the three-way contract explicit."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "meta/scripts/verify_shell_split.sh per script",
|
||||
"result": "fail then pass",
|
||||
"evidence": "All three now report 'libs sourced, functions defined'. Four real failures on the way: chained libs in all three, the unguarded cd, the exported flags, and the vbox heredoc corruption."
|
||||
},
|
||||
{
|
||||
"command": "append an unterminated heredoc to a lib, re-run the verifier, restore",
|
||||
"result": "pass",
|
||||
"evidence": "Reports the here-document parse failure and exits non-zero; passes again once restored. Tested in both directions, because a check that never fires is worse than none."
|
||||
},
|
||||
{
|
||||
"command": "git checkout HEAD -- enforce_vbox_hosts.sh, rm its lib dir, bash -n and shellcheck -x",
|
||||
"result": "pass",
|
||||
"evidence": "Restored to 443 lines, parses and lints clean."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <13 changed files>",
|
||||
"result": "pass",
|
||||
"evidence": "Clean, including shellcheck over each lib in isolation."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"None of the three was run: they install CUDA runtimes and AUR packages, start user services, and rewrite sshd and nftables configuration.",
|
||||
"The heredoc failure means the function-boundary heuristic the splitter uses is not safe on files with heredocs at top level. bash -n now catches it, but only after the fact - the splitter itself still has no awareness of heredocs.",
|
||||
"enforce_vbox_hosts.sh stays at 443 lines and needs a seam chosen by hand, outside any heredoc."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; the three scripts return to their previous sizes, the nine libs disappear, and the verifier loses its parse check.",
|
||||
"After rollback, re-run bash -n and shellcheck on the restored scripts."
|
||||
]
|
||||
}
|
||||
@ -1,512 +0,0 @@
|
||||
/**
|
||||
* End-to-end tests for the app, driving the real flow: search for a die, click
|
||||
* to add it, scroll the wheel over a counter, and get a real recommendation.
|
||||
*
|
||||
* The worker is replaced with a port that runs the *real* solver synchronously —
|
||||
* jsdom has no module-worker support, but nothing about the solver is stubbed,
|
||||
* so these exercise the actual recommendation path.
|
||||
*/
|
||||
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { App } from "./App.tsx";
|
||||
import { STORAGE_KEY, encodeInventoryHash, toBase64Url } from "./lib/inventoryIo.ts";
|
||||
import type { SavedInventory, UrlHashPort } from "./lib/inventoryIo.ts";
|
||||
import { solve } from "./core/solve.ts";
|
||||
import type { SolverPort } from "./hooks/useSolver.ts";
|
||||
import type { WorkerReply, WorkerRequest } from "./worker/solver.worker.ts";
|
||||
|
||||
/**
|
||||
* A solver port that runs the real solver in-process.
|
||||
*
|
||||
* @returns A port usable in place of the Web Worker.
|
||||
*/
|
||||
function createInlinePort(): SolverPort {
|
||||
const listeners = new Set<(event: MessageEvent<WorkerReply>) => void>();
|
||||
return {
|
||||
postMessage: ({ id, request }: WorkerRequest) => {
|
||||
let reply: WorkerReply;
|
||||
try {
|
||||
// Keep the simulation short: these tests are about the wiring.
|
||||
reply = { id, ok: true, response: solve({ ...request, simulationTurns: 200 }) };
|
||||
} catch (error) {
|
||||
reply = { id, ok: false, error: error instanceof Error ? error.message : "failed" };
|
||||
}
|
||||
for (const listener of listeners) {
|
||||
listener({ data: reply } as MessageEvent<WorkerReply>);
|
||||
}
|
||||
},
|
||||
addEventListener: (_type, listener) => listeners.add(listener),
|
||||
removeEventListener: (_type, listener) => listeners.delete(listener),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An in-memory Storage stand-in, so tests do not share persisted state.
|
||||
*
|
||||
* @param initial - Optional starting contents.
|
||||
* @returns A minimal storage object.
|
||||
*/
|
||||
function memoryStorage(initial?: string): Pick<Storage, "getItem" | "setItem"> {
|
||||
const store = new Map<string, string>();
|
||||
if (initial !== undefined) {
|
||||
store.set(STORAGE_KEY, initial);
|
||||
}
|
||||
return {
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
store.set(key, value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Read back what the app persisted, typed so assertions are not on `any`.
|
||||
*
|
||||
* @param storage - The storage the app was given.
|
||||
* @returns The parsed inventory.
|
||||
*/
|
||||
function readSaved(storage: Pick<Storage, "getItem">): SavedInventory {
|
||||
return JSON.parse(storage.getItem(STORAGE_KEY) ?? "{}") as SavedInventory;
|
||||
}
|
||||
|
||||
/**
|
||||
* A URL port that reports a fragment without touching the real location.
|
||||
*
|
||||
* @param hash - The fragment the page was "opened with".
|
||||
* @returns The port plus a record of whether the app cleared the fragment.
|
||||
*/
|
||||
function stubUrl(hash = ""): UrlHashPort & { cleared: () => number } {
|
||||
let clears = 0;
|
||||
return {
|
||||
read: () => hash,
|
||||
clear: () => {
|
||||
clears += 1;
|
||||
},
|
||||
base: () => "https://dice.example/",
|
||||
cleared: () => clears,
|
||||
};
|
||||
}
|
||||
|
||||
const renderApp = (initial?: string, urlHash: UrlHashPort = stubUrl()) =>
|
||||
render(
|
||||
<App
|
||||
createPort={createInlinePort}
|
||||
storage={memoryStorage(initial)}
|
||||
urlHash={urlHash}
|
||||
clipboard={{ writeText: () => Promise.resolve() }}
|
||||
saveFile={() => undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
describe("App", () => {
|
||||
it("asks for dice before anything is entered", () => {
|
||||
renderApp();
|
||||
expect(screen.getByText(/Add at least six dice/)).toBeInTheDocument();
|
||||
expect(screen.getByText("0 dice")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("finds a die by fuzzy search, adds six by clicking, and solves", async () => {
|
||||
renderApp();
|
||||
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
const row = screen.getAllByRole("listitem")[0];
|
||||
const add = within(row).getByRole("button", { name: "Weighted die" });
|
||||
|
||||
for (let i = 0; i < 6; i += 1) {
|
||||
await userEvent.click(add);
|
||||
}
|
||||
|
||||
expect(screen.getByText("6 dice")).toBeInTheDocument();
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Best loadout")).toBeInTheDocument();
|
||||
});
|
||||
// Six Weighted dice is the right answer and the panel must name it.
|
||||
expect(screen.getByText("6×")).toBeInTheDocument();
|
||||
expect(screen.getByText("Weighted die")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Provably optimal/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("adds dice by scrolling the wheel over the counter", async () => {
|
||||
renderApp();
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
const counter = screen.getByLabelText("How many Weighted die");
|
||||
const stepper = counter.parentElement;
|
||||
if (!stepper) {
|
||||
throw new Error("no stepper");
|
||||
}
|
||||
|
||||
for (let i = 0; i < 6; i += 1) {
|
||||
fireEvent.wheel(stepper, { deltaY: -120 });
|
||||
}
|
||||
expect(screen.getByLabelText("How many Weighted die")).toHaveTextContent("6");
|
||||
expect(screen.getByText("6 dice")).toBeInTheDocument();
|
||||
|
||||
fireEvent.wheel(stepper, { deltaY: 120 });
|
||||
expect(screen.getByLabelText("How many Weighted die")).toHaveTextContent("5");
|
||||
expect(screen.getByText("5 dice")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("accumulates a rapid burst of clicks and wheel ticks", async () => {
|
||||
// Driving the real app in headless Chrome caught this: six fast clicks used
|
||||
// to land as one, because each handler computed from the count captured at
|
||||
// render time. React batches faster than it re-renders.
|
||||
renderApp();
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
|
||||
const row = screen.getAllByRole("listitem")[0];
|
||||
const add = within(row).getByRole("button", { name: "Weighted die" });
|
||||
act(() => {
|
||||
for (let i = 0; i < 4; i += 1) {
|
||||
fireEvent.click(add);
|
||||
}
|
||||
});
|
||||
expect(screen.getByLabelText("How many Weighted die")).toHaveTextContent("4");
|
||||
|
||||
const stepper = screen.getByLabelText("How many Weighted die").parentElement;
|
||||
if (!stepper) {
|
||||
throw new Error("no stepper");
|
||||
}
|
||||
act(() => {
|
||||
for (let i = 0; i < 2; i += 1) {
|
||||
fireEvent.wheel(stepper, { deltaY: -120 });
|
||||
}
|
||||
});
|
||||
expect(screen.getByLabelText("How many Weighted die")).toHaveTextContent("6");
|
||||
expect(screen.getByText("6 dice")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("ranks the badges you own alongside the dice", async () => {
|
||||
const saved = JSON.stringify({
|
||||
diceCounts: { weighted: 6 },
|
||||
badgeIds: ["gold_emperors", "gold_defence"],
|
||||
});
|
||||
renderApp(saved);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Best badge per tier")).toBeInTheDocument();
|
||||
});
|
||||
// The name also appears in the ownership checkbox, so scope to the result.
|
||||
const results = document.querySelector(".result");
|
||||
if (!results) {
|
||||
throw new Error("no result panel");
|
||||
}
|
||||
expect(within(results as HTMLElement).getByText("Gold Emperor's badge")).toBeInTheDocument();
|
||||
// The Defence badge is owned too, and must be reported as situational
|
||||
// rather than given an invented number.
|
||||
expect(within(results as HTMLElement).getByText(/situational/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("restores a saved inventory on load", () => {
|
||||
renderApp(JSON.stringify({ diceCounts: { weighted: 4 }, badgeIds: [] }));
|
||||
expect(screen.getByText("4 dice")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("persists changes for next time", async () => {
|
||||
const storage = memoryStorage();
|
||||
render(<App createPort={createInlinePort} storage={storage} />);
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
await userEvent.click(screen.getByLabelText("Add one Weighted die"));
|
||||
|
||||
expect(readSaved(storage)).toEqual({ diceCounts: { weighted: 1 }, badgeIds: [] });
|
||||
});
|
||||
|
||||
it("clears everything on request", async () => {
|
||||
renderApp(JSON.stringify({ diceCounts: { weighted: 6 }, badgeIds: ["tin_might"] }));
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Best loadout")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Clear" }));
|
||||
expect(screen.getByText("0 dice")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Add at least six dice/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("falls back to the browser's own storage when none is injected", () => {
|
||||
window.localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({ diceCounts: { weighted: 2 }, badgeIds: [] }),
|
||||
);
|
||||
render(<App createPort={createInlinePort} />);
|
||||
expect(screen.getByText("2 dice")).toBeInTheDocument();
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
it("disables Clear when there is nothing to clear", () => {
|
||||
renderApp();
|
||||
expect(screen.getByRole("button", { name: "Clear" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("drops a die from the inventory when its count reaches zero", async () => {
|
||||
const storage = memoryStorage(
|
||||
JSON.stringify({ diceCounts: { weighted: 1 }, badgeIds: [] }),
|
||||
);
|
||||
render(<App createPort={createInlinePort} storage={storage} />);
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
await userEvent.click(screen.getByLabelText("Remove one Weighted die"));
|
||||
|
||||
expect(readSaved(storage)).toEqual({ diceCounts: {}, badgeIds: [] });
|
||||
});
|
||||
|
||||
it("toggles a badge on and off", async () => {
|
||||
const storage = memoryStorage();
|
||||
render(<App createPort={createInlinePort} storage={storage} />);
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "emperor");
|
||||
|
||||
const checkbox = screen.getByRole("checkbox");
|
||||
await userEvent.click(checkbox);
|
||||
expect(readSaved(storage).badgeIds).toEqual(["gold_emperors"]);
|
||||
|
||||
await userEvent.click(checkbox);
|
||||
expect(readSaved(storage).badgeIds).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses the singular for a single die", async () => {
|
||||
renderApp();
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
await userEvent.click(screen.getByLabelText("Add one Weighted die"));
|
||||
expect(screen.getByText("1 die")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("surfaces a solver error rather than showing nothing", async () => {
|
||||
// A port that always fails, standing in for a worker that threw.
|
||||
const failingPort = (): SolverPort => {
|
||||
const listeners = new Set<(event: MessageEvent<WorkerReply>) => void>();
|
||||
return {
|
||||
postMessage: ({ id }: WorkerRequest) => {
|
||||
for (const listener of listeners) {
|
||||
listener({ data: { id, ok: false, error: "solver exploded" } } as MessageEvent<
|
||||
WorkerReply
|
||||
>);
|
||||
}
|
||||
},
|
||||
addEventListener: (_type, listener) => listeners.add(listener),
|
||||
removeEventListener: (_type, listener) => listeners.delete(listener),
|
||||
};
|
||||
};
|
||||
render(
|
||||
<App
|
||||
createPort={failingPort}
|
||||
storage={memoryStorage(JSON.stringify({ diceCounts: { weighted: 6 }, badgeIds: [] }))}
|
||||
/>,
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("solver exploded")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("shared links", () => {
|
||||
const shared = encodeInventoryHash({ diceCounts: { weighted: 3 }, badgeIds: [] });
|
||||
|
||||
it("prefers a link over whatever this browser had saved", () => {
|
||||
const mine = JSON.stringify({ diceCounts: { lucky: 1 }, badgeIds: [] });
|
||||
renderApp(mine, stubUrl(shared));
|
||||
expect(screen.getByText("3 dice")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("drops the fragment so a reload does not resurrect the link", () => {
|
||||
const url = stubUrl(shared);
|
||||
renderApp(undefined, url);
|
||||
expect(url.cleared()).toBe(1);
|
||||
});
|
||||
|
||||
it("leaves the URL alone when there was no link", () => {
|
||||
const url = stubUrl();
|
||||
renderApp(undefined, url);
|
||||
expect(url.cleared()).toBe(0);
|
||||
});
|
||||
|
||||
it("does not overwrite the saved inventory until the visitor commits", () => {
|
||||
// Silently clobbering somebody's own loadout with a link they opened is
|
||||
// unrecoverable, so nothing is written until they say so.
|
||||
const storage = memoryStorage(JSON.stringify({ diceCounts: { lucky: 1 }, badgeIds: [] }));
|
||||
render(
|
||||
<App
|
||||
createPort={createInlinePort}
|
||||
storage={storage}
|
||||
urlHash={stubUrl(shared)}
|
||||
clipboard={{ writeText: () => Promise.resolve() }}
|
||||
saveFile={() => undefined}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText("3 dice")).toBeInTheDocument();
|
||||
expect(readSaved(storage).diceCounts).toEqual({ lucky: 1 });
|
||||
});
|
||||
|
||||
it("persists once Keep is pressed", async () => {
|
||||
const storage = memoryStorage();
|
||||
render(
|
||||
<App
|
||||
createPort={createInlinePort}
|
||||
storage={storage}
|
||||
urlHash={stubUrl(shared)}
|
||||
clipboard={{ writeText: () => Promise.resolve() }}
|
||||
saveFile={() => undefined}
|
||||
/>,
|
||||
);
|
||||
await userEvent.click(screen.getByRole("button", { name: "Keep" }));
|
||||
expect(readSaved(storage).diceCounts).toEqual({ weighted: 3 });
|
||||
expect(screen.queryByRole("button", { name: "Keep" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("persists as soon as the visitor edits anything, banner and all", async () => {
|
||||
const storage = memoryStorage();
|
||||
render(
|
||||
<App
|
||||
createPort={createInlinePort}
|
||||
storage={storage}
|
||||
urlHash={stubUrl(shared)}
|
||||
clipboard={{ writeText: () => Promise.resolve() }}
|
||||
saveFile={() => undefined}
|
||||
/>,
|
||||
);
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
await userEvent.click(screen.getByLabelText("Remove one Weighted die"));
|
||||
expect(readSaved(storage).diceCounts).toEqual({ weighted: 2 });
|
||||
expect(screen.queryByRole("button", { name: "Keep" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows no banner on an ordinary visit", () => {
|
||||
renderApp();
|
||||
expect(screen.queryByRole("button", { name: "Keep" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("falls through to storage when the fragment carries no inventory", () => {
|
||||
const mine = JSON.stringify({ diceCounts: { lucky: 1 }, badgeIds: [] });
|
||||
renderApp(mine, stubUrl("#nothing=here"));
|
||||
expect(screen.getByText("1 die")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps the saved inventory when the link is damaged", () => {
|
||||
const mine = JSON.stringify({ diceCounts: { lucky: 1 }, badgeIds: [] });
|
||||
// "@" is not a base64 character, so decoding throws rather than yielding
|
||||
// an inventory — the case a truncated or mangled URL actually produces.
|
||||
renderApp(mine, stubUrl("#i=@@@"));
|
||||
expect(screen.getByText("1 die")).toBeInTheDocument();
|
||||
// Nothing was taken from the link, so there is nothing to accept or refuse.
|
||||
expect(screen.queryByRole("button", { name: "Keep" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Discard" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("reports what a shared link had to drop", () => {
|
||||
const link = `#i=${toBase64Url(
|
||||
JSON.stringify({ diceCounts: { weighted: 2, nosuchdie: 1 }, badgeIds: [] }),
|
||||
)}`;
|
||||
renderApp(undefined, stubUrl(link));
|
||||
expect(screen.getByText("2 dice")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Unknown die/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("replaces the whole inventory on import", async () => {
|
||||
const storage = memoryStorage(JSON.stringify({ diceCounts: { lucky: 2 }, badgeIds: [] }));
|
||||
render(
|
||||
<App createPort={createInlinePort} storage={storage} urlHash={stubUrl()} />,
|
||||
);
|
||||
fireEvent.change(screen.getByLabelText("Inventory JSON"), {
|
||||
target: { value: '{"diceCounts":{"weighted":4},"badgeIds":[]}' },
|
||||
});
|
||||
await userEvent.click(screen.getByRole("button", { name: "Import pasted" }));
|
||||
expect(screen.getByText("4 dice")).toBeInTheDocument();
|
||||
expect(readSaved(storage).diceCounts).toEqual({ weighted: 4 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("layout", () => {
|
||||
it("gives the left column to the dice and nothing else", () => {
|
||||
renderApp();
|
||||
const inventory = document.querySelector("section.inventory");
|
||||
if (!inventory) {
|
||||
throw new Error("no inventory section");
|
||||
}
|
||||
// The search box, the title and the badges all moved to the right column so
|
||||
// the 43-row grid gets the whole vertical budget.
|
||||
expect(inventory.querySelector(".die-list")).toBeInTheDocument();
|
||||
expect(inventory.querySelector(".toolbar")).toBeNull();
|
||||
expect(inventory.querySelector("h1")).toBeNull();
|
||||
expect(inventory.querySelector(".badges")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the badges collapsed until asked for", () => {
|
||||
renderApp();
|
||||
const badges = document.querySelector("details.badges");
|
||||
expect(badges).toBeInTheDocument();
|
||||
expect(badges).not.toHaveAttribute("open");
|
||||
// Still reachable — collapsed, not removed.
|
||||
expect(within(badges as HTMLElement).getByText("Badges")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("no longer tells touch users to scroll a mouse wheel", () => {
|
||||
renderApp();
|
||||
expect(screen.queryByText(/scroll the wheel/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("shared links cannot destroy what is already saved", () => {
|
||||
it("ignores a link that carries no dice or badges", () => {
|
||||
// A count of zero parses cleanly, so "did the parser complain?" is the
|
||||
// wrong question — this used to blank the inventory on screen, disable
|
||||
// Clear, and leave Keep as the only enabled control, writing the emptiness
|
||||
// over the visitor's own dice.
|
||||
const mine = JSON.stringify({ diceCounts: { lucky: 4 }, badgeIds: [] });
|
||||
const empty = encodeInventoryHash({ diceCounts: { weighted: 0 }, badgeIds: [] });
|
||||
const storage = memoryStorage(mine);
|
||||
render(
|
||||
<App createPort={createInlinePort} storage={storage} urlHash={stubUrl(empty)} />,
|
||||
);
|
||||
expect(screen.getByText("4 dice")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Keep" })).not.toBeInTheDocument();
|
||||
expect(readSaved(storage).diceCounts).toEqual({ lucky: 4 });
|
||||
});
|
||||
|
||||
it("restores the visitor's own inventory when a link is discarded", async () => {
|
||||
const mine = JSON.stringify({ diceCounts: { lucky: 4 }, badgeIds: ["tin_might"] });
|
||||
const link = encodeInventoryHash({ diceCounts: { weighted: 3 }, badgeIds: [] });
|
||||
const storage = memoryStorage(mine);
|
||||
render(
|
||||
<App createPort={createInlinePort} storage={storage} urlHash={stubUrl(link)} />,
|
||||
);
|
||||
expect(screen.getByText("3 dice")).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Discard" }));
|
||||
expect(screen.getByText("4 dice")).toBeInTheDocument();
|
||||
expect(readSaved(storage)).toEqual({
|
||||
diceCounts: { lucky: 4 },
|
||||
badgeIds: ["tin_might"],
|
||||
});
|
||||
});
|
||||
|
||||
it("clears a fragment even when it decoded to nothing", () => {
|
||||
// A fragment left in the bar is read again on the next reload, where it
|
||||
// would land on top of whatever has been edited since.
|
||||
for (const hash of ["#i=@@@", "#other=1", "#i="]) {
|
||||
const url = stubUrl(hash);
|
||||
renderApp(undefined, url);
|
||||
expect(url.cleared()).toBe(1);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("a saved inventory that no longer parses cleanly", () => {
|
||||
const stale = JSON.stringify({
|
||||
diceCounts: { lucky: 4, future_patch_die: 6 },
|
||||
badgeIds: [],
|
||||
});
|
||||
|
||||
it("is not silently truncated in storage on load", () => {
|
||||
const storage = memoryStorage(stale);
|
||||
render(<App createPort={createInlinePort} storage={storage} urlHash={stubUrl()} />);
|
||||
// Still the original text: nothing was written over it on first paint.
|
||||
expect(readSaved(storage).diceCounts).toEqual({ lucky: 4, future_patch_die: 6 });
|
||||
});
|
||||
|
||||
it("says what it could not read, and only commits once accepted", async () => {
|
||||
const storage = memoryStorage(stale);
|
||||
render(<App createPort={createInlinePort} storage={storage} urlHash={stubUrl()} />);
|
||||
expect(screen.getByText(/Unknown die “future_patch_die”/)).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Keep" }));
|
||||
expect(readSaved(storage).diceCounts).toEqual({ lucky: 4 });
|
||||
});
|
||||
});
|
||||
249
kcd2_dice_solver/src/AppLinks.test.tsx
Normal file
249
kcd2_dice_solver/src/AppLinks.test.tsx
Normal file
@ -0,0 +1,249 @@
|
||||
/** Shared-link and layout behaviour of the App shell. */
|
||||
|
||||
/**
|
||||
* End-to-end tests for the app, driving the real flow: search for a die, click
|
||||
* to add it, scroll the wheel over a counter, and get a real recommendation.
|
||||
*
|
||||
* The worker is replaced with a port that runs the *real* solver synchronously —
|
||||
* jsdom has no module-worker support, but nothing about the solver is stubbed,
|
||||
* so these exercise the actual recommendation path.
|
||||
*/
|
||||
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { App } from "./App.tsx";
|
||||
import { STORAGE_KEY, encodeInventoryHash, toBase64Url } from "./lib/inventoryIo.ts";
|
||||
import type { SavedInventory, UrlHashPort } from "./lib/inventoryIo.ts";
|
||||
import { solve } from "./core/solve.ts";
|
||||
import type { SolverPort } from "./hooks/useSolver.ts";
|
||||
import type { WorkerReply, WorkerRequest } from "./worker/solver.worker.ts";
|
||||
|
||||
/**
|
||||
* A solver port that runs the real solver in-process.
|
||||
*
|
||||
* @returns A port usable in place of the Web Worker.
|
||||
*/
|
||||
function createInlinePort(): SolverPort {
|
||||
const listeners = new Set<(event: MessageEvent<WorkerReply>) => void>();
|
||||
return {
|
||||
postMessage: ({ id, request }: WorkerRequest) => {
|
||||
let reply: WorkerReply;
|
||||
try {
|
||||
// Keep the simulation short: these tests are about the wiring.
|
||||
reply = { id, ok: true, response: solve({ ...request, simulationTurns: 200 }) };
|
||||
} catch (error) {
|
||||
reply = { id, ok: false, error: error instanceof Error ? error.message : "failed" };
|
||||
}
|
||||
for (const listener of listeners) {
|
||||
listener({ data: reply } as MessageEvent<WorkerReply>);
|
||||
}
|
||||
},
|
||||
addEventListener: (_type, listener) => listeners.add(listener),
|
||||
removeEventListener: (_type, listener) => listeners.delete(listener),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An in-memory Storage stand-in, so tests do not share persisted state.
|
||||
*
|
||||
* @param initial - Optional starting contents.
|
||||
* @returns A minimal storage object.
|
||||
*/
|
||||
function memoryStorage(initial?: string): Pick<Storage, "getItem" | "setItem"> {
|
||||
const store = new Map<string, string>();
|
||||
if (initial !== undefined) {
|
||||
store.set(STORAGE_KEY, initial);
|
||||
}
|
||||
return {
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
store.set(key, value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Read back what the app persisted, typed so assertions are not on `any`.
|
||||
*
|
||||
* @param storage - The storage the app was given.
|
||||
* @returns The parsed inventory.
|
||||
*/
|
||||
function readSaved(storage: Pick<Storage, "getItem">): SavedInventory {
|
||||
return JSON.parse(storage.getItem(STORAGE_KEY) ?? "{}") as SavedInventory;
|
||||
}
|
||||
|
||||
/**
|
||||
* A URL port that reports a fragment without touching the real location.
|
||||
*
|
||||
* @param hash - The fragment the page was "opened with".
|
||||
* @returns The port plus a record of whether the app cleared the fragment.
|
||||
*/
|
||||
function stubUrl(hash = ""): UrlHashPort & { cleared: () => number } {
|
||||
let clears = 0;
|
||||
return {
|
||||
read: () => hash,
|
||||
clear: () => {
|
||||
clears += 1;
|
||||
},
|
||||
base: () => "https://dice.example/",
|
||||
cleared: () => clears,
|
||||
};
|
||||
}
|
||||
|
||||
const renderApp = (initial?: string, urlHash: UrlHashPort = stubUrl()) =>
|
||||
render(
|
||||
<App
|
||||
createPort={createInlinePort}
|
||||
storage={memoryStorage(initial)}
|
||||
urlHash={urlHash}
|
||||
clipboard={{ writeText: () => Promise.resolve() }}
|
||||
saveFile={() => undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
describe("shared links", () => {
|
||||
const shared = encodeInventoryHash({ diceCounts: { weighted: 3 }, badgeIds: [] });
|
||||
|
||||
it("prefers a link over whatever this browser had saved", () => {
|
||||
const mine = JSON.stringify({ diceCounts: { lucky: 1 }, badgeIds: [] });
|
||||
renderApp(mine, stubUrl(shared));
|
||||
expect(screen.getByText("3 dice")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("drops the fragment so a reload does not resurrect the link", () => {
|
||||
const url = stubUrl(shared);
|
||||
renderApp(undefined, url);
|
||||
expect(url.cleared()).toBe(1);
|
||||
});
|
||||
|
||||
it("leaves the URL alone when there was no link", () => {
|
||||
const url = stubUrl();
|
||||
renderApp(undefined, url);
|
||||
expect(url.cleared()).toBe(0);
|
||||
});
|
||||
|
||||
it("does not overwrite the saved inventory until the visitor commits", () => {
|
||||
// Silently clobbering somebody's own loadout with a link they opened is
|
||||
// unrecoverable, so nothing is written until they say so.
|
||||
const storage = memoryStorage(JSON.stringify({ diceCounts: { lucky: 1 }, badgeIds: [] }));
|
||||
render(
|
||||
<App
|
||||
createPort={createInlinePort}
|
||||
storage={storage}
|
||||
urlHash={stubUrl(shared)}
|
||||
clipboard={{ writeText: () => Promise.resolve() }}
|
||||
saveFile={() => undefined}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText("3 dice")).toBeInTheDocument();
|
||||
expect(readSaved(storage).diceCounts).toEqual({ lucky: 1 });
|
||||
});
|
||||
|
||||
it("persists once Keep is pressed", async () => {
|
||||
const storage = memoryStorage();
|
||||
render(
|
||||
<App
|
||||
createPort={createInlinePort}
|
||||
storage={storage}
|
||||
urlHash={stubUrl(shared)}
|
||||
clipboard={{ writeText: () => Promise.resolve() }}
|
||||
saveFile={() => undefined}
|
||||
/>,
|
||||
);
|
||||
await userEvent.click(screen.getByRole("button", { name: "Keep" }));
|
||||
expect(readSaved(storage).diceCounts).toEqual({ weighted: 3 });
|
||||
expect(screen.queryByRole("button", { name: "Keep" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("persists as soon as the visitor edits anything, banner and all", async () => {
|
||||
const storage = memoryStorage();
|
||||
render(
|
||||
<App
|
||||
createPort={createInlinePort}
|
||||
storage={storage}
|
||||
urlHash={stubUrl(shared)}
|
||||
clipboard={{ writeText: () => Promise.resolve() }}
|
||||
saveFile={() => undefined}
|
||||
/>,
|
||||
);
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
await userEvent.click(screen.getByLabelText("Remove one Weighted die"));
|
||||
expect(readSaved(storage).diceCounts).toEqual({ weighted: 2 });
|
||||
expect(screen.queryByRole("button", { name: "Keep" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows no banner on an ordinary visit", () => {
|
||||
renderApp();
|
||||
expect(screen.queryByRole("button", { name: "Keep" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("falls through to storage when the fragment carries no inventory", () => {
|
||||
const mine = JSON.stringify({ diceCounts: { lucky: 1 }, badgeIds: [] });
|
||||
renderApp(mine, stubUrl("#nothing=here"));
|
||||
expect(screen.getByText("1 die")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps the saved inventory when the link is damaged", () => {
|
||||
const mine = JSON.stringify({ diceCounts: { lucky: 1 }, badgeIds: [] });
|
||||
// "@" is not a base64 character, so decoding throws rather than yielding
|
||||
// an inventory — the case a truncated or mangled URL actually produces.
|
||||
renderApp(mine, stubUrl("#i=@@@"));
|
||||
expect(screen.getByText("1 die")).toBeInTheDocument();
|
||||
// Nothing was taken from the link, so there is nothing to accept or refuse.
|
||||
expect(screen.queryByRole("button", { name: "Keep" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Discard" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("reports what a shared link had to drop", () => {
|
||||
const link = `#i=${toBase64Url(
|
||||
JSON.stringify({ diceCounts: { weighted: 2, nosuchdie: 1 }, badgeIds: [] }),
|
||||
)}`;
|
||||
renderApp(undefined, stubUrl(link));
|
||||
expect(screen.getByText("2 dice")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Unknown die/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("replaces the whole inventory on import", async () => {
|
||||
const storage = memoryStorage(JSON.stringify({ diceCounts: { lucky: 2 }, badgeIds: [] }));
|
||||
render(
|
||||
<App createPort={createInlinePort} storage={storage} urlHash={stubUrl()} />,
|
||||
);
|
||||
fireEvent.change(screen.getByLabelText("Inventory JSON"), {
|
||||
target: { value: '{"diceCounts":{"weighted":4},"badgeIds":[]}' },
|
||||
});
|
||||
await userEvent.click(screen.getByRole("button", { name: "Import pasted" }));
|
||||
expect(screen.getByText("4 dice")).toBeInTheDocument();
|
||||
expect(readSaved(storage).diceCounts).toEqual({ weighted: 4 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("layout", () => {
|
||||
it("gives the left column to the dice and nothing else", () => {
|
||||
renderApp();
|
||||
const inventory = document.querySelector("section.inventory");
|
||||
if (!inventory) {
|
||||
throw new Error("no inventory section");
|
||||
}
|
||||
// The search box, the title and the badges all moved to the right column so
|
||||
// the 43-row grid gets the whole vertical budget.
|
||||
expect(inventory.querySelector(".die-list")).toBeInTheDocument();
|
||||
expect(inventory.querySelector(".toolbar")).toBeNull();
|
||||
expect(inventory.querySelector("h1")).toBeNull();
|
||||
expect(inventory.querySelector(".badges")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the badges collapsed until asked for", () => {
|
||||
renderApp();
|
||||
const badges = document.querySelector("details.badges");
|
||||
expect(badges).toBeInTheDocument();
|
||||
expect(badges).not.toHaveAttribute("open");
|
||||
// Still reachable — collapsed, not removed.
|
||||
expect(within(badges as HTMLElement).getByText("Badges")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("no longer tells touch users to scroll a mouse wheel", () => {
|
||||
renderApp();
|
||||
expect(screen.queryByText(/scroll the wheel/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
173
kcd2_dice_solver/src/AppRecovery.test.tsx
Normal file
173
kcd2_dice_solver/src/AppRecovery.test.tsx
Normal file
@ -0,0 +1,173 @@
|
||||
/** How the App recovers a shared link that would clobber saved state. */
|
||||
|
||||
/** Shared-link and layout behaviour of the App shell. */
|
||||
|
||||
/**
|
||||
* End-to-end tests for the app, driving the real flow: search for a die, click
|
||||
* to add it, scroll the wheel over a counter, and get a real recommendation.
|
||||
*
|
||||
* The worker is replaced with a port that runs the *real* solver synchronously —
|
||||
* jsdom has no module-worker support, but nothing about the solver is stubbed,
|
||||
* so these exercise the actual recommendation path.
|
||||
*/
|
||||
|
||||
import { render, screen, } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { App } from "./App.tsx";
|
||||
import { STORAGE_KEY, encodeInventoryHash, } from "./lib/inventoryIo.ts";
|
||||
import type { SavedInventory, UrlHashPort } from "./lib/inventoryIo.ts";
|
||||
import { solve } from "./core/solve.ts";
|
||||
import type { SolverPort } from "./hooks/useSolver.ts";
|
||||
import type { WorkerReply, WorkerRequest } from "./worker/solver.worker.ts";
|
||||
|
||||
/**
|
||||
* A solver port that runs the real solver in-process.
|
||||
*
|
||||
* @returns A port usable in place of the Web Worker.
|
||||
*/
|
||||
function createInlinePort(): SolverPort {
|
||||
const listeners = new Set<(event: MessageEvent<WorkerReply>) => void>();
|
||||
return {
|
||||
postMessage: ({ id, request }: WorkerRequest) => {
|
||||
let reply: WorkerReply;
|
||||
try {
|
||||
// Keep the simulation short: these tests are about the wiring.
|
||||
reply = { id, ok: true, response: solve({ ...request, simulationTurns: 200 }) };
|
||||
} catch (error) {
|
||||
reply = { id, ok: false, error: error instanceof Error ? error.message : "failed" };
|
||||
}
|
||||
for (const listener of listeners) {
|
||||
listener({ data: reply } as MessageEvent<WorkerReply>);
|
||||
}
|
||||
},
|
||||
addEventListener: (_type, listener) => listeners.add(listener),
|
||||
removeEventListener: (_type, listener) => listeners.delete(listener),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An in-memory Storage stand-in, so tests do not share persisted state.
|
||||
*
|
||||
* @param initial - Optional starting contents.
|
||||
* @returns A minimal storage object.
|
||||
*/
|
||||
function memoryStorage(initial?: string): Pick<Storage, "getItem" | "setItem"> {
|
||||
const store = new Map<string, string>();
|
||||
if (initial !== undefined) {
|
||||
store.set(STORAGE_KEY, initial);
|
||||
}
|
||||
return {
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
store.set(key, value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Read back what the app persisted, typed so assertions are not on `any`.
|
||||
*
|
||||
* @param storage - The storage the app was given.
|
||||
* @returns The parsed inventory.
|
||||
*/
|
||||
function readSaved(storage: Pick<Storage, "getItem">): SavedInventory {
|
||||
return JSON.parse(storage.getItem(STORAGE_KEY) ?? "{}") as SavedInventory;
|
||||
}
|
||||
|
||||
/**
|
||||
* A URL port that reports a fragment without touching the real location.
|
||||
*
|
||||
* @param hash - The fragment the page was "opened with".
|
||||
* @returns The port plus a record of whether the app cleared the fragment.
|
||||
*/
|
||||
function stubUrl(hash = ""): UrlHashPort & { cleared: () => number } {
|
||||
let clears = 0;
|
||||
return {
|
||||
read: () => hash,
|
||||
clear: () => {
|
||||
clears += 1;
|
||||
},
|
||||
base: () => "https://dice.example/",
|
||||
cleared: () => clears,
|
||||
};
|
||||
}
|
||||
|
||||
const renderApp = (initial?: string, urlHash: UrlHashPort = stubUrl()) =>
|
||||
render(
|
||||
<App
|
||||
createPort={createInlinePort}
|
||||
storage={memoryStorage(initial)}
|
||||
urlHash={urlHash}
|
||||
clipboard={{ writeText: () => Promise.resolve() }}
|
||||
saveFile={() => undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
describe("shared links cannot destroy what is already saved", () => {
|
||||
it("ignores a link that carries no dice or badges", () => {
|
||||
// A count of zero parses cleanly, so "did the parser complain?" is the
|
||||
// wrong question — this used to blank the inventory on screen, disable
|
||||
// Clear, and leave Keep as the only enabled control, writing the emptiness
|
||||
// over the visitor's own dice.
|
||||
const mine = JSON.stringify({ diceCounts: { lucky: 4 }, badgeIds: [] });
|
||||
const empty = encodeInventoryHash({ diceCounts: { weighted: 0 }, badgeIds: [] });
|
||||
const storage = memoryStorage(mine);
|
||||
render(
|
||||
<App createPort={createInlinePort} storage={storage} urlHash={stubUrl(empty)} />,
|
||||
);
|
||||
expect(screen.getByText("4 dice")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Keep" })).not.toBeInTheDocument();
|
||||
expect(readSaved(storage).diceCounts).toEqual({ lucky: 4 });
|
||||
});
|
||||
|
||||
it("restores the visitor's own inventory when a link is discarded", async () => {
|
||||
const mine = JSON.stringify({ diceCounts: { lucky: 4 }, badgeIds: ["tin_might"] });
|
||||
const link = encodeInventoryHash({ diceCounts: { weighted: 3 }, badgeIds: [] });
|
||||
const storage = memoryStorage(mine);
|
||||
render(
|
||||
<App createPort={createInlinePort} storage={storage} urlHash={stubUrl(link)} />,
|
||||
);
|
||||
expect(screen.getByText("3 dice")).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Discard" }));
|
||||
expect(screen.getByText("4 dice")).toBeInTheDocument();
|
||||
expect(readSaved(storage)).toEqual({
|
||||
diceCounts: { lucky: 4 },
|
||||
badgeIds: ["tin_might"],
|
||||
});
|
||||
});
|
||||
|
||||
it("clears a fragment even when it decoded to nothing", () => {
|
||||
// A fragment left in the bar is read again on the next reload, where it
|
||||
// would land on top of whatever has been edited since.
|
||||
for (const hash of ["#i=@@@", "#other=1", "#i="]) {
|
||||
const url = stubUrl(hash);
|
||||
renderApp(undefined, url);
|
||||
expect(url.cleared()).toBe(1);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("a saved inventory that no longer parses cleanly", () => {
|
||||
const stale = JSON.stringify({
|
||||
diceCounts: { lucky: 4, future_patch_die: 6 },
|
||||
badgeIds: [],
|
||||
});
|
||||
|
||||
it("is not silently truncated in storage on load", () => {
|
||||
const storage = memoryStorage(stale);
|
||||
render(<App createPort={createInlinePort} storage={storage} urlHash={stubUrl()} />);
|
||||
// Still the original text: nothing was written over it on first paint.
|
||||
expect(readSaved(storage).diceCounts).toEqual({ lucky: 4, future_patch_die: 6 });
|
||||
});
|
||||
|
||||
it("says what it could not read, and only commits once accepted", async () => {
|
||||
const storage = memoryStorage(stale);
|
||||
render(<App createPort={createInlinePort} storage={storage} urlHash={stubUrl()} />);
|
||||
expect(screen.getByText(/Unknown die “future_patch_die”/)).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Keep" }));
|
||||
expect(readSaved(storage).diceCounts).toEqual({ lucky: 4 });
|
||||
});
|
||||
});
|
||||
227
kcd2_dice_solver/src/AppShell.test.tsx
Normal file
227
kcd2_dice_solver/src/AppShell.test.tsx
Normal file
@ -0,0 +1,227 @@
|
||||
/** The App shell's core behaviour. */
|
||||
|
||||
/**
|
||||
* End-to-end tests for the app, driving the real flow: search for a die, click
|
||||
* to add it, scroll the wheel over a counter, and get a real recommendation.
|
||||
*
|
||||
* The worker is replaced with a port that runs the *real* solver synchronously —
|
||||
* jsdom has no module-worker support, but nothing about the solver is stubbed,
|
||||
* so these exercise the actual recommendation path.
|
||||
*/
|
||||
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { App } from "./App.tsx";
|
||||
import { STORAGE_KEY, } from "./lib/inventoryIo.ts";
|
||||
import type { SavedInventory, UrlHashPort } from "./lib/inventoryIo.ts";
|
||||
import { solve } from "./core/solve.ts";
|
||||
import type { SolverPort } from "./hooks/useSolver.ts";
|
||||
import type { WorkerReply, WorkerRequest } from "./worker/solver.worker.ts";
|
||||
|
||||
/**
|
||||
* A solver port that runs the real solver in-process.
|
||||
*
|
||||
* @returns A port usable in place of the Web Worker.
|
||||
*/
|
||||
function createInlinePort(): SolverPort {
|
||||
const listeners = new Set<(event: MessageEvent<WorkerReply>) => void>();
|
||||
return {
|
||||
postMessage: ({ id, request }: WorkerRequest) => {
|
||||
let reply: WorkerReply;
|
||||
try {
|
||||
// Keep the simulation short: these tests are about the wiring.
|
||||
reply = { id, ok: true, response: solve({ ...request, simulationTurns: 200 }) };
|
||||
} catch (error) {
|
||||
reply = { id, ok: false, error: error instanceof Error ? error.message : "failed" };
|
||||
}
|
||||
for (const listener of listeners) {
|
||||
listener({ data: reply } as MessageEvent<WorkerReply>);
|
||||
}
|
||||
},
|
||||
addEventListener: (_type, listener) => listeners.add(listener),
|
||||
removeEventListener: (_type, listener) => listeners.delete(listener),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An in-memory Storage stand-in, so tests do not share persisted state.
|
||||
*
|
||||
* @param initial - Optional starting contents.
|
||||
* @returns A minimal storage object.
|
||||
*/
|
||||
function memoryStorage(initial?: string): Pick<Storage, "getItem" | "setItem"> {
|
||||
const store = new Map<string, string>();
|
||||
if (initial !== undefined) {
|
||||
store.set(STORAGE_KEY, initial);
|
||||
}
|
||||
return {
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
store.set(key, value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Read back what the app persisted, typed so assertions are not on `any`.
|
||||
*
|
||||
* @param storage - The storage the app was given.
|
||||
* @returns The parsed inventory.
|
||||
*/
|
||||
function readSaved(storage: Pick<Storage, "getItem">): SavedInventory {
|
||||
return JSON.parse(storage.getItem(STORAGE_KEY) ?? "{}") as SavedInventory;
|
||||
}
|
||||
|
||||
/**
|
||||
* A URL port that reports a fragment without touching the real location.
|
||||
*
|
||||
* @param hash - The fragment the page was "opened with".
|
||||
* @returns The port plus a record of whether the app cleared the fragment.
|
||||
*/
|
||||
function stubUrl(hash = ""): UrlHashPort & { cleared: () => number } {
|
||||
let clears = 0;
|
||||
return {
|
||||
read: () => hash,
|
||||
clear: () => {
|
||||
clears += 1;
|
||||
},
|
||||
base: () => "https://dice.example/",
|
||||
cleared: () => clears,
|
||||
};
|
||||
}
|
||||
|
||||
const renderApp = (initial?: string, urlHash: UrlHashPort = stubUrl()) =>
|
||||
render(
|
||||
<App
|
||||
createPort={createInlinePort}
|
||||
storage={memoryStorage(initial)}
|
||||
urlHash={urlHash}
|
||||
clipboard={{ writeText: () => Promise.resolve() }}
|
||||
saveFile={() => undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
describe("App", () => {
|
||||
it("asks for dice before anything is entered", () => {
|
||||
renderApp();
|
||||
expect(screen.getByText(/Add at least six dice/)).toBeInTheDocument();
|
||||
expect(screen.getByText("0 dice")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("finds a die by fuzzy search, adds six by clicking, and solves", async () => {
|
||||
renderApp();
|
||||
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
const row = screen.getAllByRole("listitem")[0];
|
||||
const add = within(row).getByRole("button", { name: "Weighted die" });
|
||||
|
||||
for (let i = 0; i < 6; i += 1) {
|
||||
await userEvent.click(add);
|
||||
}
|
||||
|
||||
expect(screen.getByText("6 dice")).toBeInTheDocument();
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Best loadout")).toBeInTheDocument();
|
||||
});
|
||||
// Six Weighted dice is the right answer and the panel must name it.
|
||||
expect(screen.getByText("6×")).toBeInTheDocument();
|
||||
expect(screen.getByText("Weighted die")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Provably optimal/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("adds dice by scrolling the wheel over the counter", async () => {
|
||||
renderApp();
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
const counter = screen.getByLabelText("How many Weighted die");
|
||||
const stepper = counter.parentElement;
|
||||
if (!stepper) {
|
||||
throw new Error("no stepper");
|
||||
}
|
||||
|
||||
for (let i = 0; i < 6; i += 1) {
|
||||
fireEvent.wheel(stepper, { deltaY: -120 });
|
||||
}
|
||||
expect(screen.getByLabelText("How many Weighted die")).toHaveTextContent("6");
|
||||
expect(screen.getByText("6 dice")).toBeInTheDocument();
|
||||
|
||||
fireEvent.wheel(stepper, { deltaY: 120 });
|
||||
expect(screen.getByLabelText("How many Weighted die")).toHaveTextContent("5");
|
||||
expect(screen.getByText("5 dice")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("accumulates a rapid burst of clicks and wheel ticks", async () => {
|
||||
// Driving the real app in headless Chrome caught this: six fast clicks used
|
||||
// to land as one, because each handler computed from the count captured at
|
||||
// render time. React batches faster than it re-renders.
|
||||
renderApp();
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
|
||||
const row = screen.getAllByRole("listitem")[0];
|
||||
const add = within(row).getByRole("button", { name: "Weighted die" });
|
||||
act(() => {
|
||||
for (let i = 0; i < 4; i += 1) {
|
||||
fireEvent.click(add);
|
||||
}
|
||||
});
|
||||
expect(screen.getByLabelText("How many Weighted die")).toHaveTextContent("4");
|
||||
|
||||
const stepper = screen.getByLabelText("How many Weighted die").parentElement;
|
||||
if (!stepper) {
|
||||
throw new Error("no stepper");
|
||||
}
|
||||
act(() => {
|
||||
for (let i = 0; i < 2; i += 1) {
|
||||
fireEvent.wheel(stepper, { deltaY: -120 });
|
||||
}
|
||||
});
|
||||
expect(screen.getByLabelText("How many Weighted die")).toHaveTextContent("6");
|
||||
expect(screen.getByText("6 dice")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("ranks the badges you own alongside the dice", async () => {
|
||||
const saved = JSON.stringify({
|
||||
diceCounts: { weighted: 6 },
|
||||
badgeIds: ["gold_emperors", "gold_defence"],
|
||||
});
|
||||
renderApp(saved);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Best badge per tier")).toBeInTheDocument();
|
||||
});
|
||||
// The name also appears in the ownership checkbox, so scope to the result.
|
||||
const results = document.querySelector(".result");
|
||||
if (!results) {
|
||||
throw new Error("no result panel");
|
||||
}
|
||||
expect(within(results as HTMLElement).getByText("Gold Emperor's badge")).toBeInTheDocument();
|
||||
// The Defence badge is owned too, and must be reported as situational
|
||||
// rather than given an invented number.
|
||||
expect(within(results as HTMLElement).getByText(/situational/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("restores a saved inventory on load", () => {
|
||||
renderApp(JSON.stringify({ diceCounts: { weighted: 4 }, badgeIds: [] }));
|
||||
expect(screen.getByText("4 dice")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("persists changes for next time", async () => {
|
||||
const storage = memoryStorage();
|
||||
render(<App createPort={createInlinePort} storage={storage} />);
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
await userEvent.click(screen.getByLabelText("Add one Weighted die"));
|
||||
|
||||
expect(readSaved(storage)).toEqual({ diceCounts: { weighted: 1 }, badgeIds: [] });
|
||||
});
|
||||
|
||||
it("clears everything on request", async () => {
|
||||
renderApp(JSON.stringify({ diceCounts: { weighted: 6 }, badgeIds: ["tin_might"] }));
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Best loadout")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Clear" }));
|
||||
expect(screen.getByText("0 dice")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Add at least six dice/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
180
kcd2_dice_solver/src/AppStorage.test.tsx
Normal file
180
kcd2_dice_solver/src/AppStorage.test.tsx
Normal file
@ -0,0 +1,180 @@
|
||||
/** How the App shell falls back to browser storage. */
|
||||
|
||||
/** The App shell's core behaviour. */
|
||||
|
||||
/**
|
||||
* End-to-end tests for the app, driving the real flow: search for a die, click
|
||||
* to add it, scroll the wheel over a counter, and get a real recommendation.
|
||||
*
|
||||
* The worker is replaced with a port that runs the *real* solver synchronously —
|
||||
* jsdom has no module-worker support, but nothing about the solver is stubbed,
|
||||
* so these exercise the actual recommendation path.
|
||||
*/
|
||||
|
||||
import { render, screen, waitFor, } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { App } from "./App.tsx";
|
||||
import { STORAGE_KEY, } from "./lib/inventoryIo.ts";
|
||||
import type { SavedInventory, UrlHashPort } from "./lib/inventoryIo.ts";
|
||||
import { solve } from "./core/solve.ts";
|
||||
import type { SolverPort } from "./hooks/useSolver.ts";
|
||||
import type { WorkerReply, WorkerRequest } from "./worker/solver.worker.ts";
|
||||
|
||||
/**
|
||||
* A solver port that runs the real solver in-process.
|
||||
*
|
||||
* @returns A port usable in place of the Web Worker.
|
||||
*/
|
||||
function createInlinePort(): SolverPort {
|
||||
const listeners = new Set<(event: MessageEvent<WorkerReply>) => void>();
|
||||
return {
|
||||
postMessage: ({ id, request }: WorkerRequest) => {
|
||||
let reply: WorkerReply;
|
||||
try {
|
||||
// Keep the simulation short: these tests are about the wiring.
|
||||
reply = { id, ok: true, response: solve({ ...request, simulationTurns: 200 }) };
|
||||
} catch (error) {
|
||||
reply = { id, ok: false, error: error instanceof Error ? error.message : "failed" };
|
||||
}
|
||||
for (const listener of listeners) {
|
||||
listener({ data: reply } as MessageEvent<WorkerReply>);
|
||||
}
|
||||
},
|
||||
addEventListener: (_type, listener) => listeners.add(listener),
|
||||
removeEventListener: (_type, listener) => listeners.delete(listener),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An in-memory Storage stand-in, so tests do not share persisted state.
|
||||
*
|
||||
* @param initial - Optional starting contents.
|
||||
* @returns A minimal storage object.
|
||||
*/
|
||||
function memoryStorage(initial?: string): Pick<Storage, "getItem" | "setItem"> {
|
||||
const store = new Map<string, string>();
|
||||
if (initial !== undefined) {
|
||||
store.set(STORAGE_KEY, initial);
|
||||
}
|
||||
return {
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
store.set(key, value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Read back what the app persisted, typed so assertions are not on `any`.
|
||||
*
|
||||
* @param storage - The storage the app was given.
|
||||
* @returns The parsed inventory.
|
||||
*/
|
||||
function readSaved(storage: Pick<Storage, "getItem">): SavedInventory {
|
||||
return JSON.parse(storage.getItem(STORAGE_KEY) ?? "{}") as SavedInventory;
|
||||
}
|
||||
|
||||
/**
|
||||
* A URL port that reports a fragment without touching the real location.
|
||||
*
|
||||
* @param hash - The fragment the page was "opened with".
|
||||
* @returns The port plus a record of whether the app cleared the fragment.
|
||||
*/
|
||||
function stubUrl(hash = ""): UrlHashPort & { cleared: () => number } {
|
||||
let clears = 0;
|
||||
return {
|
||||
read: () => hash,
|
||||
clear: () => {
|
||||
clears += 1;
|
||||
},
|
||||
base: () => "https://dice.example/",
|
||||
cleared: () => clears,
|
||||
};
|
||||
}
|
||||
|
||||
const renderApp = (initial?: string, urlHash: UrlHashPort = stubUrl()) =>
|
||||
render(
|
||||
<App
|
||||
createPort={createInlinePort}
|
||||
storage={memoryStorage(initial)}
|
||||
urlHash={urlHash}
|
||||
clipboard={{ writeText: () => Promise.resolve() }}
|
||||
saveFile={() => undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
describe("App storage", () => {
|
||||
it("falls back to the browser's own storage when none is injected", () => {
|
||||
window.localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({ diceCounts: { weighted: 2 }, badgeIds: [] }),
|
||||
);
|
||||
render(<App createPort={createInlinePort} />);
|
||||
expect(screen.getByText("2 dice")).toBeInTheDocument();
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
it("disables Clear when there is nothing to clear", () => {
|
||||
renderApp();
|
||||
expect(screen.getByRole("button", { name: "Clear" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("drops a die from the inventory when its count reaches zero", async () => {
|
||||
const storage = memoryStorage(
|
||||
JSON.stringify({ diceCounts: { weighted: 1 }, badgeIds: [] }),
|
||||
);
|
||||
render(<App createPort={createInlinePort} storage={storage} />);
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
await userEvent.click(screen.getByLabelText("Remove one Weighted die"));
|
||||
|
||||
expect(readSaved(storage)).toEqual({ diceCounts: {}, badgeIds: [] });
|
||||
});
|
||||
|
||||
it("toggles a badge on and off", async () => {
|
||||
const storage = memoryStorage();
|
||||
render(<App createPort={createInlinePort} storage={storage} />);
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "emperor");
|
||||
|
||||
const checkbox = screen.getByRole("checkbox");
|
||||
await userEvent.click(checkbox);
|
||||
expect(readSaved(storage).badgeIds).toEqual(["gold_emperors"]);
|
||||
|
||||
await userEvent.click(checkbox);
|
||||
expect(readSaved(storage).badgeIds).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses the singular for a single die", async () => {
|
||||
renderApp();
|
||||
await userEvent.type(screen.getByLabelText("Search dice and badges"), "wei");
|
||||
await userEvent.click(screen.getByLabelText("Add one Weighted die"));
|
||||
expect(screen.getByText("1 die")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("surfaces a solver error rather than showing nothing", async () => {
|
||||
// A port that always fails, standing in for a worker that threw.
|
||||
const failingPort = (): SolverPort => {
|
||||
const listeners = new Set<(event: MessageEvent<WorkerReply>) => void>();
|
||||
return {
|
||||
postMessage: ({ id }: WorkerRequest) => {
|
||||
for (const listener of listeners) {
|
||||
listener({ data: { id, ok: false, error: "solver exploded" } } as MessageEvent<
|
||||
WorkerReply
|
||||
>);
|
||||
}
|
||||
},
|
||||
addEventListener: (_type, listener) => listeners.add(listener),
|
||||
removeEventListener: (_type, listener) => listeners.delete(listener),
|
||||
};
|
||||
};
|
||||
render(
|
||||
<App
|
||||
createPort={failingPort}
|
||||
storage={memoryStorage(JSON.stringify({ diceCounts: { weighted: 6 }, badgeIds: [] }))}
|
||||
/>,
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("solver exploded")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
164
kcd2_dice_solver/src/components/componentInventory.test.tsx
Normal file
164
kcd2_dice_solver/src/components/componentInventory.test.tsx
Normal file
@ -0,0 +1,164 @@
|
||||
/** Inventory IO component tests. */
|
||||
|
||||
/** Result panel and inventory IO component tests. */
|
||||
|
||||
/** Badge picker and result panel component tests. */
|
||||
|
||||
/** Row, list and picker component tests. */
|
||||
|
||||
/**
|
||||
* Component tests for the three ways of entering an inventory: clicking a die,
|
||||
* scrolling the wheel over its counter, and fuzzy-searching by name.
|
||||
*/
|
||||
|
||||
import { fireEvent, render, screen, waitFor, } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { SavedInventory } from "../lib/inventoryIo.ts";
|
||||
import { InventoryIo } from "./InventoryIo.tsx";
|
||||
import type { InventoryIoProps } from "./InventoryIo.tsx";
|
||||
|
||||
/**
|
||||
* Apply the updater a component emitted, to assert on the resulting count.
|
||||
*
|
||||
* @param mock - The mocked onChange.
|
||||
* @param previous - The count it should be applied to.
|
||||
* @param call - Which call to read, counting from the end by default.
|
||||
* @returns The count the component asked for.
|
||||
*/
|
||||
|
||||
|
||||
describe("InventoryIo", () => {
|
||||
const inventory: SavedInventory = {
|
||||
diceCounts: { weighted: 2 },
|
||||
badgeIds: ["tin_might"],
|
||||
};
|
||||
|
||||
/**
|
||||
* Render the panel with every port stubbed, and open it.
|
||||
*
|
||||
* @param overrides - Ports or handlers to replace.
|
||||
* @returns The stubs the caller will want to assert on.
|
||||
*/
|
||||
function setup(overrides: Partial<InventoryIoProps> = {}) {
|
||||
const onImport = vi.fn();
|
||||
const saveFile = vi.fn();
|
||||
const clipboard = { writeText: vi.fn<(text: string) => Promise<void>>().mockResolvedValue() };
|
||||
render(
|
||||
<InventoryIo
|
||||
inventory={inventory}
|
||||
onImport={onImport}
|
||||
clipboard={clipboard}
|
||||
saveFile={saveFile}
|
||||
shareUrl="https://dice.example/#i=abc"
|
||||
{...overrides}
|
||||
/>,
|
||||
);
|
||||
return { onImport, saveFile, clipboard };
|
||||
}
|
||||
|
||||
it("starts collapsed so it costs no vertical space", () => {
|
||||
setup();
|
||||
expect(screen.getByText("Import / export").closest("details")).not.toHaveAttribute("open");
|
||||
});
|
||||
|
||||
it("downloads the inventory as parseable JSON", async () => {
|
||||
const { saveFile } = setup();
|
||||
await userEvent.click(screen.getByRole("button", { name: "Download .json" }));
|
||||
expect(saveFile).toHaveBeenCalledTimes(1);
|
||||
const [filename, body] = saveFile.mock.calls[0] as [string, string];
|
||||
expect(filename).toBe("kcd2-dice.json");
|
||||
expect(JSON.parse(body)).toEqual(inventory);
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Saved kcd2-dice.json.");
|
||||
});
|
||||
|
||||
it("copies the JSON to the clipboard", async () => {
|
||||
const { clipboard } = setup();
|
||||
await userEvent.click(screen.getByRole("button", { name: "Copy JSON" }));
|
||||
expect(JSON.parse(clipboard.writeText.mock.calls[0][0])).toEqual(inventory);
|
||||
await screen.findByText("JSON copied.");
|
||||
});
|
||||
|
||||
it("copies the share link", async () => {
|
||||
const { clipboard } = setup();
|
||||
await userEvent.click(screen.getByRole("button", { name: "Copy link" }));
|
||||
expect(clipboard.writeText).toHaveBeenCalledWith("https://dice.example/#i=abc");
|
||||
await screen.findByText("Link copied.");
|
||||
});
|
||||
|
||||
it("falls back to the textarea when the clipboard refuses", async () => {
|
||||
// Insecure origins reject; the payload must still be reachable by hand.
|
||||
const clipboard = {
|
||||
writeText: vi.fn<(text: string) => Promise<void>>().mockRejectedValue(new Error("denied")),
|
||||
};
|
||||
setup({ clipboard });
|
||||
await userEvent.click(screen.getByRole("button", { name: "Copy JSON" }));
|
||||
await screen.findByText(/Copy failed/);
|
||||
const box = screen.getByLabelText<HTMLTextAreaElement>("Inventory JSON");
|
||||
expect(JSON.parse(box.value)).toEqual(inventory);
|
||||
});
|
||||
|
||||
it("imports a pasted inventory", async () => {
|
||||
const { onImport } = setup();
|
||||
// fireEvent rather than userEvent.type: the latter treats "{" and "[" as
|
||||
// key-descriptor syntax, which mangles JSON.
|
||||
fireEvent.change(screen.getByLabelText("Inventory JSON"), {
|
||||
target: { value: JSON.stringify({ diceCounts: { lucky: 3 }, badgeIds: [] }) },
|
||||
});
|
||||
await userEvent.click(screen.getByRole("button", { name: "Import pasted" }));
|
||||
expect(onImport).toHaveBeenCalledWith({ diceCounts: { lucky: 3 }, badgeIds: [] });
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Imported.");
|
||||
});
|
||||
|
||||
it("refuses an unusable payload without calling onImport", async () => {
|
||||
const { onImport } = setup();
|
||||
fireEvent.change(screen.getByLabelText("Inventory JSON"), { target: { value: "{not json" } });
|
||||
await userEvent.click(screen.getByRole("button", { name: "Import pasted" }));
|
||||
expect(onImport).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Nothing imported. Not valid JSON.");
|
||||
});
|
||||
|
||||
it("imports what it can and says what it ignored", async () => {
|
||||
const { onImport } = setup();
|
||||
fireEvent.change(screen.getByLabelText("Inventory JSON"), {
|
||||
target: { value: '{"diceCounts":{"lucky":1,"nope":2},"badgeIds":[]}' },
|
||||
});
|
||||
await userEvent.click(screen.getByRole("button", { name: "Import pasted" }));
|
||||
expect(onImport).toHaveBeenCalledWith({ diceCounts: { lucky: 1 }, badgeIds: [] });
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Ignored: Unknown die “nope”.");
|
||||
});
|
||||
|
||||
it("keeps the import button disabled until something is pasted", () => {
|
||||
setup();
|
||||
expect(screen.getByRole("button", { name: "Import pasted" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("imports an uploaded file", async () => {
|
||||
const { onImport } = setup();
|
||||
const file = new File([JSON.stringify({ diceCounts: { lucky: 5 }, badgeIds: [] })], "inv.json", {
|
||||
type: "application/json",
|
||||
});
|
||||
await userEvent.upload(screen.getByLabelText(/Load a .json file/), file);
|
||||
await waitFor(() => {
|
||||
expect(onImport).toHaveBeenCalledWith({ diceCounts: { lucky: 5 }, badgeIds: [] });
|
||||
});
|
||||
});
|
||||
|
||||
it("does nothing when the file picker is dismissed", () => {
|
||||
const { onImport } = setup();
|
||||
const input = screen.getByLabelText(/Load a .json file/);
|
||||
fireEvent.change(input, { target: { files: [] } });
|
||||
expect(onImport).not.toHaveBeenCalled();
|
||||
fireEvent.change(input, { target: { files: null } });
|
||||
expect(onImport).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports a file it cannot read", async () => {
|
||||
const { onImport } = setup();
|
||||
const unreadable = new File(["x"], "bad.json", { type: "application/json" });
|
||||
vi.spyOn(unreadable, "text").mockRejectedValue(new Error("I/O"));
|
||||
await userEvent.upload(screen.getByLabelText(/Load a .json file/), unreadable);
|
||||
await screen.findByText("Could not read that file.");
|
||||
expect(onImport).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
71
kcd2_dice_solver/src/components/componentPickers.test.tsx
Normal file
71
kcd2_dice_solver/src/components/componentPickers.test.tsx
Normal file
@ -0,0 +1,71 @@
|
||||
/** Badge picker and result panel component tests. */
|
||||
|
||||
/** Row, list and picker component tests. */
|
||||
|
||||
/**
|
||||
* Component tests for the three ways of entering an inventory: clicking a die,
|
||||
* scrolling the wheel over its counter, and fuzzy-searching by name.
|
||||
*/
|
||||
|
||||
import { render, screen, } from "@testing-library/react";
|
||||
import { ordinary } from "../test/fixtures.ts";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { Die } from "../data/dice.ts";
|
||||
import { BadgePicker } from "./BadgePicker.tsx";
|
||||
import { summariseDice } from "./ResultPanel.tsx";
|
||||
|
||||
/**
|
||||
* Apply the updater a component emitted, to assert on the resulting count.
|
||||
*
|
||||
* @param mock - The mocked onChange.
|
||||
* @param previous - The count it should be applied to.
|
||||
* @param call - Which call to read, counting from the end by default.
|
||||
* @returns The count the component asked for.
|
||||
*/
|
||||
|
||||
|
||||
describe("BadgePicker", () => {
|
||||
it("groups badges under their tier", () => {
|
||||
render(<BadgePicker query="" owned={new Set()} onToggle={vi.fn()} />);
|
||||
expect(screen.getByRole("heading", { name: "tin" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { name: "silver" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { name: "gold" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("hides a tier with no matching badge", () => {
|
||||
render(<BadgePicker query="emperor" owned={new Set()} onToggle={vi.fn()} />);
|
||||
expect(screen.queryByRole("heading", { name: "tin" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { name: "gold" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("reflects which badges are owned", () => {
|
||||
render(<BadgePicker query="emperor" owned={new Set(["gold_emperors"])} onToggle={vi.fn()} />);
|
||||
expect(screen.getByRole("checkbox")).toBeChecked();
|
||||
});
|
||||
|
||||
it("reports a toggle in both directions", async () => {
|
||||
const onToggle = vi.fn();
|
||||
const { rerender } = render(
|
||||
<BadgePicker query="emperor" owned={new Set()} onToggle={onToggle} />,
|
||||
);
|
||||
await userEvent.click(screen.getByRole("checkbox"));
|
||||
expect(onToggle).toHaveBeenLastCalledWith("gold_emperors", true);
|
||||
|
||||
rerender(
|
||||
<BadgePicker query="emperor" owned={new Set(["gold_emperors"])} onToggle={onToggle} />,
|
||||
);
|
||||
await userEvent.click(screen.getByRole("checkbox"));
|
||||
expect(onToggle).toHaveBeenLastCalledWith("gold_emperors", false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("summariseDice", () => {
|
||||
it("collapses duplicates and orders by count", () => {
|
||||
const weighted: Die = { ...ordinary, id: "weighted", name: "Weighted die" };
|
||||
expect(summariseDice([ordinary, weighted, weighted, weighted])).toEqual([
|
||||
{ die: weighted, count: 3 },
|
||||
{ die: ordinary, count: 1 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
145
kcd2_dice_solver/src/components/componentResult.test.tsx
Normal file
145
kcd2_dice_solver/src/components/componentResult.test.tsx
Normal file
@ -0,0 +1,145 @@
|
||||
/** Result panel and inventory IO component tests. */
|
||||
|
||||
/** Badge picker and result panel component tests. */
|
||||
|
||||
/** Row, list and picker component tests. */
|
||||
|
||||
/**
|
||||
* Component tests for the three ways of entering an inventory: clicking a die,
|
||||
* scrolling the wheel over its counter, and fuzzy-searching by name.
|
||||
*/
|
||||
|
||||
import { render, screen, } from "@testing-library/react";
|
||||
import { ordinary, response } from "../test/fixtures.ts";
|
||||
import { describe, expect, it, } from "vitest";
|
||||
import type { Die } from "../data/dice.ts";
|
||||
import type { SolveResponse } from "../core/solve.ts";
|
||||
import { ResultPanel, } from "./ResultPanel.tsx";
|
||||
|
||||
/**
|
||||
* Apply the updater a component emitted, to assert on the resulting count.
|
||||
*
|
||||
* @param mock - The mocked onChange.
|
||||
* @param previous - The count it should be applied to.
|
||||
* @param call - Which call to read, counting from the end by default.
|
||||
* @returns The count the component asked for.
|
||||
*/
|
||||
|
||||
|
||||
describe("ResultPanel", () => {
|
||||
it("prompts for dice before the first solve", () => {
|
||||
render(<ResultPanel result={null} error={null} solving={false} />);
|
||||
expect(screen.getByText(/Add at least six dice/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("says it is working while a solve is in flight", () => {
|
||||
render(<ResultPanel result={null} error={null} solving />);
|
||||
expect(screen.getByText("Solving…")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows an error instead of a stale answer", () => {
|
||||
render(<ResultPanel result={null} error="Need at least 6 dice" solving={false} />);
|
||||
expect(screen.getByText("Need at least 6 dice")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the loadout and its numbers", () => {
|
||||
render(<ResultPanel result={response} error={null} solving={false} />);
|
||||
expect(screen.getByText("6×")).toBeInTheDocument();
|
||||
expect(screen.getByText("Ordinary die")).toBeInTheDocument();
|
||||
expect(screen.getByText("399")).toBeInTheDocument();
|
||||
expect(screen.getByText("3.09%")).toBeInTheDocument();
|
||||
expect(screen.getByText("900")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("says when the answer is proven rather than merely good", () => {
|
||||
render(<ResultPanel result={response} error={null} solving={false} />);
|
||||
expect(screen.getByText(/Provably optimal/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("admits when the answer is only a local search result", () => {
|
||||
render(
|
||||
<ResultPanel result={{ ...response, optimal: false }} error={null} solving={false} />,
|
||||
);
|
||||
expect(screen.getByText(/not proven/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("lists runners-up when there are any", () => {
|
||||
const withAlternatives: SolveResponse = {
|
||||
...response,
|
||||
alternatives: [
|
||||
{ dice: new Array<Die>(6).fill(ordinary), evaluation: response.evaluation },
|
||||
],
|
||||
};
|
||||
render(<ResultPanel result={withAlternatives} error={null} solving={false} />);
|
||||
expect(screen.getByText("Runners-up")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("asks for badges when none are owned", () => {
|
||||
render(<ResultPanel result={response} error={null} solving={false} />);
|
||||
expect(screen.getByText(/Tick the badges you own/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the pick, its value and its reasoning for each tier", () => {
|
||||
const withBadges: SolveResponse = {
|
||||
...response,
|
||||
badges: [
|
||||
{
|
||||
tier: "gold",
|
||||
ranked: [
|
||||
{
|
||||
badge: {
|
||||
id: "gold_emperors",
|
||||
name: "Gold Emperor's badge",
|
||||
description: "",
|
||||
tier: "gold",
|
||||
effect: { kind: "scoring", rules: { emperorTriple: true } },
|
||||
},
|
||||
pointsPerGame: 1234,
|
||||
reason: "Changes the scoring table.",
|
||||
dice: new Array<Die>(6).fill(ordinary),
|
||||
},
|
||||
{
|
||||
badge: {
|
||||
id: "gold_warlord",
|
||||
name: "Gold Warlord badge",
|
||||
description: "",
|
||||
tier: "gold",
|
||||
effect: { kind: "multiplier", factor: 2, uses: 1 },
|
||||
},
|
||||
pointsPerGame: 567,
|
||||
reason: "Doubles a good turn.",
|
||||
dice: null,
|
||||
},
|
||||
{
|
||||
badge: {
|
||||
id: "gold_defence",
|
||||
name: "Gold Defence badge",
|
||||
description: "",
|
||||
tier: "gold",
|
||||
effect: { kind: "defence" },
|
||||
},
|
||||
pointsPerGame: null,
|
||||
reason: "Situational.",
|
||||
dice: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
render(<ResultPanel result={withBadges} error={null} solving={false} />);
|
||||
expect(screen.getByText("Gold Emperor's badge")).toBeInTheDocument();
|
||||
expect(screen.getByText(/~1,234 pts\/game/)).toBeInTheDocument();
|
||||
expect(screen.getByText("Changes the scoring table.")).toBeInTheDocument();
|
||||
expect(screen.getByText(/With this badge, bring/)).toBeInTheDocument();
|
||||
// The runners-up list renders both a valued badge and a situational one.
|
||||
expect(screen.getByText(/Gold Warlord badge — ~567 pts\/game/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Gold Defence badge — situational/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("dims the panel while a fresh solve is running", () => {
|
||||
const { container } = render(
|
||||
<ResultPanel result={response} error={null} solving />,
|
||||
);
|
||||
expect(container.querySelector(".result")).toHaveClass("stale");
|
||||
});
|
||||
});
|
||||
120
kcd2_dice_solver/src/components/componentRows.test.tsx
Normal file
120
kcd2_dice_solver/src/components/componentRows.test.tsx
Normal file
@ -0,0 +1,120 @@
|
||||
/** Row, list and picker component tests. */
|
||||
|
||||
/**
|
||||
* Component tests for the three ways of entering an inventory: clicking a die,
|
||||
* scrolling the wheel over its counter, and fuzzy-searching by name.
|
||||
*/
|
||||
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { MAX_PER_DIE } from "../data/dice.ts";
|
||||
import type { Die } from "../data/dice.ts";
|
||||
import { DiceList } from "./DiceList.tsx";
|
||||
import { DieRow, } from "./DieRow.tsx";
|
||||
|
||||
/**
|
||||
* Apply the updater a component emitted, to assert on the resulting count.
|
||||
*
|
||||
* @param mock - The mocked onChange.
|
||||
* @param previous - The count it should be applied to.
|
||||
* @param call - Which call to read, counting from the end by default.
|
||||
* @returns The count the component asked for.
|
||||
*/
|
||||
function applied(
|
||||
mock: { mock: { calls: unknown[][] } },
|
||||
previous: number,
|
||||
call = mock.mock.calls.length - 1,
|
||||
): number {
|
||||
const update = mock.mock.calls[call][0] as (p: number) => number;
|
||||
return update(previous);
|
||||
}
|
||||
|
||||
const ordinary: Die = {
|
||||
id: "ordinary",
|
||||
name: "Ordinary die",
|
||||
description: "An ordinary playing die.",
|
||||
weights: [1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6],
|
||||
wildcardFaces: [],
|
||||
wildScoresAlone: false,
|
||||
};
|
||||
|
||||
describe("DieRow", () => {
|
||||
it("adds one die when the row is clicked", async () => {
|
||||
const onChange = vi.fn();
|
||||
render(<DieRow die={ordinary} count={0} highlight={[]} onChange={onChange} />);
|
||||
await userEvent.click(screen.getByRole("button", { name: "Ordinary die" }));
|
||||
expect(applied(onChange, 0)).toBe(1);
|
||||
});
|
||||
|
||||
it("stops at the maximum when clicked repeatedly", async () => {
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<DieRow die={ordinary} count={MAX_PER_DIE} highlight={[]} onChange={onChange} />,
|
||||
);
|
||||
await userEvent.click(screen.getByRole("button", { name: "Ordinary die" }));
|
||||
expect(applied(onChange, MAX_PER_DIE)).toBe(MAX_PER_DIE);
|
||||
});
|
||||
|
||||
it("marks a row you own", () => {
|
||||
const { container } = render(
|
||||
<DieRow die={ordinary} count={2} highlight={[]} onChange={vi.fn()} />,
|
||||
);
|
||||
expect(container.querySelector(".die-row")).toHaveClass("owned");
|
||||
});
|
||||
|
||||
it("tags the wildcard dice", () => {
|
||||
const balatro: Die = {
|
||||
...ordinary,
|
||||
id: "balatro",
|
||||
wildcardFaces: [1],
|
||||
wildScoresAlone: true,
|
||||
};
|
||||
render(<DieRow die={balatro} count={0} highlight={[]} onChange={vi.fn()} />);
|
||||
expect(screen.getByText("wild")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("DiceList", () => {
|
||||
it("shows every die when the query is empty", () => {
|
||||
render(<DiceList query="" counts={{}} onChange={vi.fn()} />);
|
||||
expect(screen.getAllByRole("listitem")).toHaveLength(43);
|
||||
});
|
||||
|
||||
it("narrows to the Weighted die on a three-letter query", () => {
|
||||
render(<DiceList query="wei" counts={{}} onChange={vi.fn()} />);
|
||||
const rows = screen.getAllByRole("listitem");
|
||||
// The name is split into highlighted and plain runs, so match on the row
|
||||
// button's accessible name rather than on a single text node.
|
||||
expect(within(rows[0]).getByRole("button", { name: "Weighted die" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("highlights the characters the query matched", () => {
|
||||
render(<DiceList query="wei" counts={{}} onChange={vi.fn()} />);
|
||||
const rows = screen.getAllByRole("listitem");
|
||||
expect(within(rows[0]).getByText("Wei").tagName).toBe("MARK");
|
||||
});
|
||||
|
||||
it("finds a die by a fragment from the middle of its name", () => {
|
||||
render(<DiceList query="grozav" counts={{}} onChange={vi.fn()} />);
|
||||
expect(screen.getAllByRole("listitem")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("says so when nothing matches", () => {
|
||||
render(<DiceList query="qqqqq" counts={{}} onChange={vi.fn()} />);
|
||||
expect(screen.getByText(/No die matches/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("passes the owned count through to the row", () => {
|
||||
render(<DiceList query="wei" counts={{ weighted: 4 }} onChange={vi.fn()} />);
|
||||
expect(screen.getByLabelText("How many Weighted die")).toHaveTextContent("4");
|
||||
});
|
||||
|
||||
it("reports which die changed", async () => {
|
||||
const onChange = vi.fn();
|
||||
render(<DiceList query="wei" counts={{}} onChange={onChange} />);
|
||||
await userEvent.click(screen.getByRole("button", { name: "Weighted die" }));
|
||||
expect(onChange.mock.calls[0][0]).toBe("weighted");
|
||||
expect((onChange.mock.calls[0][1] as (p: number) => number)(0)).toBe(1);
|
||||
});
|
||||
});
|
||||
@ -3,20 +3,11 @@
|
||||
* scrolling the wheel over its counter, and fuzzy-searching by name.
|
||||
*/
|
||||
|
||||
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { fireEvent, render, screen, } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { MAX_PER_DIE } from "../data/dice.ts";
|
||||
import type { Die } from "../data/dice.ts";
|
||||
import type { SolveResponse } from "../core/solve.ts";
|
||||
import type { SavedInventory } from "../lib/inventoryIo.ts";
|
||||
import { BadgePicker } from "./BadgePicker.tsx";
|
||||
import { DiceList } from "./DiceList.tsx";
|
||||
import { DieRow, highlightName } from "./DieRow.tsx";
|
||||
import { InventoryIo } from "./InventoryIo.tsx";
|
||||
import type { InventoryIoProps } from "./InventoryIo.tsx";
|
||||
import { highlightName } from "./DieRow.tsx";
|
||||
import { QuantityStepper, clampCount } from "./QuantityStepper.tsx";
|
||||
import { ResultPanel, summariseDice } from "./ResultPanel.tsx";
|
||||
|
||||
/**
|
||||
* Apply the updater a component emitted, to assert on the resulting count.
|
||||
@ -35,14 +26,6 @@ function applied(
|
||||
return update(previous);
|
||||
}
|
||||
|
||||
const ordinary: Die = {
|
||||
id: "ordinary",
|
||||
name: "Ordinary die",
|
||||
description: "An ordinary playing die.",
|
||||
weights: [1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6],
|
||||
wildcardFaces: [],
|
||||
wildScoresAlone: false,
|
||||
};
|
||||
|
||||
describe("clampCount", () => {
|
||||
it("keeps a value inside the range", () => {
|
||||
@ -136,397 +119,3 @@ describe("highlightName", () => {
|
||||
expect(container.textContent).toBe("Die");
|
||||
});
|
||||
});
|
||||
|
||||
describe("DieRow", () => {
|
||||
it("adds one die when the row is clicked", async () => {
|
||||
const onChange = vi.fn();
|
||||
render(<DieRow die={ordinary} count={0} highlight={[]} onChange={onChange} />);
|
||||
await userEvent.click(screen.getByRole("button", { name: "Ordinary die" }));
|
||||
expect(applied(onChange, 0)).toBe(1);
|
||||
});
|
||||
|
||||
it("stops at the maximum when clicked repeatedly", async () => {
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<DieRow die={ordinary} count={MAX_PER_DIE} highlight={[]} onChange={onChange} />,
|
||||
);
|
||||
await userEvent.click(screen.getByRole("button", { name: "Ordinary die" }));
|
||||
expect(applied(onChange, MAX_PER_DIE)).toBe(MAX_PER_DIE);
|
||||
});
|
||||
|
||||
it("marks a row you own", () => {
|
||||
const { container } = render(
|
||||
<DieRow die={ordinary} count={2} highlight={[]} onChange={vi.fn()} />,
|
||||
);
|
||||
expect(container.querySelector(".die-row")).toHaveClass("owned");
|
||||
});
|
||||
|
||||
it("tags the wildcard dice", () => {
|
||||
const balatro: Die = {
|
||||
...ordinary,
|
||||
id: "balatro",
|
||||
wildcardFaces: [1],
|
||||
wildScoresAlone: true,
|
||||
};
|
||||
render(<DieRow die={balatro} count={0} highlight={[]} onChange={vi.fn()} />);
|
||||
expect(screen.getByText("wild")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("DiceList", () => {
|
||||
it("shows every die when the query is empty", () => {
|
||||
render(<DiceList query="" counts={{}} onChange={vi.fn()} />);
|
||||
expect(screen.getAllByRole("listitem")).toHaveLength(43);
|
||||
});
|
||||
|
||||
it("narrows to the Weighted die on a three-letter query", () => {
|
||||
render(<DiceList query="wei" counts={{}} onChange={vi.fn()} />);
|
||||
const rows = screen.getAllByRole("listitem");
|
||||
// The name is split into highlighted and plain runs, so match on the row
|
||||
// button's accessible name rather than on a single text node.
|
||||
expect(within(rows[0]).getByRole("button", { name: "Weighted die" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("highlights the characters the query matched", () => {
|
||||
render(<DiceList query="wei" counts={{}} onChange={vi.fn()} />);
|
||||
const rows = screen.getAllByRole("listitem");
|
||||
expect(within(rows[0]).getByText("Wei").tagName).toBe("MARK");
|
||||
});
|
||||
|
||||
it("finds a die by a fragment from the middle of its name", () => {
|
||||
render(<DiceList query="grozav" counts={{}} onChange={vi.fn()} />);
|
||||
expect(screen.getAllByRole("listitem")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("says so when nothing matches", () => {
|
||||
render(<DiceList query="qqqqq" counts={{}} onChange={vi.fn()} />);
|
||||
expect(screen.getByText(/No die matches/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("passes the owned count through to the row", () => {
|
||||
render(<DiceList query="wei" counts={{ weighted: 4 }} onChange={vi.fn()} />);
|
||||
expect(screen.getByLabelText("How many Weighted die")).toHaveTextContent("4");
|
||||
});
|
||||
|
||||
it("reports which die changed", async () => {
|
||||
const onChange = vi.fn();
|
||||
render(<DiceList query="wei" counts={{}} onChange={onChange} />);
|
||||
await userEvent.click(screen.getByRole("button", { name: "Weighted die" }));
|
||||
expect(onChange.mock.calls[0][0]).toBe("weighted");
|
||||
expect((onChange.mock.calls[0][1] as (p: number) => number)(0)).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("BadgePicker", () => {
|
||||
it("groups badges under their tier", () => {
|
||||
render(<BadgePicker query="" owned={new Set()} onToggle={vi.fn()} />);
|
||||
expect(screen.getByRole("heading", { name: "tin" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { name: "silver" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { name: "gold" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("hides a tier with no matching badge", () => {
|
||||
render(<BadgePicker query="emperor" owned={new Set()} onToggle={vi.fn()} />);
|
||||
expect(screen.queryByRole("heading", { name: "tin" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { name: "gold" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("reflects which badges are owned", () => {
|
||||
render(<BadgePicker query="emperor" owned={new Set(["gold_emperors"])} onToggle={vi.fn()} />);
|
||||
expect(screen.getByRole("checkbox")).toBeChecked();
|
||||
});
|
||||
|
||||
it("reports a toggle in both directions", async () => {
|
||||
const onToggle = vi.fn();
|
||||
const { rerender } = render(
|
||||
<BadgePicker query="emperor" owned={new Set()} onToggle={onToggle} />,
|
||||
);
|
||||
await userEvent.click(screen.getByRole("checkbox"));
|
||||
expect(onToggle).toHaveBeenLastCalledWith("gold_emperors", true);
|
||||
|
||||
rerender(
|
||||
<BadgePicker query="emperor" owned={new Set(["gold_emperors"])} onToggle={onToggle} />,
|
||||
);
|
||||
await userEvent.click(screen.getByRole("checkbox"));
|
||||
expect(onToggle).toHaveBeenLastCalledWith("gold_emperors", false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("summariseDice", () => {
|
||||
it("collapses duplicates and orders by count", () => {
|
||||
const weighted: Die = { ...ordinary, id: "weighted", name: "Weighted die" };
|
||||
expect(summariseDice([ordinary, weighted, weighted, weighted])).toEqual([
|
||||
{ die: weighted, count: 3 },
|
||||
{ die: ordinary, count: 1 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
const response: SolveResponse = {
|
||||
dice: new Array<Die>(6).fill(ordinary),
|
||||
evaluation: { ev: 399.1, bustProbability: 0.0309, p90: 900 },
|
||||
simulation: {
|
||||
meanPerTurn: 412.5,
|
||||
standardError: 3.2,
|
||||
bustRate: 0.2,
|
||||
throwsPerTurn: 1.4,
|
||||
turns: 20000,
|
||||
},
|
||||
optimal: true,
|
||||
alternatives: [],
|
||||
badges: [],
|
||||
inventorySize: 6,
|
||||
};
|
||||
|
||||
describe("ResultPanel", () => {
|
||||
it("prompts for dice before the first solve", () => {
|
||||
render(<ResultPanel result={null} error={null} solving={false} />);
|
||||
expect(screen.getByText(/Add at least six dice/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("says it is working while a solve is in flight", () => {
|
||||
render(<ResultPanel result={null} error={null} solving />);
|
||||
expect(screen.getByText("Solving…")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows an error instead of a stale answer", () => {
|
||||
render(<ResultPanel result={null} error="Need at least 6 dice" solving={false} />);
|
||||
expect(screen.getByText("Need at least 6 dice")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the loadout and its numbers", () => {
|
||||
render(<ResultPanel result={response} error={null} solving={false} />);
|
||||
expect(screen.getByText("6×")).toBeInTheDocument();
|
||||
expect(screen.getByText("Ordinary die")).toBeInTheDocument();
|
||||
expect(screen.getByText("399")).toBeInTheDocument();
|
||||
expect(screen.getByText("3.09%")).toBeInTheDocument();
|
||||
expect(screen.getByText("900")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("says when the answer is proven rather than merely good", () => {
|
||||
render(<ResultPanel result={response} error={null} solving={false} />);
|
||||
expect(screen.getByText(/Provably optimal/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("admits when the answer is only a local search result", () => {
|
||||
render(
|
||||
<ResultPanel result={{ ...response, optimal: false }} error={null} solving={false} />,
|
||||
);
|
||||
expect(screen.getByText(/not proven/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("lists runners-up when there are any", () => {
|
||||
const withAlternatives: SolveResponse = {
|
||||
...response,
|
||||
alternatives: [
|
||||
{ dice: new Array<Die>(6).fill(ordinary), evaluation: response.evaluation },
|
||||
],
|
||||
};
|
||||
render(<ResultPanel result={withAlternatives} error={null} solving={false} />);
|
||||
expect(screen.getByText("Runners-up")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("asks for badges when none are owned", () => {
|
||||
render(<ResultPanel result={response} error={null} solving={false} />);
|
||||
expect(screen.getByText(/Tick the badges you own/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the pick, its value and its reasoning for each tier", () => {
|
||||
const withBadges: SolveResponse = {
|
||||
...response,
|
||||
badges: [
|
||||
{
|
||||
tier: "gold",
|
||||
ranked: [
|
||||
{
|
||||
badge: {
|
||||
id: "gold_emperors",
|
||||
name: "Gold Emperor's badge",
|
||||
description: "",
|
||||
tier: "gold",
|
||||
effect: { kind: "scoring", rules: { emperorTriple: true } },
|
||||
},
|
||||
pointsPerGame: 1234,
|
||||
reason: "Changes the scoring table.",
|
||||
dice: new Array<Die>(6).fill(ordinary),
|
||||
},
|
||||
{
|
||||
badge: {
|
||||
id: "gold_warlord",
|
||||
name: "Gold Warlord badge",
|
||||
description: "",
|
||||
tier: "gold",
|
||||
effect: { kind: "multiplier", factor: 2, uses: 1 },
|
||||
},
|
||||
pointsPerGame: 567,
|
||||
reason: "Doubles a good turn.",
|
||||
dice: null,
|
||||
},
|
||||
{
|
||||
badge: {
|
||||
id: "gold_defence",
|
||||
name: "Gold Defence badge",
|
||||
description: "",
|
||||
tier: "gold",
|
||||
effect: { kind: "defence" },
|
||||
},
|
||||
pointsPerGame: null,
|
||||
reason: "Situational.",
|
||||
dice: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
render(<ResultPanel result={withBadges} error={null} solving={false} />);
|
||||
expect(screen.getByText("Gold Emperor's badge")).toBeInTheDocument();
|
||||
expect(screen.getByText(/~1,234 pts\/game/)).toBeInTheDocument();
|
||||
expect(screen.getByText("Changes the scoring table.")).toBeInTheDocument();
|
||||
expect(screen.getByText(/With this badge, bring/)).toBeInTheDocument();
|
||||
// The runners-up list renders both a valued badge and a situational one.
|
||||
expect(screen.getByText(/Gold Warlord badge — ~567 pts\/game/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Gold Defence badge — situational/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("dims the panel while a fresh solve is running", () => {
|
||||
const { container } = render(
|
||||
<ResultPanel result={response} error={null} solving />,
|
||||
);
|
||||
expect(container.querySelector(".result")).toHaveClass("stale");
|
||||
});
|
||||
});
|
||||
|
||||
describe("InventoryIo", () => {
|
||||
const inventory: SavedInventory = {
|
||||
diceCounts: { weighted: 2 },
|
||||
badgeIds: ["tin_might"],
|
||||
};
|
||||
|
||||
/**
|
||||
* Render the panel with every port stubbed, and open it.
|
||||
*
|
||||
* @param overrides - Ports or handlers to replace.
|
||||
* @returns The stubs the caller will want to assert on.
|
||||
*/
|
||||
function setup(overrides: Partial<InventoryIoProps> = {}) {
|
||||
const onImport = vi.fn();
|
||||
const saveFile = vi.fn();
|
||||
const clipboard = { writeText: vi.fn<(text: string) => Promise<void>>().mockResolvedValue() };
|
||||
render(
|
||||
<InventoryIo
|
||||
inventory={inventory}
|
||||
onImport={onImport}
|
||||
clipboard={clipboard}
|
||||
saveFile={saveFile}
|
||||
shareUrl="https://dice.example/#i=abc"
|
||||
{...overrides}
|
||||
/>,
|
||||
);
|
||||
return { onImport, saveFile, clipboard };
|
||||
}
|
||||
|
||||
it("starts collapsed so it costs no vertical space", () => {
|
||||
setup();
|
||||
expect(screen.getByText("Import / export").closest("details")).not.toHaveAttribute("open");
|
||||
});
|
||||
|
||||
it("downloads the inventory as parseable JSON", async () => {
|
||||
const { saveFile } = setup();
|
||||
await userEvent.click(screen.getByRole("button", { name: "Download .json" }));
|
||||
expect(saveFile).toHaveBeenCalledTimes(1);
|
||||
const [filename, body] = saveFile.mock.calls[0] as [string, string];
|
||||
expect(filename).toBe("kcd2-dice.json");
|
||||
expect(JSON.parse(body)).toEqual(inventory);
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Saved kcd2-dice.json.");
|
||||
});
|
||||
|
||||
it("copies the JSON to the clipboard", async () => {
|
||||
const { clipboard } = setup();
|
||||
await userEvent.click(screen.getByRole("button", { name: "Copy JSON" }));
|
||||
expect(JSON.parse(clipboard.writeText.mock.calls[0][0])).toEqual(inventory);
|
||||
await screen.findByText("JSON copied.");
|
||||
});
|
||||
|
||||
it("copies the share link", async () => {
|
||||
const { clipboard } = setup();
|
||||
await userEvent.click(screen.getByRole("button", { name: "Copy link" }));
|
||||
expect(clipboard.writeText).toHaveBeenCalledWith("https://dice.example/#i=abc");
|
||||
await screen.findByText("Link copied.");
|
||||
});
|
||||
|
||||
it("falls back to the textarea when the clipboard refuses", async () => {
|
||||
// Insecure origins reject; the payload must still be reachable by hand.
|
||||
const clipboard = {
|
||||
writeText: vi.fn<(text: string) => Promise<void>>().mockRejectedValue(new Error("denied")),
|
||||
};
|
||||
setup({ clipboard });
|
||||
await userEvent.click(screen.getByRole("button", { name: "Copy JSON" }));
|
||||
await screen.findByText(/Copy failed/);
|
||||
const box = screen.getByLabelText<HTMLTextAreaElement>("Inventory JSON");
|
||||
expect(JSON.parse(box.value)).toEqual(inventory);
|
||||
});
|
||||
|
||||
it("imports a pasted inventory", async () => {
|
||||
const { onImport } = setup();
|
||||
// fireEvent rather than userEvent.type: the latter treats "{" and "[" as
|
||||
// key-descriptor syntax, which mangles JSON.
|
||||
fireEvent.change(screen.getByLabelText("Inventory JSON"), {
|
||||
target: { value: JSON.stringify({ diceCounts: { lucky: 3 }, badgeIds: [] }) },
|
||||
});
|
||||
await userEvent.click(screen.getByRole("button", { name: "Import pasted" }));
|
||||
expect(onImport).toHaveBeenCalledWith({ diceCounts: { lucky: 3 }, badgeIds: [] });
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Imported.");
|
||||
});
|
||||
|
||||
it("refuses an unusable payload without calling onImport", async () => {
|
||||
const { onImport } = setup();
|
||||
fireEvent.change(screen.getByLabelText("Inventory JSON"), { target: { value: "{not json" } });
|
||||
await userEvent.click(screen.getByRole("button", { name: "Import pasted" }));
|
||||
expect(onImport).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Nothing imported. Not valid JSON.");
|
||||
});
|
||||
|
||||
it("imports what it can and says what it ignored", async () => {
|
||||
const { onImport } = setup();
|
||||
fireEvent.change(screen.getByLabelText("Inventory JSON"), {
|
||||
target: { value: '{"diceCounts":{"lucky":1,"nope":2},"badgeIds":[]}' },
|
||||
});
|
||||
await userEvent.click(screen.getByRole("button", { name: "Import pasted" }));
|
||||
expect(onImport).toHaveBeenCalledWith({ diceCounts: { lucky: 1 }, badgeIds: [] });
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Ignored: Unknown die “nope”.");
|
||||
});
|
||||
|
||||
it("keeps the import button disabled until something is pasted", () => {
|
||||
setup();
|
||||
expect(screen.getByRole("button", { name: "Import pasted" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("imports an uploaded file", async () => {
|
||||
const { onImport } = setup();
|
||||
const file = new File([JSON.stringify({ diceCounts: { lucky: 5 }, badgeIds: [] })], "inv.json", {
|
||||
type: "application/json",
|
||||
});
|
||||
await userEvent.upload(screen.getByLabelText(/Load a .json file/), file);
|
||||
await waitFor(() => {
|
||||
expect(onImport).toHaveBeenCalledWith({ diceCounts: { lucky: 5 }, badgeIds: [] });
|
||||
});
|
||||
});
|
||||
|
||||
it("does nothing when the file picker is dismissed", () => {
|
||||
const { onImport } = setup();
|
||||
const input = screen.getByLabelText(/Load a .json file/);
|
||||
fireEvent.change(input, { target: { files: [] } });
|
||||
expect(onImport).not.toHaveBeenCalled();
|
||||
fireEvent.change(input, { target: { files: null } });
|
||||
expect(onImport).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports a file it cannot read", async () => {
|
||||
const { onImport } = setup();
|
||||
const unreadable = new File(["x"], "bad.json", { type: "application/json" });
|
||||
vi.spyOn(unreadable, "text").mockRejectedValue(new Error("I/O"));
|
||||
await userEvent.upload(screen.getByLabelText(/Load a .json file/), unreadable);
|
||||
await screen.findByText("Could not read that file.");
|
||||
expect(onImport).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@ -7,30 +7,16 @@
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BASE_RULES } from "../data/badges.ts";
|
||||
import { DICE_BY_ID } from "../data/dice.ts";
|
||||
import type { Die } from "../data/dice.ts";
|
||||
import { mulberry32 } from "../lib/rng.ts";
|
||||
import { Scorer } from "./scoring.ts";
|
||||
import {
|
||||
DEFAULT_POLICY,
|
||||
NO_CHARGES,
|
||||
applySetDie,
|
||||
chooseHold,
|
||||
simulateTurn,
|
||||
simulateTurns,
|
||||
subMultisets,
|
||||
} from "./simulate.ts";
|
||||
|
||||
const die = (id: string): Die => {
|
||||
const found = DICE_BY_ID.get(id);
|
||||
if (!found) {
|
||||
throw new Error(`no such die: ${id}`);
|
||||
}
|
||||
return found;
|
||||
};
|
||||
|
||||
const scorer = new Scorer(BASE_RULES);
|
||||
const sixOrdinary = new Array<Die>(6).fill(die("ordinary"));
|
||||
|
||||
/**
|
||||
* A die that always rolls the given face, for pinning deterministic behaviour.
|
||||
@ -38,18 +24,7 @@ const sixOrdinary = new Array<Die>(6).fill(die("ordinary"));
|
||||
* @param face - The face it always shows, 1-6.
|
||||
* @returns Six copies of that die.
|
||||
*/
|
||||
const alwaysRolls = (face: number): Die[] =>
|
||||
new Array<Die>(6).fill({
|
||||
id: `always-${face}`,
|
||||
name: `always ${face}`,
|
||||
description: "",
|
||||
weights: [1, 2, 3, 4, 5, 6].map((f) => (f === face ? 1 : 0)) as unknown as Die["weights"],
|
||||
wildcardFaces: [],
|
||||
wildScoresAlone: false,
|
||||
});
|
||||
|
||||
const alwaysTwo = alwaysRolls(2);
|
||||
const alwaysThree = alwaysRolls(3);
|
||||
|
||||
describe("subMultisets", () => {
|
||||
it("enumerates every sub-multiset including the empty one", () => {
|
||||
@ -123,150 +98,3 @@ describe("applySetDie", () => {
|
||||
expect(applySetDie(counts, 3, scorer)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("simulateTurn", () => {
|
||||
it("banks once the threshold is reached", () => {
|
||||
const random = mulberry32(1);
|
||||
const banked = simulateTurn(sixOrdinary, scorer, DEFAULT_POLICY, NO_CHARGES, random);
|
||||
expect(banked).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it("is reproducible for a given seed", () => {
|
||||
const first = simulateTurn(sixOrdinary, scorer, DEFAULT_POLICY, NO_CHARGES, mulberry32(7));
|
||||
const second = simulateTurn(sixOrdinary, scorer, DEFAULT_POLICY, NO_CHARGES, mulberry32(7));
|
||||
expect(first).toBe(second);
|
||||
});
|
||||
|
||||
it("counts the throws it made", () => {
|
||||
const counter = { throws: 0 };
|
||||
simulateTurn(sixOrdinary, scorer, DEFAULT_POLICY, NO_CHARGES, mulberry32(3), counter);
|
||||
expect(counter.throws).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("brings the whole set back when every die scores", () => {
|
||||
// Six weighted dice are ones about two thirds of the time, and with no
|
||||
// per-die bonus the policy holds every scoring die — so all six get set
|
||||
// aside and the hot-dice branch has to refill the hand. A threshold above
|
||||
// one throw's typical score keeps the turn going long enough to see it.
|
||||
const weighted = new Array<Die>(6).fill(die("weighted"));
|
||||
const counter = { throws: 0 };
|
||||
simulateTurn(
|
||||
weighted,
|
||||
scorer,
|
||||
{ bankThreshold: 20_000, dieValueBonus: 0 },
|
||||
NO_CHARGES,
|
||||
mulberry32(5),
|
||||
counter,
|
||||
);
|
||||
expect(counter.throws).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it("always terminates, even for dice that can never bust", () => {
|
||||
// Six dice that always roll a 2 always score (six of a kind, 1600). Before
|
||||
// banking was checked ahead of the hot-dice re-roll, this looped forever.
|
||||
const banked = simulateTurn(
|
||||
alwaysTwo,
|
||||
scorer,
|
||||
DEFAULT_POLICY,
|
||||
NO_CHARGES,
|
||||
mulberry32(1),
|
||||
);
|
||||
expect(banked).toBe(1600);
|
||||
});
|
||||
});
|
||||
|
||||
describe("badge charges in a turn", () => {
|
||||
const misfortune = new Array<Die>(6).fill(die("misfortune"));
|
||||
|
||||
it("an anti-bust charge can only raise the mean", () => {
|
||||
const base = simulateTurns(misfortune, scorer, 2000, DEFAULT_POLICY, NO_CHARGES, 11);
|
||||
const rescued = simulateTurns(
|
||||
misfortune,
|
||||
scorer,
|
||||
2000,
|
||||
DEFAULT_POLICY,
|
||||
{ ...NO_CHARGES, antibust: 1 },
|
||||
11,
|
||||
);
|
||||
expect(rescued.meanPerTurn).toBeGreaterThanOrEqual(base.meanPerTurn);
|
||||
expect(rescued.bustRate).toBeLessThanOrEqual(base.bustRate);
|
||||
});
|
||||
|
||||
it("a re-roll charge can only raise the mean", () => {
|
||||
const base = simulateTurns(misfortune, scorer, 2000, DEFAULT_POLICY, NO_CHARGES, 13);
|
||||
const rerolled = simulateTurns(
|
||||
misfortune,
|
||||
scorer,
|
||||
2000,
|
||||
DEFAULT_POLICY,
|
||||
{ ...NO_CHARGES, reroll: 1, rerollDice: 3 },
|
||||
13,
|
||||
);
|
||||
expect(rerolled.meanPerTurn).toBeGreaterThanOrEqual(base.meanPerTurn);
|
||||
});
|
||||
|
||||
it("an extra die can only raise the mean", () => {
|
||||
const base = simulateTurns(sixOrdinary, scorer, 2000, DEFAULT_POLICY, NO_CHARGES, 17);
|
||||
const bigger = simulateTurns(
|
||||
sixOrdinary,
|
||||
scorer,
|
||||
2000,
|
||||
DEFAULT_POLICY,
|
||||
{ ...NO_CHARGES, extraDice: 1 },
|
||||
17,
|
||||
);
|
||||
expect(bigger.meanPerTurn).toBeGreaterThanOrEqual(base.meanPerTurn);
|
||||
});
|
||||
|
||||
it("a transmutation charge can only raise the mean", () => {
|
||||
const base = simulateTurns(sixOrdinary, scorer, 2000, DEFAULT_POLICY, NO_CHARGES, 19);
|
||||
const transmuted = simulateTurns(
|
||||
sixOrdinary,
|
||||
scorer,
|
||||
2000,
|
||||
DEFAULT_POLICY,
|
||||
{ ...NO_CHARGES, setDie: 1, setDieValue: 1 },
|
||||
19,
|
||||
);
|
||||
expect(transmuted.meanPerTurn).toBeGreaterThanOrEqual(base.meanPerTurn);
|
||||
});
|
||||
});
|
||||
|
||||
describe("simulateTurns", () => {
|
||||
it("reports a mean, an error bar, a bust rate and a throw count", () => {
|
||||
const result = simulateTurns(sixOrdinary, scorer, 1000);
|
||||
expect(result.turns).toBe(1000);
|
||||
expect(result.meanPerTurn).toBeGreaterThan(0);
|
||||
expect(result.standardError).toBeGreaterThan(0);
|
||||
expect(result.bustRate).toBeGreaterThan(0);
|
||||
expect(result.bustRate).toBeLessThan(1);
|
||||
expect(result.throwsPerTurn).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("is reproducible for a given seed", () => {
|
||||
const a = simulateTurns(sixOrdinary, scorer, 500, DEFAULT_POLICY, NO_CHARGES, 42);
|
||||
const b = simulateTurns(sixOrdinary, scorer, 500, DEFAULT_POLICY, NO_CHARGES, 42);
|
||||
expect(a.meanPerTurn).toBe(b.meanPerTurn);
|
||||
});
|
||||
|
||||
it("reports zero variance when every turn is identical", () => {
|
||||
const result = simulateTurns(alwaysTwo, scorer, 50);
|
||||
expect(result.meanPerTurn).toBe(1600);
|
||||
expect(result.standardError).toBe(0);
|
||||
expect(result.bustRate).toBe(0);
|
||||
});
|
||||
|
||||
it("reports a total bust for dice that can never score", () => {
|
||||
// Two each of 2, 3 and 4 every single throw: no 1, no 5, no three of a
|
||||
// kind and no straight, so every turn busts.
|
||||
const noScore = [
|
||||
...alwaysTwo.slice(0, 2),
|
||||
...alwaysThree.slice(0, 2),
|
||||
...alwaysRolls(4).slice(0, 2),
|
||||
];
|
||||
const result = simulateTurns(noScore, scorer, 20);
|
||||
expect(result.meanPerTurn).toBe(0);
|
||||
expect(result.standardError).toBe(0);
|
||||
expect(result.bustRate).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
198
kcd2_dice_solver/src/core/simulateTurns.test.ts
Normal file
198
kcd2_dice_solver/src/core/simulateTurns.test.ts
Normal file
@ -0,0 +1,198 @@
|
||||
/** Whole-turn and multi-turn simulation tests. */
|
||||
|
||||
/**
|
||||
* Tests for the turn simulator.
|
||||
*
|
||||
* The simulator encodes a *policy*, not a fact, so these tests pin the policy's
|
||||
* stated rules rather than asserting that its output is "correct" play.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BASE_RULES } from "../data/badges.ts";
|
||||
import { DICE_BY_ID } from "../data/dice.ts";
|
||||
import type { Die } from "../data/dice.ts";
|
||||
import { mulberry32 } from "../lib/rng.ts";
|
||||
import { Scorer } from "./scoring.ts";
|
||||
import {
|
||||
DEFAULT_POLICY,
|
||||
NO_CHARGES,
|
||||
simulateTurn,
|
||||
simulateTurns,
|
||||
} from "./simulate.ts";
|
||||
|
||||
const die = (id: string): Die => {
|
||||
const found = DICE_BY_ID.get(id);
|
||||
if (!found) {
|
||||
throw new Error(`no such die: ${id}`);
|
||||
}
|
||||
return found;
|
||||
};
|
||||
|
||||
const scorer = new Scorer(BASE_RULES);
|
||||
const sixOrdinary = new Array<Die>(6).fill(die("ordinary"));
|
||||
|
||||
/**
|
||||
* A die that always rolls the given face, for pinning deterministic behaviour.
|
||||
*
|
||||
* @param face - The face it always shows, 1-6.
|
||||
* @returns Six copies of that die.
|
||||
*/
|
||||
const alwaysRolls = (face: number): Die[] =>
|
||||
new Array<Die>(6).fill({
|
||||
id: `always-${face}`,
|
||||
name: `always ${face}`,
|
||||
description: "",
|
||||
weights: [1, 2, 3, 4, 5, 6].map((f) => (f === face ? 1 : 0)) as unknown as Die["weights"],
|
||||
wildcardFaces: [],
|
||||
wildScoresAlone: false,
|
||||
});
|
||||
|
||||
const alwaysTwo = alwaysRolls(2);
|
||||
const alwaysThree = alwaysRolls(3);
|
||||
|
||||
describe("simulateTurn", () => {
|
||||
it("banks once the threshold is reached", () => {
|
||||
const random = mulberry32(1);
|
||||
const banked = simulateTurn(sixOrdinary, scorer, DEFAULT_POLICY, NO_CHARGES, random);
|
||||
expect(banked).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it("is reproducible for a given seed", () => {
|
||||
const first = simulateTurn(sixOrdinary, scorer, DEFAULT_POLICY, NO_CHARGES, mulberry32(7));
|
||||
const second = simulateTurn(sixOrdinary, scorer, DEFAULT_POLICY, NO_CHARGES, mulberry32(7));
|
||||
expect(first).toBe(second);
|
||||
});
|
||||
|
||||
it("counts the throws it made", () => {
|
||||
const counter = { throws: 0 };
|
||||
simulateTurn(sixOrdinary, scorer, DEFAULT_POLICY, NO_CHARGES, mulberry32(3), counter);
|
||||
expect(counter.throws).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("brings the whole set back when every die scores", () => {
|
||||
// Six weighted dice are ones about two thirds of the time, and with no
|
||||
// per-die bonus the policy holds every scoring die — so all six get set
|
||||
// aside and the hot-dice branch has to refill the hand. A threshold above
|
||||
// one throw's typical score keeps the turn going long enough to see it.
|
||||
const weighted = new Array<Die>(6).fill(die("weighted"));
|
||||
const counter = { throws: 0 };
|
||||
simulateTurn(
|
||||
weighted,
|
||||
scorer,
|
||||
{ bankThreshold: 20_000, dieValueBonus: 0 },
|
||||
NO_CHARGES,
|
||||
mulberry32(5),
|
||||
counter,
|
||||
);
|
||||
expect(counter.throws).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it("always terminates, even for dice that can never bust", () => {
|
||||
// Six dice that always roll a 2 always score (six of a kind, 1600). Before
|
||||
// banking was checked ahead of the hot-dice re-roll, this looped forever.
|
||||
const banked = simulateTurn(
|
||||
alwaysTwo,
|
||||
scorer,
|
||||
DEFAULT_POLICY,
|
||||
NO_CHARGES,
|
||||
mulberry32(1),
|
||||
);
|
||||
expect(banked).toBe(1600);
|
||||
});
|
||||
});
|
||||
|
||||
describe("badge charges in a turn", () => {
|
||||
const misfortune = new Array<Die>(6).fill(die("misfortune"));
|
||||
|
||||
it("an anti-bust charge can only raise the mean", () => {
|
||||
const base = simulateTurns(misfortune, scorer, 2000, DEFAULT_POLICY, NO_CHARGES, 11);
|
||||
const rescued = simulateTurns(
|
||||
misfortune,
|
||||
scorer,
|
||||
2000,
|
||||
DEFAULT_POLICY,
|
||||
{ ...NO_CHARGES, antibust: 1 },
|
||||
11,
|
||||
);
|
||||
expect(rescued.meanPerTurn).toBeGreaterThanOrEqual(base.meanPerTurn);
|
||||
expect(rescued.bustRate).toBeLessThanOrEqual(base.bustRate);
|
||||
});
|
||||
|
||||
it("a re-roll charge can only raise the mean", () => {
|
||||
const base = simulateTurns(misfortune, scorer, 2000, DEFAULT_POLICY, NO_CHARGES, 13);
|
||||
const rerolled = simulateTurns(
|
||||
misfortune,
|
||||
scorer,
|
||||
2000,
|
||||
DEFAULT_POLICY,
|
||||
{ ...NO_CHARGES, reroll: 1, rerollDice: 3 },
|
||||
13,
|
||||
);
|
||||
expect(rerolled.meanPerTurn).toBeGreaterThanOrEqual(base.meanPerTurn);
|
||||
});
|
||||
|
||||
it("an extra die can only raise the mean", () => {
|
||||
const base = simulateTurns(sixOrdinary, scorer, 2000, DEFAULT_POLICY, NO_CHARGES, 17);
|
||||
const bigger = simulateTurns(
|
||||
sixOrdinary,
|
||||
scorer,
|
||||
2000,
|
||||
DEFAULT_POLICY,
|
||||
{ ...NO_CHARGES, extraDice: 1 },
|
||||
17,
|
||||
);
|
||||
expect(bigger.meanPerTurn).toBeGreaterThanOrEqual(base.meanPerTurn);
|
||||
});
|
||||
|
||||
it("a transmutation charge can only raise the mean", () => {
|
||||
const base = simulateTurns(sixOrdinary, scorer, 2000, DEFAULT_POLICY, NO_CHARGES, 19);
|
||||
const transmuted = simulateTurns(
|
||||
sixOrdinary,
|
||||
scorer,
|
||||
2000,
|
||||
DEFAULT_POLICY,
|
||||
{ ...NO_CHARGES, setDie: 1, setDieValue: 1 },
|
||||
19,
|
||||
);
|
||||
expect(transmuted.meanPerTurn).toBeGreaterThanOrEqual(base.meanPerTurn);
|
||||
});
|
||||
});
|
||||
|
||||
describe("simulateTurns", () => {
|
||||
it("reports a mean, an error bar, a bust rate and a throw count", () => {
|
||||
const result = simulateTurns(sixOrdinary, scorer, 1000);
|
||||
expect(result.turns).toBe(1000);
|
||||
expect(result.meanPerTurn).toBeGreaterThan(0);
|
||||
expect(result.standardError).toBeGreaterThan(0);
|
||||
expect(result.bustRate).toBeGreaterThan(0);
|
||||
expect(result.bustRate).toBeLessThan(1);
|
||||
expect(result.throwsPerTurn).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("is reproducible for a given seed", () => {
|
||||
const a = simulateTurns(sixOrdinary, scorer, 500, DEFAULT_POLICY, NO_CHARGES, 42);
|
||||
const b = simulateTurns(sixOrdinary, scorer, 500, DEFAULT_POLICY, NO_CHARGES, 42);
|
||||
expect(a.meanPerTurn).toBe(b.meanPerTurn);
|
||||
});
|
||||
|
||||
it("reports zero variance when every turn is identical", () => {
|
||||
const result = simulateTurns(alwaysTwo, scorer, 50);
|
||||
expect(result.meanPerTurn).toBe(1600);
|
||||
expect(result.standardError).toBe(0);
|
||||
expect(result.bustRate).toBe(0);
|
||||
});
|
||||
|
||||
it("reports a total bust for dice that can never score", () => {
|
||||
// Two each of 2, 3 and 4 every single throw: no 1, no 5, no three of a
|
||||
// kind and no straight, so every turn busts.
|
||||
const noScore = [
|
||||
...alwaysTwo.slice(0, 2),
|
||||
...alwaysThree.slice(0, 2),
|
||||
...alwaysRolls(4).slice(0, 2),
|
||||
];
|
||||
const result = simulateTurns(noScore, scorer, 20);
|
||||
expect(result.meanPerTurn).toBe(0);
|
||||
expect(result.standardError).toBe(0);
|
||||
expect(result.bustRate).toBe(1);
|
||||
});
|
||||
});
|
||||
160
kcd2_dice_solver/src/lib/inventoryHash.test.ts
Normal file
160
kcd2_dice_solver/src/lib/inventoryHash.test.ts
Normal file
@ -0,0 +1,160 @@
|
||||
/** Serialisation, base64url and inventory-hash round trips. */
|
||||
|
||||
/**
|
||||
* Tests for inventory persistence and transport.
|
||||
*
|
||||
* The validator is the security boundary of the import features: everything a
|
||||
* user can paste, upload, or follow a link to lands here first. So the cases
|
||||
* below lean on malformed input rather than the happy path.
|
||||
*/
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
EMPTY,
|
||||
EXPORT_FILENAME,
|
||||
browserClipboard,
|
||||
browserSaveFile,
|
||||
browserUrlHash,
|
||||
decodeInventoryHash,
|
||||
encodeInventoryHash,
|
||||
fromBase64Url,
|
||||
parseInventoryJson,
|
||||
serialiseInventory,
|
||||
toBase64Url,
|
||||
} from "./inventoryIo.ts";
|
||||
import type { SavedInventory } from "./inventoryIo.ts";
|
||||
|
||||
/**
|
||||
* A storage stub holding one entry.
|
||||
*
|
||||
* @param initial - What the key already contains, if anything.
|
||||
* @returns A minimal Storage.
|
||||
*/
|
||||
|
||||
describe("serialiseInventory", () => {
|
||||
it("round-trips through the parser", () => {
|
||||
const inventory: SavedInventory = {
|
||||
diceCounts: { weighted: 4 },
|
||||
badgeIds: ["tin_might"],
|
||||
};
|
||||
expect(parseInventoryJson(serialiseInventory(inventory)).inventory).toEqual(inventory);
|
||||
});
|
||||
});
|
||||
|
||||
describe("base64url", () => {
|
||||
it("round-trips ASCII", () => {
|
||||
expect(fromBase64Url(toBase64Url("hello world"))).toBe("hello world");
|
||||
});
|
||||
|
||||
it("really produces URL-safe characters, not merely claims to", () => {
|
||||
// Standard base64 of these bytes contains both '+' and '/', so this
|
||||
// exercises the substitutions rather than trivially covering the line.
|
||||
const raw = "ÿï¿";
|
||||
const encoded = toBase64Url(raw);
|
||||
expect(encoded).not.toMatch(/[+/=]/);
|
||||
expect(encoded).toMatch(/[-_]/);
|
||||
expect(fromBase64Url(encoded)).toBe(raw);
|
||||
});
|
||||
|
||||
it("round-trips every padding length", () => {
|
||||
for (const text of ["abc", "abcd", "abcde"]) {
|
||||
expect(fromBase64Url(toBase64Url(text))).toBe(text);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("inventory hash", () => {
|
||||
const inventory: SavedInventory = {
|
||||
diceCounts: { weighted: 2 },
|
||||
badgeIds: ["tin_might"],
|
||||
};
|
||||
|
||||
it("round-trips an inventory", () => {
|
||||
const result = decodeInventoryHash(encodeInventoryHash(inventory));
|
||||
expect(result?.inventory).toEqual(inventory);
|
||||
expect(result?.dropped).toEqual([]);
|
||||
});
|
||||
|
||||
it("decodes with or without the leading hash", () => {
|
||||
const hash = encodeInventoryHash(inventory);
|
||||
expect(decodeInventoryHash(hash.slice(1))?.inventory).toEqual(inventory);
|
||||
});
|
||||
|
||||
it("returns null when there is no fragment", () => {
|
||||
expect(decodeInventoryHash("")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the fragment carries something else", () => {
|
||||
expect(decodeInventoryHash("#other=1")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for an empty inventory parameter", () => {
|
||||
expect(decodeInventoryHash("#i=")).toBeNull();
|
||||
});
|
||||
|
||||
it("reports a damaged link rather than throwing", () => {
|
||||
// Lone '!' is not valid base64, so atob throws — and it must be caught in
|
||||
// the same place a JSON failure would be.
|
||||
expect(decodeInventoryHash("#i=!!!")).toEqual({
|
||||
inventory: EMPTY,
|
||||
dropped: ["This link is damaged."],
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a link that decodes but is not an inventory", () => {
|
||||
const result = decodeInventoryHash(`#i=${toBase64Url("42")}`);
|
||||
expect(result?.dropped).toEqual(["Not an inventory."]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("browser ports", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
window.location.hash = "";
|
||||
});
|
||||
|
||||
it("browserClipboard writes through navigator.clipboard", async () => {
|
||||
const writeText = vi.fn<(text: string) => Promise<void>>().mockResolvedValue();
|
||||
Object.defineProperty(navigator, "clipboard", { value: { writeText }, configurable: true });
|
||||
await browserClipboard.writeText("payload");
|
||||
expect(writeText).toHaveBeenCalledWith("payload");
|
||||
});
|
||||
|
||||
it("browserSaveFile builds, clicks, and revokes an object URL", () => {
|
||||
// jsdom has no createObjectURL, but the properties are assignable — so the
|
||||
// real implementation can be exercised rather than mocked away wholesale.
|
||||
const createObjectURL = vi.fn(() => "blob:kcd2");
|
||||
const revokeObjectURL = vi.fn();
|
||||
Object.defineProperty(URL, "createObjectURL", { value: createObjectURL, configurable: true });
|
||||
Object.defineProperty(URL, "revokeObjectURL", { value: revokeObjectURL, configurable: true });
|
||||
const click = vi
|
||||
.spyOn(HTMLAnchorElement.prototype, "click")
|
||||
.mockImplementation(function mockClick(this: HTMLAnchorElement) {
|
||||
expect(this.download).toBe(EXPORT_FILENAME);
|
||||
expect(this.getAttribute("href")).toBe("blob:kcd2");
|
||||
});
|
||||
|
||||
browserSaveFile(EXPORT_FILENAME, "{}");
|
||||
|
||||
expect(createObjectURL).toHaveBeenCalledTimes(1);
|
||||
expect(click).toHaveBeenCalledTimes(1);
|
||||
expect(revokeObjectURL).toHaveBeenCalledWith("blob:kcd2");
|
||||
});
|
||||
|
||||
it("browserUrlHash reads the fragment", () => {
|
||||
window.location.hash = "#i=abc";
|
||||
expect(browserUrlHash.read()).toBe("#i=abc");
|
||||
});
|
||||
|
||||
it("browserUrlHash clears the fragment without reloading", () => {
|
||||
window.location.hash = "#i=abc";
|
||||
browserUrlHash.clear();
|
||||
expect(window.location.hash).toBe("");
|
||||
});
|
||||
|
||||
it("browserUrlHash builds a base URL with no fragment", () => {
|
||||
window.location.hash = "#i=abc";
|
||||
expect(browserUrlHash.base()).toBe(window.location.origin + window.location.pathname);
|
||||
expect(browserUrlHash.base()).not.toContain("#");
|
||||
});
|
||||
});
|
||||
@ -6,24 +6,14 @@
|
||||
* below lean on malformed input rather than the happy path.
|
||||
*/
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, } from "vitest";
|
||||
import {
|
||||
EMPTY,
|
||||
EXPORT_FILENAME,
|
||||
STORAGE_KEY,
|
||||
browserClipboard,
|
||||
browserSaveFile,
|
||||
browserUrlHash,
|
||||
decodeInventoryHash,
|
||||
encodeInventoryHash,
|
||||
fromBase64Url,
|
||||
loadInventory,
|
||||
parseInventory,
|
||||
parseInventoryJson,
|
||||
serialiseInventory,
|
||||
toBase64Url,
|
||||
} from "./inventoryIo.ts";
|
||||
import type { SavedInventory } from "./inventoryIo.ts";
|
||||
|
||||
/**
|
||||
* A storage stub holding one entry.
|
||||
@ -172,131 +162,3 @@ describe("loadInventory", () => {
|
||||
).toEqual(EMPTY);
|
||||
});
|
||||
});
|
||||
|
||||
describe("serialiseInventory", () => {
|
||||
it("round-trips through the parser", () => {
|
||||
const inventory: SavedInventory = {
|
||||
diceCounts: { weighted: 4 },
|
||||
badgeIds: ["tin_might"],
|
||||
};
|
||||
expect(parseInventoryJson(serialiseInventory(inventory)).inventory).toEqual(inventory);
|
||||
});
|
||||
});
|
||||
|
||||
describe("base64url", () => {
|
||||
it("round-trips ASCII", () => {
|
||||
expect(fromBase64Url(toBase64Url("hello world"))).toBe("hello world");
|
||||
});
|
||||
|
||||
it("really produces URL-safe characters, not merely claims to", () => {
|
||||
// Standard base64 of these bytes contains both '+' and '/', so this
|
||||
// exercises the substitutions rather than trivially covering the line.
|
||||
const raw = "ÿï¿";
|
||||
const encoded = toBase64Url(raw);
|
||||
expect(encoded).not.toMatch(/[+/=]/);
|
||||
expect(encoded).toMatch(/[-_]/);
|
||||
expect(fromBase64Url(encoded)).toBe(raw);
|
||||
});
|
||||
|
||||
it("round-trips every padding length", () => {
|
||||
for (const text of ["abc", "abcd", "abcde"]) {
|
||||
expect(fromBase64Url(toBase64Url(text))).toBe(text);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("inventory hash", () => {
|
||||
const inventory: SavedInventory = {
|
||||
diceCounts: { weighted: 2 },
|
||||
badgeIds: ["tin_might"],
|
||||
};
|
||||
|
||||
it("round-trips an inventory", () => {
|
||||
const result = decodeInventoryHash(encodeInventoryHash(inventory));
|
||||
expect(result?.inventory).toEqual(inventory);
|
||||
expect(result?.dropped).toEqual([]);
|
||||
});
|
||||
|
||||
it("decodes with or without the leading hash", () => {
|
||||
const hash = encodeInventoryHash(inventory);
|
||||
expect(decodeInventoryHash(hash.slice(1))?.inventory).toEqual(inventory);
|
||||
});
|
||||
|
||||
it("returns null when there is no fragment", () => {
|
||||
expect(decodeInventoryHash("")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the fragment carries something else", () => {
|
||||
expect(decodeInventoryHash("#other=1")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for an empty inventory parameter", () => {
|
||||
expect(decodeInventoryHash("#i=")).toBeNull();
|
||||
});
|
||||
|
||||
it("reports a damaged link rather than throwing", () => {
|
||||
// Lone '!' is not valid base64, so atob throws — and it must be caught in
|
||||
// the same place a JSON failure would be.
|
||||
expect(decodeInventoryHash("#i=!!!")).toEqual({
|
||||
inventory: EMPTY,
|
||||
dropped: ["This link is damaged."],
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a link that decodes but is not an inventory", () => {
|
||||
const result = decodeInventoryHash(`#i=${toBase64Url("42")}`);
|
||||
expect(result?.dropped).toEqual(["Not an inventory."]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("browser ports", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
window.location.hash = "";
|
||||
});
|
||||
|
||||
it("browserClipboard writes through navigator.clipboard", async () => {
|
||||
const writeText = vi.fn<(text: string) => Promise<void>>().mockResolvedValue();
|
||||
Object.defineProperty(navigator, "clipboard", { value: { writeText }, configurable: true });
|
||||
await browserClipboard.writeText("payload");
|
||||
expect(writeText).toHaveBeenCalledWith("payload");
|
||||
});
|
||||
|
||||
it("browserSaveFile builds, clicks, and revokes an object URL", () => {
|
||||
// jsdom has no createObjectURL, but the properties are assignable — so the
|
||||
// real implementation can be exercised rather than mocked away wholesale.
|
||||
const createObjectURL = vi.fn(() => "blob:kcd2");
|
||||
const revokeObjectURL = vi.fn();
|
||||
Object.defineProperty(URL, "createObjectURL", { value: createObjectURL, configurable: true });
|
||||
Object.defineProperty(URL, "revokeObjectURL", { value: revokeObjectURL, configurable: true });
|
||||
const click = vi
|
||||
.spyOn(HTMLAnchorElement.prototype, "click")
|
||||
.mockImplementation(function mockClick(this: HTMLAnchorElement) {
|
||||
expect(this.download).toBe(EXPORT_FILENAME);
|
||||
expect(this.getAttribute("href")).toBe("blob:kcd2");
|
||||
});
|
||||
|
||||
browserSaveFile(EXPORT_FILENAME, "{}");
|
||||
|
||||
expect(createObjectURL).toHaveBeenCalledTimes(1);
|
||||
expect(click).toHaveBeenCalledTimes(1);
|
||||
expect(revokeObjectURL).toHaveBeenCalledWith("blob:kcd2");
|
||||
});
|
||||
|
||||
it("browserUrlHash reads the fragment", () => {
|
||||
window.location.hash = "#i=abc";
|
||||
expect(browserUrlHash.read()).toBe("#i=abc");
|
||||
});
|
||||
|
||||
it("browserUrlHash clears the fragment without reloading", () => {
|
||||
window.location.hash = "#i=abc";
|
||||
browserUrlHash.clear();
|
||||
expect(window.location.hash).toBe("");
|
||||
});
|
||||
|
||||
it("browserUrlHash builds a base URL with no fragment", () => {
|
||||
window.location.hash = "#i=abc";
|
||||
expect(browserUrlHash.base()).toBe(window.location.origin + window.location.pathname);
|
||||
expect(browserUrlHash.base()).not.toContain("#");
|
||||
});
|
||||
});
|
||||
|
||||
35
kcd2_dice_solver/src/test/fixtures.ts
Normal file
35
kcd2_dice_solver/src/test/fixtures.ts
Normal file
@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Shared component-test fixtures.
|
||||
*
|
||||
* In src/test/ because vite.config.ts excludes that path from coverage;
|
||||
* a fixture beside the source would be counted as production code and
|
||||
* break the 100% gate.
|
||||
*/
|
||||
|
||||
import type { Die } from "../data/dice.ts";
|
||||
import type { SolveResponse } from "../core/solve.ts";
|
||||
|
||||
export const ordinary: Die = {
|
||||
id: "ordinary",
|
||||
name: "Ordinary die",
|
||||
description: "An ordinary playing die.",
|
||||
weights: [1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6],
|
||||
wildcardFaces: [],
|
||||
wildScoresAlone: false,
|
||||
};
|
||||
|
||||
export const response: SolveResponse = {
|
||||
dice: new Array<Die>(6).fill(ordinary),
|
||||
evaluation: { ev: 399.1, bustProbability: 0.0309, p90: 900 },
|
||||
simulation: {
|
||||
meanPerTurn: 412.5,
|
||||
standardError: 3.2,
|
||||
bustRate: 0.2,
|
||||
throwsPerTurn: 1.4,
|
||||
turns: 20000,
|
||||
},
|
||||
optimal: true,
|
||||
alternatives: [],
|
||||
badges: [],
|
||||
inventorySize: 6,
|
||||
};
|
||||
241
linux_configuration/scripts/single_use/features/lib/aw_autostart.sh
Executable file
241
linux_configuration/scripts/single_use/features/lib/aw_autostart.sh
Executable file
@ -0,0 +1,241 @@
|
||||
#!/bin/bash
|
||||
# Autostart unit and the installed/running checks.
|
||||
#
|
||||
# Sourced by setup_activitywatch.sh; split out to keep aw_service.sh under the
|
||||
# 250-line cap. Sourced rather than run, so it inherits the caller's
|
||||
# strict mode and the variables defined above the source line.
|
||||
|
||||
# Function to setup autostart
|
||||
setup_autostart() {
|
||||
echo ""
|
||||
echo "5. Setting Up Autostart..."
|
||||
echo "========================="
|
||||
|
||||
local autostart_dir="$USER_HOME/.config/autostart"
|
||||
local desktop_file="$autostart_dir/activitywatch.desktop"
|
||||
local i3_config="$USER_HOME/.config/i3/config"
|
||||
|
||||
# Method 1: XDG Autostart (works with most desktop environments)
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
sudo -u "$ACTUAL_USER" mkdir -p "$autostart_dir"
|
||||
else
|
||||
mkdir -p "$autostart_dir"
|
||||
fi
|
||||
|
||||
# Create desktop file for autostart
|
||||
cat >"$desktop_file" <<EOF
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=ActivityWatch
|
||||
Comment=Automated time tracker
|
||||
Exec=aw-qt
|
||||
Icon=activitywatch
|
||||
Hidden=false
|
||||
NoDisplay=false
|
||||
X-GNOME-Autostart-enabled=true
|
||||
StartupNotify=false
|
||||
Terminal=false
|
||||
Categories=Utility;
|
||||
EOF
|
||||
|
||||
# Set proper ownership if running as root
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
chown "$ACTUAL_USER:$ACTUAL_USER" "$desktop_file"
|
||||
fi
|
||||
|
||||
echo "✓ Created XDG autostart entry: $desktop_file"
|
||||
|
||||
# Method 2: i3 config autostart (specific to i3)
|
||||
if [[ -f $i3_config ]]; then
|
||||
# Check if autostart entry already exists
|
||||
if ! grep -q "aw-qt" "$i3_config"; then
|
||||
# Add autostart entry to i3 config
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
# Running as root
|
||||
sudo -u "$ACTUAL_USER" bash -c "cat <<'EOF' >> '$i3_config'
|
||||
|
||||
# Auto-start ActivityWatch
|
||||
exec --no-startup-id aw-qt
|
||||
EOF"
|
||||
else
|
||||
{
|
||||
printf '\n'
|
||||
printf '# Auto-start ActivityWatch\n'
|
||||
printf 'exec --no-startup-id aw-qt\n'
|
||||
} >>"$i3_config"
|
||||
fi
|
||||
|
||||
echo "✓ Added ActivityWatch to i3 config autostart"
|
||||
else
|
||||
echo "✓ ActivityWatch autostart already exists in i3 config"
|
||||
fi
|
||||
else
|
||||
echo "! i3 config not found at $i3_config"
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to create i3blocks status script
|
||||
create_i3blocks_status() {
|
||||
echo ""
|
||||
echo "6. Creating i3blocks Status Script..."
|
||||
echo "===================================="
|
||||
|
||||
local i3blocks_dir="$USER_HOME/.config/i3blocks"
|
||||
local status_script="$i3blocks_dir/activitywatch_status.sh"
|
||||
|
||||
# Create i3blocks directory if it doesn't exist
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
sudo -u "$ACTUAL_USER" mkdir -p "$i3blocks_dir"
|
||||
else
|
||||
mkdir -p "$i3blocks_dir"
|
||||
fi
|
||||
|
||||
# Create the status script
|
||||
cat >"$status_script" <<'EOF'
|
||||
#!/bin/bash
|
||||
# ActivityWatch status script for i3blocks
|
||||
# Shows ActivityWatch installation and running status
|
||||
|
||||
# Check if ActivityWatch is installed
|
||||
check_installed() {
|
||||
# Check if activitywatch-bin package is installed
|
||||
if pacman -Qi activitywatch-bin &>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check if aw-qt binary exists
|
||||
if command -v aw-qt &>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
# Check if ActivityWatch is running
|
||||
check_running() {
|
||||
# Check for aw-qt process
|
||||
if pgrep -f "aw-qt" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check for aw-server process
|
||||
if pgrep -f "aw-server" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
# Main logic
|
||||
if ! check_installed; then
|
||||
echo "AW uninstalled"
|
||||
echo
|
||||
echo "#FF0000" # Red
|
||||
elif check_running; then
|
||||
echo "AW on"
|
||||
echo
|
||||
echo "#00FF00" # Green
|
||||
else
|
||||
echo "AW off"
|
||||
echo
|
||||
echo "#FF0000" # Red
|
||||
fi
|
||||
EOF
|
||||
|
||||
chmod +x "$status_script"
|
||||
|
||||
# Set proper ownership if running as root
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
chown "$ACTUAL_USER:$ACTUAL_USER" "$status_script"
|
||||
fi
|
||||
|
||||
echo "✓ Created i3blocks status script: $status_script"
|
||||
|
||||
# Show configuration instructions
|
||||
echo ""
|
||||
echo "To add to your i3blocks config, add this block:"
|
||||
echo ""
|
||||
echo "[activitywatch]"
|
||||
echo "command=~/.config/i3blocks/activitywatch_status.sh"
|
||||
echo "interval=10"
|
||||
echo "color=#FFFFFF"
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Function to test the setup
|
||||
test_setup() {
|
||||
echo ""
|
||||
echo "7. Testing Setup..."
|
||||
echo "=================="
|
||||
|
||||
echo "Installation status:"
|
||||
if check_activitywatch_installed >/dev/null 2>&1; then
|
||||
echo "✓ ActivityWatch is installed"
|
||||
else
|
||||
echo "✗ ActivityWatch is not installed"
|
||||
fi
|
||||
|
||||
echo "Running status:"
|
||||
if check_activitywatch_running >/dev/null 2>&1; then
|
||||
echo "✓ ActivityWatch is running"
|
||||
else
|
||||
echo "✗ ActivityWatch is not running"
|
||||
fi
|
||||
|
||||
echo "Autostart files:"
|
||||
if [[ -f "$USER_HOME/.config/autostart/activitywatch.desktop" ]]; then
|
||||
echo "✓ XDG autostart file exists"
|
||||
else
|
||||
echo "✗ XDG autostart file missing"
|
||||
fi
|
||||
|
||||
if [[ -f "$USER_HOME/.config/i3/config" ]] && grep -q "aw-qt" "$USER_HOME/.config/i3/config"; then
|
||||
echo "✓ i3 autostart configured"
|
||||
else
|
||||
echo "! i3 autostart may not be configured"
|
||||
fi
|
||||
|
||||
echo "i3blocks status script:"
|
||||
if [[ -x "$USER_HOME/.config/i3blocks/activitywatch_status.sh" ]]; then
|
||||
echo "✓ i3blocks status script created"
|
||||
echo "Testing status script:"
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
sudo -u "$ACTUAL_USER" "$USER_HOME/.config/i3blocks/activitywatch_status.sh"
|
||||
else
|
||||
"$USER_HOME/.config/i3blocks/activitywatch_status.sh"
|
||||
fi
|
||||
else
|
||||
echo "✗ i3blocks status script missing"
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to show final instructions
|
||||
show_instructions() {
|
||||
echo ""
|
||||
echo "=========================================="
|
||||
echo "ActivityWatch Setup Complete"
|
||||
echo "=========================================="
|
||||
echo "Summary:"
|
||||
echo "✓ ActivityWatch installation checked/completed"
|
||||
echo "✓ ActivityWatch startup configured"
|
||||
echo "✓ Autostart configured (XDG + i3)"
|
||||
echo "✓ i3blocks status script created"
|
||||
echo ""
|
||||
echo "Next steps:"
|
||||
echo "1. Add the i3blocks configuration to your config file:"
|
||||
echo " ~/.config/i3blocks/config"
|
||||
echo ""
|
||||
echo "2. Reload i3 configuration:"
|
||||
echo " Super+Shift+R"
|
||||
echo ""
|
||||
echo "3. ActivityWatch web interface should be available at:"
|
||||
echo " http://localhost:5600"
|
||||
echo ""
|
||||
echo "4. Check system tray for ActivityWatch icon"
|
||||
echo ""
|
||||
echo "Files created:"
|
||||
echo " ~/.config/autostart/activitywatch.desktop"
|
||||
echo " ~/.config/i3blocks/activitywatch_status.sh"
|
||||
echo " ~/.config/i3/config (modified)"
|
||||
echo ""
|
||||
}
|
||||
75
linux_configuration/scripts/single_use/features/lib/aw_install.sh
Executable file
75
linux_configuration/scripts/single_use/features/lib/aw_install.sh
Executable file
@ -0,0 +1,75 @@
|
||||
#!/bin/bash
|
||||
# ActivityWatch install, both packaged and manual.
|
||||
#
|
||||
# Sourced by setup_activitywatch.sh; split out to keep it under the 250-line
|
||||
# cap. Sourced rather than run, so it inherits the caller's strict mode
|
||||
# and the variables defined above the source line.
|
||||
|
||||
# Function to install ActivityWatch
|
||||
install_activitywatch() {
|
||||
echo ""
|
||||
echo "2. Installing ActivityWatch..."
|
||||
echo "============================="
|
||||
|
||||
# Check if we need sudo for installation
|
||||
check_sudo "install"
|
||||
|
||||
echo "Installing activitywatch-bin from AUR..."
|
||||
|
||||
# Check if an AUR helper is available
|
||||
local aur_helpers=("yay" "paru" "makepkg")
|
||||
local helper_found=""
|
||||
|
||||
for helper in "${aur_helpers[@]}"; do
|
||||
if command -v "$helper" &>/dev/null; then
|
||||
helper_found="$helper"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ -n $helper_found && $helper_found != "makepkg" ]]; then
|
||||
echo "Using AUR helper: $helper_found"
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
# Running as root, need to install as user
|
||||
sudo -u "$ACTUAL_USER" "$helper_found" -S --noconfirm activitywatch-bin
|
||||
else
|
||||
"$helper_found" -S --noconfirm activitywatch-bin
|
||||
fi
|
||||
else
|
||||
echo "No AUR helper found. Installing manually with makepkg..."
|
||||
install_activitywatch_manual
|
||||
fi
|
||||
|
||||
echo "✓ ActivityWatch installation completed"
|
||||
}
|
||||
|
||||
# Function to manually install ActivityWatch via makepkg
|
||||
install_activitywatch_manual() {
|
||||
local temp_dir="/tmp/activitywatch-install"
|
||||
local original_user="$ACTUAL_USER"
|
||||
|
||||
# Create temp directory
|
||||
mkdir -p "$temp_dir"
|
||||
# Guarded: the next command is `git clone ... .`, which would otherwise
|
||||
# clone into whatever directory the caller happened to be in.
|
||||
cd "$temp_dir" || {
|
||||
print_error "Cannot enter $temp_dir"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Download PKGBUILD
|
||||
if command -v git &>/dev/null; then
|
||||
sudo -u "$original_user" git clone https://aur.archlinux.org/activitywatch-bin.git .
|
||||
else
|
||||
echo "Installing git..."
|
||||
pacman -S --noconfirm git
|
||||
sudo -u "$original_user" git clone https://aur.archlinux.org/activitywatch-bin.git .
|
||||
fi
|
||||
|
||||
# Build and install package
|
||||
sudo -u "$original_user" makepkg -si --noconfirm
|
||||
|
||||
# Cleanup
|
||||
cd /
|
||||
rm -rf "$temp_dir"
|
||||
}
|
||||
68
linux_configuration/scripts/single_use/features/lib/aw_service.sh
Executable file
68
linux_configuration/scripts/single_use/features/lib/aw_service.sh
Executable file
@ -0,0 +1,68 @@
|
||||
#!/bin/bash
|
||||
# Service checks, startup and the autostart unit.
|
||||
#
|
||||
# Sourced by setup_activitywatch.sh; split out to keep it under the 250-line
|
||||
# cap. Sourced rather than run, so it inherits the caller's strict mode
|
||||
# and the variables defined above the source line.
|
||||
|
||||
# Function to check if ActivityWatch is running
|
||||
check_activitywatch_running() {
|
||||
echo ""
|
||||
echo "3. Checking ActivityWatch Status..."
|
||||
echo "=================================="
|
||||
|
||||
# Check for aw-qt process
|
||||
if pgrep -f "aw-qt" >/dev/null; then
|
||||
echo "✓ ActivityWatch (aw-qt) is running"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check for aw-server process
|
||||
if pgrep -f "aw-server" >/dev/null; then
|
||||
echo "✓ ActivityWatch server is running"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "✗ ActivityWatch is not running"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Function to start ActivityWatch
|
||||
start_activitywatch() {
|
||||
echo ""
|
||||
echo "4. Starting ActivityWatch..."
|
||||
echo "==========================="
|
||||
|
||||
# Find aw-qt executable
|
||||
local aw_qt_path=""
|
||||
|
||||
if command -v aw-qt &>/dev/null; then
|
||||
aw_qt_path="$(which aw-qt)"
|
||||
elif [[ -x "/usr/bin/aw-qt" ]]; then
|
||||
aw_qt_path="/usr/bin/aw-qt"
|
||||
else
|
||||
echo "✗ Could not find aw-qt executable"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "Starting ActivityWatch as user: $ACTUAL_USER"
|
||||
echo "Using aw-qt from: $aw_qt_path"
|
||||
|
||||
# Start as the actual user in the background
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
# Running as root, start as user
|
||||
sudo -u "$ACTUAL_USER" env DISPLAY=:0 "$aw_qt_path" &
|
||||
else
|
||||
# Running as user
|
||||
"$aw_qt_path" &
|
||||
fi
|
||||
|
||||
# Give it time to start
|
||||
sleep 3
|
||||
|
||||
if check_activitywatch_running >/dev/null 2>&1; then
|
||||
echo "✓ ActivityWatch started successfully"
|
||||
else
|
||||
echo "! ActivityWatch may be starting (check system tray)"
|
||||
fi
|
||||
}
|
||||
74
linux_configuration/scripts/single_use/features/lib/wg_firewall.sh
Executable file
74
linux_configuration/scripts/single_use/features/lib/wg_firewall.sh
Executable file
@ -0,0 +1,74 @@
|
||||
#!/bin/bash
|
||||
# nftables ruleset, its verification and sshd hardening.
|
||||
#
|
||||
# Sourced by setup_wireguard_ssh.sh; split out to keep wg_keys.sh under the
|
||||
# 250-line cap. Sourced rather than run, so it inherits the caller's
|
||||
# strict mode and the variables defined above the source line.
|
||||
|
||||
write_nftables_ruleset() {
|
||||
detect_lan_subnet
|
||||
if [[ -f $NFT_CONF ]]; then
|
||||
cp "$NFT_CONF" "${NFT_CONF}.bak.$(date +%s)"
|
||||
log_warn "Backed up existing ${NFT_CONF} before overwriting."
|
||||
fi
|
||||
local web_rule=""
|
||||
if [[ $ALLOW_WEB == "true" ]]; then
|
||||
web_rule=$'\n\t\ttcp dport { 80, 443 } accept'
|
||||
fi
|
||||
# DNS blocker (setup_dns_blocker.sh): serve DNS (53) -- and DHCP (67) when
|
||||
# this PC is the LAN DHCP server -- to LAN clients only. Restricted to the
|
||||
# LAN subnet so nothing is ever exposed to the internet.
|
||||
local dns_rule="" dhcp_rule=""
|
||||
if [[ $ALLOW_DNS == "true" ]]; then
|
||||
dns_rule=$'\n\t\tip saddr '"${LAN_SUBNET}"$' udp dport 53 accept'
|
||||
dns_rule+=$'\n\t\tip saddr '"${LAN_SUBNET}"$' tcp dport 53 accept'
|
||||
# DHCP clients have no IP yet (saddr 0.0.0.0 -> 255.255.255.255) and the
|
||||
# broadcast is classified INVALID by conntrack -- so this rule MUST sit
|
||||
# BEFORE 'ct state invalid drop' and match the client source port, not a
|
||||
# saddr. Link-local only: :67 broadcasts never route in from the internet.
|
||||
dhcp_rule=$'\n\t\tudp sport 68 udp dport 67 accept'
|
||||
fi
|
||||
cat >"${NFT_CONF}.new" <<EOF
|
||||
#!/usr/sbin/nft -f
|
||||
flush ruleset
|
||||
|
||||
table inet filter {
|
||||
chain input {
|
||||
type filter hook input priority 0; policy drop;
|
||||
|
||||
iif "lo" accept
|
||||
ct state established,related accept${dhcp_rule}
|
||||
ct state invalid drop
|
||||
|
||||
icmp type { destination-unreachable, time-exceeded, parameter-problem, echo-request } accept
|
||||
icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, nd-neighbor-solicit, nd-neighbor-advert, echo-request } accept
|
||||
|
||||
udp dport ${WG_PORT} accept
|
||||
|
||||
iifname "${WG_IFACE}" tcp dport 22 accept
|
||||
ip saddr ${LAN_SUBNET} tcp dport 22 accept${web_rule}${dns_rule}
|
||||
}
|
||||
chain forward {
|
||||
type filter hook forward priority 0; policy drop;
|
||||
}
|
||||
chain output {
|
||||
type filter hook output priority 0; policy accept;
|
||||
}
|
||||
}
|
||||
EOF
|
||||
}
|
||||
|
||||
verify_nftables_then_apply() {
|
||||
nft -c -f "${NFT_CONF}.new" || die "nftables ruleset failed syntax check -- not applying."
|
||||
mv "${NFT_CONF}.new" "$NFT_CONF"
|
||||
log_warn "Applying a default-drop firewall now."
|
||||
nft -f "$NFT_CONF"
|
||||
sleep 2
|
||||
if ! is_service_active sshd; then
|
||||
nft flush ruleset
|
||||
die "sshd died after applying nftables -- rolled back. Investigate before retrying."
|
||||
fi
|
||||
log_ok "nftables applied; sshd is still active."
|
||||
log_warn "Before closing this terminal, open a SECOND ssh session now and confirm it connects."
|
||||
enable_service nftables
|
||||
}
|
||||
42
linux_configuration/scripts/single_use/features/lib/wg_keys.sh
Executable file
42
linux_configuration/scripts/single_use/features/lib/wg_keys.sh
Executable file
@ -0,0 +1,42 @@
|
||||
#!/bin/bash
|
||||
# Key generation and the WireGuard service.
|
||||
#
|
||||
# Sourced by setup_wireguard_ssh.sh; split out to keep it under the 250-line
|
||||
# cap. Sourced rather than run, so it inherits the caller's strict mode
|
||||
# and the variables defined above the source line.
|
||||
|
||||
generate_server_keys() {
|
||||
ensure_dir "$WG_DIR"
|
||||
chmod 700 "$WG_DIR"
|
||||
if [[ -f "${WG_DIR}/server_private.key" ]]; then
|
||||
log_info "Server keypair already exists -- not rotating (would break existing peer configs)."
|
||||
return 0
|
||||
fi
|
||||
umask 077
|
||||
wg genkey | tee "${WG_DIR}/server_private.key" | wg pubkey >"${WG_DIR}/server_public.key"
|
||||
log_ok "Generated server keypair."
|
||||
}
|
||||
|
||||
write_wg0_conf() {
|
||||
if [[ -f $WG_CONF ]]; then
|
||||
log_info "${WG_CONF} already exists -- leaving peers intact, not regenerating."
|
||||
return 0
|
||||
fi
|
||||
local server_private_key
|
||||
server_private_key=$(<"${WG_DIR}/server_private.key")
|
||||
umask 077
|
||||
cat >"$WG_CONF" <<EOF
|
||||
[Interface]
|
||||
Address = ${WG_SERVER_IP}/24
|
||||
ListenPort = ${WG_PORT}
|
||||
PrivateKey = ${server_private_key}
|
||||
# No PostUp/PostDown NAT: this is a host-only tunnel, not a routed VPN.
|
||||
EOF
|
||||
chmod 600 "$WG_CONF"
|
||||
log_ok "Wrote ${WG_CONF}."
|
||||
}
|
||||
|
||||
enable_wg_service() {
|
||||
enable_service "wg-quick@${WG_IFACE}"
|
||||
log_ok "wg-quick@${WG_IFACE} enabled and started."
|
||||
}
|
||||
234
linux_configuration/scripts/single_use/features/lib/wg_sshd.sh
Executable file
234
linux_configuration/scripts/single_use/features/lib/wg_sshd.sh
Executable file
@ -0,0 +1,234 @@
|
||||
#!/bin/bash
|
||||
# sshd hardening and the DuckDNS record update.
|
||||
#
|
||||
# Sourced by setup_wireguard_ssh.sh; split out to keep wg_firewall.sh under the
|
||||
# 250-line cap. Sourced rather than run, so it inherits the caller's
|
||||
# strict mode and the variables defined above the source line.
|
||||
|
||||
harden_sshd() {
|
||||
log_warn "Before disabling password auth, confirm key-based login works."
|
||||
log_warn "In ANOTHER terminal, run: ssh -o PreferredAuthentications=publickey $(get_actual_user)@localhost echo ok"
|
||||
if ! ask_yes_no "Did key-based login succeed?"; then
|
||||
die "Aborting -- run ssh-copy-id to set up key auth first, then re-run setup."
|
||||
fi
|
||||
cat >"$SSHD_DROPIN" <<'EOF'
|
||||
# Managed by setup_wireguard_ssh.sh -- drop-in, does not touch sshd_config.
|
||||
PasswordAuthentication no
|
||||
PubkeyAuthentication yes
|
||||
PermitRootLogin no
|
||||
EOF
|
||||
sshd -t || {
|
||||
rm -f "$SSHD_DROPIN"
|
||||
die "sshd config invalid after adding drop-in -- removed it."
|
||||
}
|
||||
systemctl reload sshd
|
||||
log_ok "sshd hardened: key-only auth, no root login."
|
||||
}
|
||||
|
||||
duckdns_already_updated() {
|
||||
local domain="$1" actual_user line script
|
||||
actual_user=$(get_actual_user)
|
||||
while IFS= read -r line; do
|
||||
[[ $line =~ ^[[:space:]]*(#|$) ]] && continue
|
||||
for script in $line; do
|
||||
[[ -f $script ]] || continue
|
||||
if grep -q "duckdns.org/update?domains=${domain}" "$script" 2>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
done < <(crontab -u "$actual_user" -l 2>/dev/null || true)
|
||||
return 1
|
||||
}
|
||||
|
||||
setup_duckdns() {
|
||||
if [[ -z $DUCKDNS_DOMAIN || -z $DUCKDNS_TOKEN ]]; then
|
||||
read -r -p "DuckDNS subdomain (without .duckdns.org): " DUCKDNS_DOMAIN
|
||||
read -r -p "DuckDNS token: " DUCKDNS_TOKEN
|
||||
[[ -n $DUCKDNS_DOMAIN && -n $DUCKDNS_TOKEN ]] || die "Both fields are required."
|
||||
save_config
|
||||
fi
|
||||
if duckdns_already_updated "$DUCKDNS_DOMAIN"; then
|
||||
log_info "An existing cron job already keeps ${DUCKDNS_DOMAIN}.duckdns.org updated -- not adding a duplicate."
|
||||
return 0
|
||||
fi
|
||||
ensure_dir "$DUCKDNS_DIR"
|
||||
cat >"${DUCKDNS_DIR}/duck.sh" <<EOF
|
||||
#!/bin/bash
|
||||
echo url="https://www.duckdns.org/update?domains=${DUCKDNS_DOMAIN}&token=${DUCKDNS_TOKEN}&ip=" | curl -fsS -o "${DUCKDNS_DIR}/duck.log" -K -
|
||||
EOF
|
||||
chmod 700 "${DUCKDNS_DIR}/duck.sh"
|
||||
bash "${DUCKDNS_DIR}/duck.sh"
|
||||
(
|
||||
crontab -l 2>/dev/null || true
|
||||
) | grep -vF "${DUCKDNS_DIR}/duck.sh" | {
|
||||
cat
|
||||
echo "*/5 * * * * ${DUCKDNS_DIR}/duck.sh >/dev/null 2>&1"
|
||||
} | crontab -
|
||||
log_ok "DuckDNS configured: ${DUCKDNS_DOMAIN}.duckdns.org (refreshed every 5 min via cron)."
|
||||
}
|
||||
|
||||
next_free_wg_ip() {
|
||||
local used octet
|
||||
used=$(grep -oP 'AllowedIPs\s*=\s*10\.8\.0\.\K[0-9]+' "$WG_CONF" 2>/dev/null || true)
|
||||
for ((octet = 2; octet <= 254; octet++)); do
|
||||
if ! grep -qx "$octet" <<<"$used"; then
|
||||
echo "10.8.0.${octet}"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
die "No free IPs left in ${WG_SUBNET}."
|
||||
}
|
||||
|
||||
add_phone_peer() {
|
||||
local name="${1:?usage: add-peer <name>}"
|
||||
[[ -f $WG_CONF ]] || die "Run 'setup' first -- ${WG_CONF} does not exist yet."
|
||||
[[ -n $DUCKDNS_DOMAIN ]] || die "DuckDNS domain not configured -- run 'setup' first."
|
||||
if grep -q "# peer:${name}\$" "$WG_CONF"; then
|
||||
die "A peer named '${name}' already exists in ${WG_CONF}. Use 'revoke ${name}' first to replace it."
|
||||
fi
|
||||
|
||||
ensure_dir "$WG_CLIENTS_DIR"
|
||||
chmod 700 "$WG_CLIENTS_DIR"
|
||||
|
||||
local tmpdir
|
||||
tmpdir=$(mktemp -d)
|
||||
trap 'rm -rf "$tmpdir"; trap - RETURN' RETURN
|
||||
|
||||
umask 077
|
||||
wg genkey | tee "${tmpdir}/priv" | wg pubkey >"${tmpdir}/pub"
|
||||
local client_priv client_pub server_pub peer_ip
|
||||
client_priv=$(<"${tmpdir}/priv")
|
||||
client_pub=$(<"${tmpdir}/pub")
|
||||
server_pub=$(<"${WG_DIR}/server_public.key")
|
||||
peer_ip=$(next_free_wg_ip)
|
||||
|
||||
cat >>"$WG_CONF" <<EOF
|
||||
|
||||
[Peer] # peer:${name}
|
||||
PublicKey = ${client_pub}
|
||||
AllowedIPs = ${peer_ip}/32
|
||||
EOF
|
||||
if is_service_active "wg-quick@${WG_IFACE}"; then
|
||||
wg syncconf "$WG_IFACE" <(wg-quick strip "$WG_IFACE")
|
||||
fi
|
||||
|
||||
local client_conf="${WG_CLIENTS_DIR}/${name}.conf"
|
||||
cat >"$client_conf" <<EOF
|
||||
[Interface]
|
||||
PrivateKey = ${client_priv}
|
||||
Address = ${peer_ip}/32
|
||||
# No DNS server here on purpose: AllowedIPs below is scoped to the WireGuard
|
||||
# subnet only (host-only tunnel), so a DNS server outside that subnet would
|
||||
# be unreachable through the tunnel -- Android would then have no working
|
||||
# resolver at all while the tunnel is active, breaking DNS for everything.
|
||||
|
||||
[Peer]
|
||||
PublicKey = ${server_pub}
|
||||
Endpoint = ${DUCKDNS_DOMAIN}.duckdns.org:${WG_PORT}
|
||||
AllowedIPs = ${WG_SUBNET}
|
||||
PersistentKeepalive = 25
|
||||
EOF
|
||||
chmod 600 "$client_conf"
|
||||
log_ok "Phone config written to ${client_conf}"
|
||||
log_info "Scan this QR code with the WireGuard Android app:"
|
||||
qrencode -t ansiutf8 <"$client_conf"
|
||||
}
|
||||
|
||||
revoke_peer() {
|
||||
local name="${1:?usage: revoke <name>}"
|
||||
[[ -f $WG_CONF ]] || die "${WG_CONF} does not exist."
|
||||
grep -q "# peer:${name}\$" "$WG_CONF" || die "No peer named '${name}' found."
|
||||
|
||||
local tmp
|
||||
tmp=$(mktemp)
|
||||
trap 'rm -f "$tmp"; trap - RETURN' RETURN
|
||||
awk -v marker="# peer:${name}" '
|
||||
$0 ~ ("^\\[Peer\\].*" marker "$") { skip = 1; next }
|
||||
skip && /^$/ { skip = 0; next }
|
||||
skip { next }
|
||||
{ print }
|
||||
' "$WG_CONF" >"$tmp"
|
||||
cat "$tmp" >"$WG_CONF"
|
||||
chmod 600 "$WG_CONF"
|
||||
|
||||
if is_service_active "wg-quick@${WG_IFACE}"; then
|
||||
wg syncconf "$WG_IFACE" <(wg-quick strip "$WG_IFACE")
|
||||
fi
|
||||
rm -f "${WG_CLIENTS_DIR}/${name}.conf"
|
||||
log_ok "Revoked peer '${name}'."
|
||||
}
|
||||
|
||||
print_router_instructions() {
|
||||
local lan_ip
|
||||
lan_ip=$(ip route get 1.1.1.1 2>/dev/null | awk '{print $7; exit}')
|
||||
cat <<EOF
|
||||
|
||||
=== Manual step: forward a port on your router (cannot be automated) ===
|
||||
1. Log into your router admin page (often http://192.168.1.1 or http://192.168.0.1).
|
||||
2. Find "Port Forwarding" / "Virtual Server" / "NAT" settings.
|
||||
3. Forward UDP port ${WG_PORT} -> ${lan_ip} (UDP only -- do NOT forward TCP/22).
|
||||
4. Save (and reboot the router if it requires it).
|
||||
5. Confirm your ISP gives you a real public IPv4 (not CGNAT):
|
||||
curl -s https://api.ipify.org
|
||||
getent hosts ${DUCKDNS_DOMAIN:-<your-domain>}.duckdns.org
|
||||
These two must match and must NOT be in 100.64.0.0/10 (CGNAT range).
|
||||
EOF
|
||||
}
|
||||
|
||||
print_android_instructions() {
|
||||
cat <<EOF
|
||||
|
||||
=== Manual step: install FOSS apps on your Android phone ===
|
||||
1. Install F-Droid (https://f-droid.org/) if you don't have it.
|
||||
2. From F-Droid, install "WireGuard" (official app, org.wireguard.android).
|
||||
3. From F-Droid, install "Termux" (then run: pkg install openssh) or "ConnectBot".
|
||||
4. Open WireGuard -> "+" -> "Scan from QR code" -> scan the code printed above.
|
||||
5. Toggle the tunnel on.
|
||||
6. From Termux/ConnectBot: ssh $(get_actual_user)@${WG_SERVER_IP}
|
||||
EOF
|
||||
}
|
||||
|
||||
allow_web() {
|
||||
export ALLOW_WEB=true
|
||||
save_config
|
||||
write_nftables_ruleset
|
||||
verify_nftables_then_apply
|
||||
log_ok "Opened tcp/80 and tcp/443 in the input chain (persisted -- future 'setup' re-runs keep this rule)."
|
||||
}
|
||||
|
||||
allow_dns() {
|
||||
export ALLOW_DNS=true
|
||||
save_config
|
||||
write_nftables_ruleset
|
||||
verify_nftables_then_apply
|
||||
log_ok "Opened udp/tcp 53 from ${LAN_SUBNET:-the LAN} in the input chain (persisted -- future 'setup' re-runs keep this rule)."
|
||||
}
|
||||
|
||||
status_cmd() {
|
||||
echo "=== WireGuard ==="
|
||||
wg show 2>/dev/null || echo "(interface not up)"
|
||||
echo
|
||||
echo "=== wg-quick@${WG_IFACE} service ==="
|
||||
systemctl status "wg-quick@${WG_IFACE}" --no-pager 2>/dev/null || echo "(not installed)"
|
||||
echo
|
||||
echo "=== nftables (input chain) ==="
|
||||
nft list ruleset 2>/dev/null | sed -n '/chain input/,/}/p' || echo "(nftables not active)"
|
||||
echo
|
||||
echo "=== sshd password auth ==="
|
||||
sshd -T 2>/dev/null | grep -i passwordauthentication || echo "(could not query sshd)"
|
||||
}
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: $0 <command> [args]
|
||||
|
||||
Commands:
|
||||
setup Full first-time setup (WireGuard, firewall, sshd, DuckDNS).
|
||||
add-peer <name> Provision a new phone/laptop and print its QR code.
|
||||
allow-web Open tcp/80 and tcp/443 in the firewall (for a web server on this host).
|
||||
allow-dns Open udp/tcp 53 from the LAN in the firewall (for the DNS blocker on this host).
|
||||
status Show WireGuard/firewall/sshd status.
|
||||
revoke <name> Remove a peer.
|
||||
help Show this message.
|
||||
EOF
|
||||
}
|
||||
@ -60,366 +60,13 @@ check_activitywatch_installed() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# Function to install ActivityWatch
|
||||
install_activitywatch() {
|
||||
echo ""
|
||||
echo "2. Installing ActivityWatch..."
|
||||
echo "============================="
|
||||
# shellcheck source=lib/aw_install.sh
|
||||
source "$SCRIPT_DIR/lib/aw_install.sh"
|
||||
# shellcheck source=lib/aw_service.sh
|
||||
source "$SCRIPT_DIR/lib/aw_service.sh"
|
||||
# shellcheck source=lib/aw_autostart.sh
|
||||
source "$SCRIPT_DIR/lib/aw_autostart.sh"
|
||||
|
||||
# Check if we need sudo for installation
|
||||
check_sudo "install"
|
||||
|
||||
echo "Installing activitywatch-bin from AUR..."
|
||||
|
||||
# Check if an AUR helper is available
|
||||
local aur_helpers=("yay" "paru" "makepkg")
|
||||
local helper_found=""
|
||||
|
||||
for helper in "${aur_helpers[@]}"; do
|
||||
if command -v "$helper" &>/dev/null; then
|
||||
helper_found="$helper"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ -n $helper_found && $helper_found != "makepkg" ]]; then
|
||||
echo "Using AUR helper: $helper_found"
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
# Running as root, need to install as user
|
||||
sudo -u "$ACTUAL_USER" "$helper_found" -S --noconfirm activitywatch-bin
|
||||
else
|
||||
"$helper_found" -S --noconfirm activitywatch-bin
|
||||
fi
|
||||
else
|
||||
echo "No AUR helper found. Installing manually with makepkg..."
|
||||
install_activitywatch_manual
|
||||
fi
|
||||
|
||||
echo "✓ ActivityWatch installation completed"
|
||||
}
|
||||
|
||||
# Function to manually install ActivityWatch via makepkg
|
||||
install_activitywatch_manual() {
|
||||
local temp_dir="/tmp/activitywatch-install"
|
||||
local original_user="$ACTUAL_USER"
|
||||
|
||||
# Create temp directory
|
||||
mkdir -p "$temp_dir"
|
||||
cd "$temp_dir"
|
||||
|
||||
# Download PKGBUILD
|
||||
if command -v git &>/dev/null; then
|
||||
sudo -u "$original_user" git clone https://aur.archlinux.org/activitywatch-bin.git .
|
||||
else
|
||||
echo "Installing git..."
|
||||
pacman -S --noconfirm git
|
||||
sudo -u "$original_user" git clone https://aur.archlinux.org/activitywatch-bin.git .
|
||||
fi
|
||||
|
||||
# Build and install package
|
||||
sudo -u "$original_user" makepkg -si --noconfirm
|
||||
|
||||
# Cleanup
|
||||
cd /
|
||||
rm -rf "$temp_dir"
|
||||
}
|
||||
|
||||
# Function to check if ActivityWatch is running
|
||||
check_activitywatch_running() {
|
||||
echo ""
|
||||
echo "3. Checking ActivityWatch Status..."
|
||||
echo "=================================="
|
||||
|
||||
# Check for aw-qt process
|
||||
if pgrep -f "aw-qt" >/dev/null; then
|
||||
echo "✓ ActivityWatch (aw-qt) is running"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check for aw-server process
|
||||
if pgrep -f "aw-server" >/dev/null; then
|
||||
echo "✓ ActivityWatch server is running"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "✗ ActivityWatch is not running"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Function to start ActivityWatch
|
||||
start_activitywatch() {
|
||||
echo ""
|
||||
echo "4. Starting ActivityWatch..."
|
||||
echo "==========================="
|
||||
|
||||
# Find aw-qt executable
|
||||
local aw_qt_path=""
|
||||
|
||||
if command -v aw-qt &>/dev/null; then
|
||||
aw_qt_path="$(which aw-qt)"
|
||||
elif [[ -x "/usr/bin/aw-qt" ]]; then
|
||||
aw_qt_path="/usr/bin/aw-qt"
|
||||
else
|
||||
echo "✗ Could not find aw-qt executable"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "Starting ActivityWatch as user: $ACTUAL_USER"
|
||||
echo "Using aw-qt from: $aw_qt_path"
|
||||
|
||||
# Start as the actual user in the background
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
# Running as root, start as user
|
||||
sudo -u "$ACTUAL_USER" env DISPLAY=:0 "$aw_qt_path" &
|
||||
else
|
||||
# Running as user
|
||||
"$aw_qt_path" &
|
||||
fi
|
||||
|
||||
# Give it time to start
|
||||
sleep 3
|
||||
|
||||
if check_activitywatch_running >/dev/null 2>&1; then
|
||||
echo "✓ ActivityWatch started successfully"
|
||||
else
|
||||
echo "! ActivityWatch may be starting (check system tray)"
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to setup autostart
|
||||
setup_autostart() {
|
||||
echo ""
|
||||
echo "5. Setting Up Autostart..."
|
||||
echo "========================="
|
||||
|
||||
local autostart_dir="$USER_HOME/.config/autostart"
|
||||
local desktop_file="$autostart_dir/activitywatch.desktop"
|
||||
local i3_config="$USER_HOME/.config/i3/config"
|
||||
|
||||
# Method 1: XDG Autostart (works with most desktop environments)
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
sudo -u "$ACTUAL_USER" mkdir -p "$autostart_dir"
|
||||
else
|
||||
mkdir -p "$autostart_dir"
|
||||
fi
|
||||
|
||||
# Create desktop file for autostart
|
||||
cat >"$desktop_file" <<EOF
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=ActivityWatch
|
||||
Comment=Automated time tracker
|
||||
Exec=aw-qt
|
||||
Icon=activitywatch
|
||||
Hidden=false
|
||||
NoDisplay=false
|
||||
X-GNOME-Autostart-enabled=true
|
||||
StartupNotify=false
|
||||
Terminal=false
|
||||
Categories=Utility;
|
||||
EOF
|
||||
|
||||
# Set proper ownership if running as root
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
chown "$ACTUAL_USER:$ACTUAL_USER" "$desktop_file"
|
||||
fi
|
||||
|
||||
echo "✓ Created XDG autostart entry: $desktop_file"
|
||||
|
||||
# Method 2: i3 config autostart (specific to i3)
|
||||
if [[ -f $i3_config ]]; then
|
||||
# Check if autostart entry already exists
|
||||
if ! grep -q "aw-qt" "$i3_config"; then
|
||||
# Add autostart entry to i3 config
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
# Running as root
|
||||
sudo -u "$ACTUAL_USER" bash -c "cat <<'EOF' >> '$i3_config'
|
||||
|
||||
# Auto-start ActivityWatch
|
||||
exec --no-startup-id aw-qt
|
||||
EOF"
|
||||
else
|
||||
{
|
||||
printf '\n'
|
||||
printf '# Auto-start ActivityWatch\n'
|
||||
printf 'exec --no-startup-id aw-qt\n'
|
||||
} >>"$i3_config"
|
||||
fi
|
||||
|
||||
echo "✓ Added ActivityWatch to i3 config autostart"
|
||||
else
|
||||
echo "✓ ActivityWatch autostart already exists in i3 config"
|
||||
fi
|
||||
else
|
||||
echo "! i3 config not found at $i3_config"
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to create i3blocks status script
|
||||
create_i3blocks_status() {
|
||||
echo ""
|
||||
echo "6. Creating i3blocks Status Script..."
|
||||
echo "===================================="
|
||||
|
||||
local i3blocks_dir="$USER_HOME/.config/i3blocks"
|
||||
local status_script="$i3blocks_dir/activitywatch_status.sh"
|
||||
|
||||
# Create i3blocks directory if it doesn't exist
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
sudo -u "$ACTUAL_USER" mkdir -p "$i3blocks_dir"
|
||||
else
|
||||
mkdir -p "$i3blocks_dir"
|
||||
fi
|
||||
|
||||
# Create the status script
|
||||
cat >"$status_script" <<'EOF'
|
||||
#!/bin/bash
|
||||
# ActivityWatch status script for i3blocks
|
||||
# Shows ActivityWatch installation and running status
|
||||
|
||||
# Check if ActivityWatch is installed
|
||||
check_installed() {
|
||||
# Check if activitywatch-bin package is installed
|
||||
if pacman -Qi activitywatch-bin &>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check if aw-qt binary exists
|
||||
if command -v aw-qt &>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
# Check if ActivityWatch is running
|
||||
check_running() {
|
||||
# Check for aw-qt process
|
||||
if pgrep -f "aw-qt" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check for aw-server process
|
||||
if pgrep -f "aw-server" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
# Main logic
|
||||
if ! check_installed; then
|
||||
echo "AW uninstalled"
|
||||
echo
|
||||
echo "#FF0000" # Red
|
||||
elif check_running; then
|
||||
echo "AW on"
|
||||
echo
|
||||
echo "#00FF00" # Green
|
||||
else
|
||||
echo "AW off"
|
||||
echo
|
||||
echo "#FF0000" # Red
|
||||
fi
|
||||
EOF
|
||||
|
||||
chmod +x "$status_script"
|
||||
|
||||
# Set proper ownership if running as root
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
chown "$ACTUAL_USER:$ACTUAL_USER" "$status_script"
|
||||
fi
|
||||
|
||||
echo "✓ Created i3blocks status script: $status_script"
|
||||
|
||||
# Show configuration instructions
|
||||
echo ""
|
||||
echo "To add to your i3blocks config, add this block:"
|
||||
echo ""
|
||||
echo "[activitywatch]"
|
||||
echo "command=~/.config/i3blocks/activitywatch_status.sh"
|
||||
echo "interval=10"
|
||||
echo "color=#FFFFFF"
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Function to test the setup
|
||||
test_setup() {
|
||||
echo ""
|
||||
echo "7. Testing Setup..."
|
||||
echo "=================="
|
||||
|
||||
echo "Installation status:"
|
||||
if check_activitywatch_installed >/dev/null 2>&1; then
|
||||
echo "✓ ActivityWatch is installed"
|
||||
else
|
||||
echo "✗ ActivityWatch is not installed"
|
||||
fi
|
||||
|
||||
echo "Running status:"
|
||||
if check_activitywatch_running >/dev/null 2>&1; then
|
||||
echo "✓ ActivityWatch is running"
|
||||
else
|
||||
echo "✗ ActivityWatch is not running"
|
||||
fi
|
||||
|
||||
echo "Autostart files:"
|
||||
if [[ -f "$USER_HOME/.config/autostart/activitywatch.desktop" ]]; then
|
||||
echo "✓ XDG autostart file exists"
|
||||
else
|
||||
echo "✗ XDG autostart file missing"
|
||||
fi
|
||||
|
||||
if [[ -f "$USER_HOME/.config/i3/config" ]] && grep -q "aw-qt" "$USER_HOME/.config/i3/config"; then
|
||||
echo "✓ i3 autostart configured"
|
||||
else
|
||||
echo "! i3 autostart may not be configured"
|
||||
fi
|
||||
|
||||
echo "i3blocks status script:"
|
||||
if [[ -x "$USER_HOME/.config/i3blocks/activitywatch_status.sh" ]]; then
|
||||
echo "✓ i3blocks status script created"
|
||||
echo "Testing status script:"
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
sudo -u "$ACTUAL_USER" "$USER_HOME/.config/i3blocks/activitywatch_status.sh"
|
||||
else
|
||||
"$USER_HOME/.config/i3blocks/activitywatch_status.sh"
|
||||
fi
|
||||
else
|
||||
echo "✗ i3blocks status script missing"
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to show final instructions
|
||||
show_instructions() {
|
||||
echo ""
|
||||
echo "=========================================="
|
||||
echo "ActivityWatch Setup Complete"
|
||||
echo "=========================================="
|
||||
echo "Summary:"
|
||||
echo "✓ ActivityWatch installation checked/completed"
|
||||
echo "✓ ActivityWatch startup configured"
|
||||
echo "✓ Autostart configured (XDG + i3)"
|
||||
echo "✓ i3blocks status script created"
|
||||
echo ""
|
||||
echo "Next steps:"
|
||||
echo "1. Add the i3blocks configuration to your config file:"
|
||||
echo " ~/.config/i3blocks/config"
|
||||
echo ""
|
||||
echo "2. Reload i3 configuration:"
|
||||
echo " Super+Shift+R"
|
||||
echo ""
|
||||
echo "3. ActivityWatch web interface should be available at:"
|
||||
echo " http://localhost:5600"
|
||||
echo ""
|
||||
echo "4. Check system tray for ActivityWatch icon"
|
||||
echo ""
|
||||
echo "Files created:"
|
||||
echo " ~/.config/autostart/activitywatch.desktop"
|
||||
echo " ~/.config/i3blocks/activitywatch_status.sh"
|
||||
echo " ~/.config/i3/config (modified)"
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Main execution flow
|
||||
main() {
|
||||
|
||||
@ -37,8 +37,8 @@ fi
|
||||
DUCKDNS_DOMAIN="${DUCKDNS_DOMAIN:-}"
|
||||
DUCKDNS_TOKEN="${DUCKDNS_TOKEN:-}"
|
||||
LAN_SUBNET="${LAN_SUBNET:-}"
|
||||
ALLOW_WEB="${ALLOW_WEB:-false}"
|
||||
ALLOW_DNS="${ALLOW_DNS:-false}"
|
||||
export ALLOW_WEB="${ALLOW_WEB:-false}"
|
||||
export ALLOW_DNS="${ALLOW_DNS:-false}"
|
||||
|
||||
die() {
|
||||
log_error "$1"
|
||||
@ -75,337 +75,13 @@ install_dependencies() {
|
||||
install_missing_pacman_packages wireguard-tools qrencode nftables openssh
|
||||
}
|
||||
|
||||
generate_server_keys() {
|
||||
ensure_dir "$WG_DIR"
|
||||
chmod 700 "$WG_DIR"
|
||||
if [[ -f "${WG_DIR}/server_private.key" ]]; then
|
||||
log_info "Server keypair already exists -- not rotating (would break existing peer configs)."
|
||||
return 0
|
||||
fi
|
||||
umask 077
|
||||
wg genkey | tee "${WG_DIR}/server_private.key" | wg pubkey >"${WG_DIR}/server_public.key"
|
||||
log_ok "Generated server keypair."
|
||||
}
|
||||
# shellcheck source=lib/wg_keys.sh
|
||||
source "$SCRIPT_DIR/lib/wg_keys.sh"
|
||||
# shellcheck source=lib/wg_firewall.sh
|
||||
source "$SCRIPT_DIR/lib/wg_firewall.sh"
|
||||
# shellcheck source=lib/wg_sshd.sh
|
||||
source "$SCRIPT_DIR/lib/wg_sshd.sh"
|
||||
|
||||
write_wg0_conf() {
|
||||
if [[ -f $WG_CONF ]]; then
|
||||
log_info "${WG_CONF} already exists -- leaving peers intact, not regenerating."
|
||||
return 0
|
||||
fi
|
||||
local server_private_key
|
||||
server_private_key=$(<"${WG_DIR}/server_private.key")
|
||||
umask 077
|
||||
cat >"$WG_CONF" <<EOF
|
||||
[Interface]
|
||||
Address = ${WG_SERVER_IP}/24
|
||||
ListenPort = ${WG_PORT}
|
||||
PrivateKey = ${server_private_key}
|
||||
# No PostUp/PostDown NAT: this is a host-only tunnel, not a routed VPN.
|
||||
EOF
|
||||
chmod 600 "$WG_CONF"
|
||||
log_ok "Wrote ${WG_CONF}."
|
||||
}
|
||||
|
||||
enable_wg_service() {
|
||||
enable_service "wg-quick@${WG_IFACE}"
|
||||
log_ok "wg-quick@${WG_IFACE} enabled and started."
|
||||
}
|
||||
|
||||
write_nftables_ruleset() {
|
||||
detect_lan_subnet
|
||||
if [[ -f $NFT_CONF ]]; then
|
||||
cp "$NFT_CONF" "${NFT_CONF}.bak.$(date +%s)"
|
||||
log_warn "Backed up existing ${NFT_CONF} before overwriting."
|
||||
fi
|
||||
local web_rule=""
|
||||
if [[ $ALLOW_WEB == "true" ]]; then
|
||||
web_rule=$'\n\t\ttcp dport { 80, 443 } accept'
|
||||
fi
|
||||
# DNS blocker (setup_dns_blocker.sh): serve DNS (53) -- and DHCP (67) when
|
||||
# this PC is the LAN DHCP server -- to LAN clients only. Restricted to the
|
||||
# LAN subnet so nothing is ever exposed to the internet.
|
||||
local dns_rule="" dhcp_rule=""
|
||||
if [[ $ALLOW_DNS == "true" ]]; then
|
||||
dns_rule=$'\n\t\tip saddr '"${LAN_SUBNET}"$' udp dport 53 accept'
|
||||
dns_rule+=$'\n\t\tip saddr '"${LAN_SUBNET}"$' tcp dport 53 accept'
|
||||
# DHCP clients have no IP yet (saddr 0.0.0.0 -> 255.255.255.255) and the
|
||||
# broadcast is classified INVALID by conntrack -- so this rule MUST sit
|
||||
# BEFORE 'ct state invalid drop' and match the client source port, not a
|
||||
# saddr. Link-local only: :67 broadcasts never route in from the internet.
|
||||
dhcp_rule=$'\n\t\tudp sport 68 udp dport 67 accept'
|
||||
fi
|
||||
cat >"${NFT_CONF}.new" <<EOF
|
||||
#!/usr/sbin/nft -f
|
||||
flush ruleset
|
||||
|
||||
table inet filter {
|
||||
chain input {
|
||||
type filter hook input priority 0; policy drop;
|
||||
|
||||
iif "lo" accept
|
||||
ct state established,related accept${dhcp_rule}
|
||||
ct state invalid drop
|
||||
|
||||
icmp type { destination-unreachable, time-exceeded, parameter-problem, echo-request } accept
|
||||
icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, nd-neighbor-solicit, nd-neighbor-advert, echo-request } accept
|
||||
|
||||
udp dport ${WG_PORT} accept
|
||||
|
||||
iifname "${WG_IFACE}" tcp dport 22 accept
|
||||
ip saddr ${LAN_SUBNET} tcp dport 22 accept${web_rule}${dns_rule}
|
||||
}
|
||||
chain forward {
|
||||
type filter hook forward priority 0; policy drop;
|
||||
}
|
||||
chain output {
|
||||
type filter hook output priority 0; policy accept;
|
||||
}
|
||||
}
|
||||
EOF
|
||||
}
|
||||
|
||||
verify_nftables_then_apply() {
|
||||
nft -c -f "${NFT_CONF}.new" || die "nftables ruleset failed syntax check -- not applying."
|
||||
mv "${NFT_CONF}.new" "$NFT_CONF"
|
||||
log_warn "Applying a default-drop firewall now."
|
||||
nft -f "$NFT_CONF"
|
||||
sleep 2
|
||||
if ! is_service_active sshd; then
|
||||
nft flush ruleset
|
||||
die "sshd died after applying nftables -- rolled back. Investigate before retrying."
|
||||
fi
|
||||
log_ok "nftables applied; sshd is still active."
|
||||
log_warn "Before closing this terminal, open a SECOND ssh session now and confirm it connects."
|
||||
enable_service nftables
|
||||
}
|
||||
|
||||
harden_sshd() {
|
||||
log_warn "Before disabling password auth, confirm key-based login works."
|
||||
log_warn "In ANOTHER terminal, run: ssh -o PreferredAuthentications=publickey $(get_actual_user)@localhost echo ok"
|
||||
if ! ask_yes_no "Did key-based login succeed?"; then
|
||||
die "Aborting -- run ssh-copy-id to set up key auth first, then re-run setup."
|
||||
fi
|
||||
cat >"$SSHD_DROPIN" <<'EOF'
|
||||
# Managed by setup_wireguard_ssh.sh -- drop-in, does not touch sshd_config.
|
||||
PasswordAuthentication no
|
||||
PubkeyAuthentication yes
|
||||
PermitRootLogin no
|
||||
EOF
|
||||
sshd -t || {
|
||||
rm -f "$SSHD_DROPIN"
|
||||
die "sshd config invalid after adding drop-in -- removed it."
|
||||
}
|
||||
systemctl reload sshd
|
||||
log_ok "sshd hardened: key-only auth, no root login."
|
||||
}
|
||||
|
||||
duckdns_already_updated() {
|
||||
local domain="$1" actual_user line script
|
||||
actual_user=$(get_actual_user)
|
||||
while IFS= read -r line; do
|
||||
[[ $line =~ ^[[:space:]]*(#|$) ]] && continue
|
||||
for script in $line; do
|
||||
[[ -f $script ]] || continue
|
||||
if grep -q "duckdns.org/update?domains=${domain}" "$script" 2>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
done < <(crontab -u "$actual_user" -l 2>/dev/null || true)
|
||||
return 1
|
||||
}
|
||||
|
||||
setup_duckdns() {
|
||||
if [[ -z $DUCKDNS_DOMAIN || -z $DUCKDNS_TOKEN ]]; then
|
||||
read -r -p "DuckDNS subdomain (without .duckdns.org): " DUCKDNS_DOMAIN
|
||||
read -r -p "DuckDNS token: " DUCKDNS_TOKEN
|
||||
[[ -n $DUCKDNS_DOMAIN && -n $DUCKDNS_TOKEN ]] || die "Both fields are required."
|
||||
save_config
|
||||
fi
|
||||
if duckdns_already_updated "$DUCKDNS_DOMAIN"; then
|
||||
log_info "An existing cron job already keeps ${DUCKDNS_DOMAIN}.duckdns.org updated -- not adding a duplicate."
|
||||
return 0
|
||||
fi
|
||||
ensure_dir "$DUCKDNS_DIR"
|
||||
cat >"${DUCKDNS_DIR}/duck.sh" <<EOF
|
||||
#!/bin/bash
|
||||
echo url="https://www.duckdns.org/update?domains=${DUCKDNS_DOMAIN}&token=${DUCKDNS_TOKEN}&ip=" | curl -fsS -o "${DUCKDNS_DIR}/duck.log" -K -
|
||||
EOF
|
||||
chmod 700 "${DUCKDNS_DIR}/duck.sh"
|
||||
bash "${DUCKDNS_DIR}/duck.sh"
|
||||
(
|
||||
crontab -l 2>/dev/null || true
|
||||
) | grep -vF "${DUCKDNS_DIR}/duck.sh" | {
|
||||
cat
|
||||
echo "*/5 * * * * ${DUCKDNS_DIR}/duck.sh >/dev/null 2>&1"
|
||||
} | crontab -
|
||||
log_ok "DuckDNS configured: ${DUCKDNS_DOMAIN}.duckdns.org (refreshed every 5 min via cron)."
|
||||
}
|
||||
|
||||
next_free_wg_ip() {
|
||||
local used octet
|
||||
used=$(grep -oP 'AllowedIPs\s*=\s*10\.8\.0\.\K[0-9]+' "$WG_CONF" 2>/dev/null || true)
|
||||
for ((octet = 2; octet <= 254; octet++)); do
|
||||
if ! grep -qx "$octet" <<<"$used"; then
|
||||
echo "10.8.0.${octet}"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
die "No free IPs left in ${WG_SUBNET}."
|
||||
}
|
||||
|
||||
add_phone_peer() {
|
||||
local name="${1:?usage: add-peer <name>}"
|
||||
[[ -f $WG_CONF ]] || die "Run 'setup' first -- ${WG_CONF} does not exist yet."
|
||||
[[ -n $DUCKDNS_DOMAIN ]] || die "DuckDNS domain not configured -- run 'setup' first."
|
||||
if grep -q "# peer:${name}\$" "$WG_CONF"; then
|
||||
die "A peer named '${name}' already exists in ${WG_CONF}. Use 'revoke ${name}' first to replace it."
|
||||
fi
|
||||
|
||||
ensure_dir "$WG_CLIENTS_DIR"
|
||||
chmod 700 "$WG_CLIENTS_DIR"
|
||||
|
||||
local tmpdir
|
||||
tmpdir=$(mktemp -d)
|
||||
trap 'rm -rf "$tmpdir"; trap - RETURN' RETURN
|
||||
|
||||
umask 077
|
||||
wg genkey | tee "${tmpdir}/priv" | wg pubkey >"${tmpdir}/pub"
|
||||
local client_priv client_pub server_pub peer_ip
|
||||
client_priv=$(<"${tmpdir}/priv")
|
||||
client_pub=$(<"${tmpdir}/pub")
|
||||
server_pub=$(<"${WG_DIR}/server_public.key")
|
||||
peer_ip=$(next_free_wg_ip)
|
||||
|
||||
cat >>"$WG_CONF" <<EOF
|
||||
|
||||
[Peer] # peer:${name}
|
||||
PublicKey = ${client_pub}
|
||||
AllowedIPs = ${peer_ip}/32
|
||||
EOF
|
||||
if is_service_active "wg-quick@${WG_IFACE}"; then
|
||||
wg syncconf "$WG_IFACE" <(wg-quick strip "$WG_IFACE")
|
||||
fi
|
||||
|
||||
local client_conf="${WG_CLIENTS_DIR}/${name}.conf"
|
||||
cat >"$client_conf" <<EOF
|
||||
[Interface]
|
||||
PrivateKey = ${client_priv}
|
||||
Address = ${peer_ip}/32
|
||||
# No DNS server here on purpose: AllowedIPs below is scoped to the WireGuard
|
||||
# subnet only (host-only tunnel), so a DNS server outside that subnet would
|
||||
# be unreachable through the tunnel -- Android would then have no working
|
||||
# resolver at all while the tunnel is active, breaking DNS for everything.
|
||||
|
||||
[Peer]
|
||||
PublicKey = ${server_pub}
|
||||
Endpoint = ${DUCKDNS_DOMAIN}.duckdns.org:${WG_PORT}
|
||||
AllowedIPs = ${WG_SUBNET}
|
||||
PersistentKeepalive = 25
|
||||
EOF
|
||||
chmod 600 "$client_conf"
|
||||
log_ok "Phone config written to ${client_conf}"
|
||||
log_info "Scan this QR code with the WireGuard Android app:"
|
||||
qrencode -t ansiutf8 <"$client_conf"
|
||||
}
|
||||
|
||||
revoke_peer() {
|
||||
local name="${1:?usage: revoke <name>}"
|
||||
[[ -f $WG_CONF ]] || die "${WG_CONF} does not exist."
|
||||
grep -q "# peer:${name}\$" "$WG_CONF" || die "No peer named '${name}' found."
|
||||
|
||||
local tmp
|
||||
tmp=$(mktemp)
|
||||
trap 'rm -f "$tmp"; trap - RETURN' RETURN
|
||||
awk -v marker="# peer:${name}" '
|
||||
$0 ~ ("^\\[Peer\\].*" marker "$") { skip = 1; next }
|
||||
skip && /^$/ { skip = 0; next }
|
||||
skip { next }
|
||||
{ print }
|
||||
' "$WG_CONF" >"$tmp"
|
||||
cat "$tmp" >"$WG_CONF"
|
||||
chmod 600 "$WG_CONF"
|
||||
|
||||
if is_service_active "wg-quick@${WG_IFACE}"; then
|
||||
wg syncconf "$WG_IFACE" <(wg-quick strip "$WG_IFACE")
|
||||
fi
|
||||
rm -f "${WG_CLIENTS_DIR}/${name}.conf"
|
||||
log_ok "Revoked peer '${name}'."
|
||||
}
|
||||
|
||||
print_router_instructions() {
|
||||
local lan_ip
|
||||
lan_ip=$(ip route get 1.1.1.1 2>/dev/null | awk '{print $7; exit}')
|
||||
cat <<EOF
|
||||
|
||||
=== Manual step: forward a port on your router (cannot be automated) ===
|
||||
1. Log into your router admin page (often http://192.168.1.1 or http://192.168.0.1).
|
||||
2. Find "Port Forwarding" / "Virtual Server" / "NAT" settings.
|
||||
3. Forward UDP port ${WG_PORT} -> ${lan_ip} (UDP only -- do NOT forward TCP/22).
|
||||
4. Save (and reboot the router if it requires it).
|
||||
5. Confirm your ISP gives you a real public IPv4 (not CGNAT):
|
||||
curl -s https://api.ipify.org
|
||||
getent hosts ${DUCKDNS_DOMAIN:-<your-domain>}.duckdns.org
|
||||
These two must match and must NOT be in 100.64.0.0/10 (CGNAT range).
|
||||
EOF
|
||||
}
|
||||
|
||||
print_android_instructions() {
|
||||
cat <<EOF
|
||||
|
||||
=== Manual step: install FOSS apps on your Android phone ===
|
||||
1. Install F-Droid (https://f-droid.org/) if you don't have it.
|
||||
2. From F-Droid, install "WireGuard" (official app, org.wireguard.android).
|
||||
3. From F-Droid, install "Termux" (then run: pkg install openssh) or "ConnectBot".
|
||||
4. Open WireGuard -> "+" -> "Scan from QR code" -> scan the code printed above.
|
||||
5. Toggle the tunnel on.
|
||||
6. From Termux/ConnectBot: ssh $(get_actual_user)@${WG_SERVER_IP}
|
||||
EOF
|
||||
}
|
||||
|
||||
allow_web() {
|
||||
ALLOW_WEB=true
|
||||
save_config
|
||||
write_nftables_ruleset
|
||||
verify_nftables_then_apply
|
||||
log_ok "Opened tcp/80 and tcp/443 in the input chain (persisted -- future 'setup' re-runs keep this rule)."
|
||||
}
|
||||
|
||||
allow_dns() {
|
||||
ALLOW_DNS=true
|
||||
save_config
|
||||
write_nftables_ruleset
|
||||
verify_nftables_then_apply
|
||||
log_ok "Opened udp/tcp 53 from ${LAN_SUBNET:-the LAN} in the input chain (persisted -- future 'setup' re-runs keep this rule)."
|
||||
}
|
||||
|
||||
status_cmd() {
|
||||
echo "=== WireGuard ==="
|
||||
wg show 2>/dev/null || echo "(interface not up)"
|
||||
echo
|
||||
echo "=== wg-quick@${WG_IFACE} service ==="
|
||||
systemctl status "wg-quick@${WG_IFACE}" --no-pager 2>/dev/null || echo "(not installed)"
|
||||
echo
|
||||
echo "=== nftables (input chain) ==="
|
||||
nft list ruleset 2>/dev/null | sed -n '/chain input/,/}/p' || echo "(nftables not active)"
|
||||
echo
|
||||
echo "=== sshd password auth ==="
|
||||
sshd -T 2>/dev/null | grep -i passwordauthentication || echo "(could not query sshd)"
|
||||
}
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: $0 <command> [args]
|
||||
|
||||
Commands:
|
||||
setup Full first-time setup (WireGuard, firewall, sshd, DuckDNS).
|
||||
add-peer <name> Provision a new phone/laptop and print its QR code.
|
||||
allow-web Open tcp/80 and tcp/443 in the firewall (for a web server on this host).
|
||||
allow-dns Open udp/tcp 53 from the LAN in the firewall (for the DNS blocker on this host).
|
||||
status Show WireGuard/firewall/sshd status.
|
||||
revoke <name> Remove a peer.
|
||||
help Show this message.
|
||||
EOF
|
||||
}
|
||||
|
||||
main() {
|
||||
local cmd="${1:-help}"
|
||||
|
||||
126
linux_configuration/scripts/single_use/fixes/lib/arch_cpu.sh
Executable file
126
linux_configuration/scripts/single_use/fixes/lib/arch_cpu.sh
Executable file
@ -0,0 +1,126 @@
|
||||
#!/bin/bash
|
||||
# CPU governor and IO scheduler tweaks.
|
||||
#
|
||||
# Sourced by optimize_arch_desktop.sh; split out to keep it under the 250-line cap.
|
||||
# Sourced rather than run, so it inherits the caller's strict mode and
|
||||
# the helper functions and variables defined above the source line.
|
||||
|
||||
# ===================================================================
|
||||
# 1. CPU Governor → performance
|
||||
# ===================================================================
|
||||
tweak_cpu_governor() {
|
||||
local gov_files
|
||||
gov_files=$(find /sys/devices/system/cpu -maxdepth 3 -name scaling_governor 2>/dev/null || true)
|
||||
|
||||
if [[ -z $gov_files ]]; then
|
||||
log_warn "No CPU governor sysfs files found — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check current state
|
||||
local all_performance=true
|
||||
local f
|
||||
for f in $gov_files; do
|
||||
if [[ $(cat "$f") != "performance" ]]; then
|
||||
all_performance=false
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $all_performance == "true" ]]; then
|
||||
log_ok "All CPU cores already on 'performance' governor — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
for f in $gov_files; do
|
||||
echo "performance" >"$f"
|
||||
done
|
||||
|
||||
# Make it persistent via a sysctl-style drop-in using udev rule
|
||||
local udev_rule="/etc/udev/rules.d/60-cpu-governor-performance.rules"
|
||||
if [[ ! -f $udev_rule ]]; then
|
||||
cat >"$udev_rule" <<'UDEVEOF'
|
||||
# Set CPU governor to performance on all cores at boot
|
||||
SUBSYSTEM=="module", DEVPATH=="*/cpu/*", ATTR{scaling_governor}=="*", ATTR{scaling_governor}="performance"
|
||||
UDEVEOF
|
||||
fi
|
||||
|
||||
# Also install cpupower hook as a more reliable persistence method
|
||||
local cpupower_conf="/etc/default/cpupower"
|
||||
if has_cmd cpupower; then
|
||||
if [[ ! -f $cpupower_conf ]] || ! grep -q "^governor='performance'" "$cpupower_conf" 2>/dev/null; then
|
||||
mkdir -p "$(dirname "$cpupower_conf")"
|
||||
cat >"$cpupower_conf" <<'CPUEOF'
|
||||
# /etc/default/cpupower — managed by optimize_arch_desktop.sh
|
||||
governor='performance'
|
||||
CPUEOF
|
||||
systemctl enable cpupower.service 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 2. I/O Scheduler per drive type
|
||||
# ===================================================================
|
||||
tweak_io_scheduler() {
|
||||
local changed=false
|
||||
|
||||
local block_dev
|
||||
for block_dev in /sys/block/sd* /sys/block/nvme* /sys/block/vd*; do
|
||||
[[ -d $block_dev ]] || continue
|
||||
local sched_file="$block_dev/queue/scheduler"
|
||||
[[ -f $sched_file ]] || continue
|
||||
|
||||
local dev_name
|
||||
dev_name=$(basename "$block_dev")
|
||||
local rotational
|
||||
rotational=$(cat "$block_dev/queue/rotational" 2>/dev/null || echo 1)
|
||||
local current
|
||||
current=$(sed 's/.*\[\(.*\)\].*/\1/' "$sched_file" 2>/dev/null || true)
|
||||
|
||||
local target
|
||||
if [[ $dev_name == nvme* ]]; then
|
||||
target="none"
|
||||
elif [[ $rotational -eq 0 ]]; then
|
||||
target="mq-deadline"
|
||||
else
|
||||
target="bfq"
|
||||
fi
|
||||
|
||||
if [[ $current == "$target" ]]; then
|
||||
log_ok "$dev_name: already using '$target' scheduler."
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "$target" >"$sched_file" 2>/dev/null || true
|
||||
log_info "$dev_name: scheduler changed from '$current' to '$target'."
|
||||
changed=true
|
||||
done
|
||||
|
||||
# Persist via udev rule
|
||||
local udev_rule="/etc/udev/rules.d/60-io-scheduler.rules"
|
||||
if [[ ! -f $udev_rule ]]; then
|
||||
cat >"$udev_rule" <<'IOEOF'
|
||||
# NVMe: no scheduler (multi-queue hardware handles it)
|
||||
ACTION=="add|change", KERNEL=="nvme[0-9]*", ATTR{queue/scheduler}="none"
|
||||
# SATA SSD: mq-deadline (low latency)
|
||||
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="mq-deadline"
|
||||
# HDD: BFQ (fair bandwidth allocation)
|
||||
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="1", ATTR{queue/scheduler}="bfq"
|
||||
IOEOF
|
||||
fi
|
||||
|
||||
if [[ $changed == "false" ]]; then
|
||||
log_ok "All I/O schedulers already optimal."
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# Apply all tweaks
|
||||
# ===================================================================
|
||||
202
linux_configuration/scripts/single_use/fixes/lib/arch_hardware.sh
Executable file
202
linux_configuration/scripts/single_use/fixes/lib/arch_hardware.sh
Executable file
@ -0,0 +1,202 @@
|
||||
#!/bin/bash
|
||||
# fstrim, NVIDIA and CPU mitigation tweaks.
|
||||
#
|
||||
# Sourced by optimize_arch_desktop.sh; split out to keep it under the 250-line
|
||||
# cap. Sourced rather than run, so it inherits the caller's strict mode
|
||||
# and the variables defined above the source line.
|
||||
|
||||
# ===================================================================
|
||||
# 5. fstrim timer
|
||||
# ===================================================================
|
||||
tweak_fstrim() {
|
||||
if systemctl is-enabled fstrim.timer >/dev/null 2>&1; then
|
||||
log_ok "fstrim.timer already enabled — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
systemctl enable --now fstrim.timer
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 6. NVIDIA GPU — max performance
|
||||
# ===================================================================
|
||||
tweak_nvidia_gpu() {
|
||||
if ! has_cmd nvidia-smi; then
|
||||
log_info "nvidia-smi not found — skipping GPU tuning."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Enable persistence mode (keeps driver loaded, faster app launches)
|
||||
local persist_status
|
||||
persist_status=$(nvidia-smi --query-gpu=persistence_mode --format=csv,noheader 2>/dev/null | head -n 1 | xargs || true)
|
||||
if [[ $persist_status != "Enabled" ]]; then
|
||||
nvidia-smi -pm 1 >/dev/null 2>&1 || true
|
||||
log_info "NVIDIA persistence mode enabled."
|
||||
else
|
||||
log_ok "NVIDIA persistence mode already enabled."
|
||||
fi
|
||||
|
||||
# Set power management to prefer maximum performance
|
||||
# PowerMizerMode: 1 = prefer max perf
|
||||
nvidia-smi -gps 0 >/dev/null 2>&1 || true
|
||||
|
||||
# Persist via systemd service
|
||||
local service_file="/etc/systemd/system/nvidia-performance.service"
|
||||
if [[ ! -f $service_file ]]; then
|
||||
cat >"$service_file" <<'NVSVC'
|
||||
[Unit]
|
||||
Description=Set NVIDIA GPU to max performance mode
|
||||
After=nvidia-persistenced.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/nvidia-smi -pm 1
|
||||
RemainAfterExit=yes
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
NVSVC
|
||||
systemctl daemon-reload
|
||||
systemctl enable nvidia-performance.service 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# Ensure nvidia-persistenced is enabled
|
||||
if has_cmd nvidia-persistenced; then
|
||||
systemctl enable nvidia-persistenced.service 2>/dev/null || true
|
||||
if ! systemctl is-active nvidia-persistenced.service >/dev/null 2>&1; then
|
||||
systemctl start nvidia-persistenced.service 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 7. [AGGRESSIVE] Disable CPU vulnerability mitigations
|
||||
# ===================================================================
|
||||
tweak_mitigations() {
|
||||
if [[ $AGGRESSIVE != "true" ]]; then
|
||||
log_info "Skipping CPU mitigation disable (use --aggressive to enable)."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Detect boot loader
|
||||
local boot_method=""
|
||||
if [[ -d /boot/loader/entries ]]; then
|
||||
boot_method="systemd-boot"
|
||||
elif [[ -f /etc/default/grub ]]; then
|
||||
boot_method="grub"
|
||||
else
|
||||
log_warn "Could not detect boot loader — skipping mitigation tweak."
|
||||
log_info "Manually add 'mitigations=off' to your kernel command line for extra speed."
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [[ $boot_method == "systemd-boot" ]]; then
|
||||
local entry
|
||||
entry=$(find /boot/loader/entries -name '*.conf' -print -quit 2>/dev/null || true)
|
||||
if [[ -n $entry ]]; then
|
||||
if grep -q 'mitigations=off' "$entry" 2>/dev/null; then
|
||||
log_ok "mitigations=off already set in systemd-boot — skipping."
|
||||
return 0
|
||||
fi
|
||||
# Append to the options line
|
||||
sed -i '/^options / s/$/ mitigations=off/' "$entry"
|
||||
log_warn "Added mitigations=off to $entry. REBOOT REQUIRED."
|
||||
log_warn "This trades security for ~5-15% performance. Only for isolated desktops."
|
||||
fi
|
||||
elif [[ $boot_method == "grub" ]]; then
|
||||
if grep -q 'mitigations=off' /etc/default/grub 2>/dev/null; then
|
||||
log_ok "mitigations=off already set in GRUB — skipping."
|
||||
return 0
|
||||
fi
|
||||
sed -i 's/^GRUB_CMDLINE_LINUX_DEFAULT="\(.*\)"/GRUB_CMDLINE_LINUX_DEFAULT="\1 mitigations=off"/' /etc/default/grub
|
||||
grub-mkconfig -o /boot/grub/grub.cfg
|
||||
log_warn "Added mitigations=off to GRUB config. REBOOT REQUIRED."
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 8. Disable NetworkManager-wait-online
|
||||
# ===================================================================
|
||||
tweak_nm_wait_online() {
|
||||
if ! systemctl is-enabled NetworkManager-wait-online.service >/dev/null 2>&1; then
|
||||
log_ok "NetworkManager-wait-online already disabled — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
systemctl disable NetworkManager-wait-online.service
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 9. Journal vacuum + permanent cap
|
||||
# ===================================================================
|
||||
tweak_journal() {
|
||||
local usage_line
|
||||
usage_line=$(journalctl --disk-usage 2>/dev/null || true)
|
||||
|
||||
local needs_vacuum=false
|
||||
if [[ $usage_line =~ ([0-9]+\.?[0-9]*)\ G ]]; then
|
||||
needs_vacuum=true
|
||||
fi
|
||||
|
||||
if [[ $needs_vacuum == "true" ]]; then
|
||||
journalctl --vacuum-size=300M
|
||||
else
|
||||
log_ok "Journal already under 1GiB."
|
||||
fi
|
||||
|
||||
local dropin_dir="/etc/systemd/journald.conf.d"
|
||||
local dropin_file="$dropin_dir/size-limit.conf"
|
||||
|
||||
if [[ -f $dropin_file ]] && grep -q 'SystemMaxUse=300M' "$dropin_file"; then
|
||||
log_ok "Journal size cap already configured."
|
||||
else
|
||||
mkdir -p "$dropin_dir"
|
||||
cat >"$dropin_file" <<'JOURNALEOF'
|
||||
[Journal]
|
||||
SystemMaxUse=300M
|
||||
JOURNALEOF
|
||||
systemctl restart systemd-journald
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 10. ananicy-cpp — automatic process nice/ionice/scheduler tuning
|
||||
# ===================================================================
|
||||
tweak_ananicy() {
|
||||
# ananicy-cpp is the C++ rewrite, available in the AUR via ananicy-cpp
|
||||
if systemctl is-enabled ananicy-cpp.service >/dev/null 2>&1; then
|
||||
log_ok "ananicy-cpp is already enabled — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
if pacman -Qi ananicy-cpp >/dev/null 2>&1; then
|
||||
systemctl enable --now ananicy-cpp.service
|
||||
log_info "Enabled ananicy-cpp.service."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check for the original ananicy
|
||||
if pacman -Qi ananicy >/dev/null 2>&1; then
|
||||
if ! systemctl is-enabled ananicy.service >/dev/null 2>&1; then
|
||||
systemctl enable --now ananicy.service
|
||||
log_info "Enabled ananicy.service."
|
||||
else
|
||||
log_ok "ananicy is already enabled."
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
|
||||
log_info "ananicy-cpp is not installed."
|
||||
log_info "Install from AUR for automatic per-process priority tuning:"
|
||||
log_info " yay -S ananicy-cpp cachyos-ananicy-rules-git"
|
||||
|
||||
return 0
|
||||
}
|
||||
122
linux_configuration/scripts/single_use/fixes/lib/arch_sysctl.sh
Executable file
122
linux_configuration/scripts/single_use/fixes/lib/arch_sysctl.sh
Executable file
@ -0,0 +1,122 @@
|
||||
#!/bin/bash
|
||||
# VM and network sysctl tuning.
|
||||
#
|
||||
# Sourced by optimize_arch_desktop.sh; split out to keep it under the 250-line
|
||||
# cap. Sourced rather than run, so it inherits the caller's strict mode
|
||||
# and the variables defined above the source line.
|
||||
|
||||
# ===================================================================
|
||||
# 3. Memory & swap tuning via sysctl
|
||||
# ===================================================================
|
||||
tweak_vm_sysctl() {
|
||||
local dropin="/etc/sysctl.d/90-desktop-performance.conf"
|
||||
|
||||
# Desktop workloads: low swappiness, aggressive VFS caching, tuned dirty ratios
|
||||
local -A params=(
|
||||
["vm.swappiness"]="10"
|
||||
["vm.vfs_cache_pressure"]="50"
|
||||
["vm.dirty_ratio"]="15"
|
||||
["vm.dirty_background_ratio"]="5"
|
||||
["vm.dirty_writeback_centisecs"]="1500"
|
||||
["vm.page-cluster"]="0"
|
||||
)
|
||||
|
||||
local needs_update=false
|
||||
local key
|
||||
for key in "${!params[@]}"; do
|
||||
local current
|
||||
current=$(sysctl -n "$key" 2>/dev/null || true)
|
||||
if [[ $current != "${params[$key]}" ]]; then
|
||||
needs_update=true
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $needs_update == "false" && -f $dropin ]]; then
|
||||
log_ok "VM sysctl parameters already tuned — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
cat >"$dropin" <<'VMEOF'
|
||||
# Desktop performance tuning — managed by optimize_arch_desktop.sh
|
||||
#
|
||||
# vm.swappiness=10 — prefer keeping data in RAM over swapping
|
||||
# vm.vfs_cache_pressure=50 — favor keeping inode/dentry caches (speeds up file operations)
|
||||
# vm.dirty_ratio=15 — allow up to 15% RAM dirty before synchronous writeback
|
||||
# vm.dirty_background_ratio=5 — start async writeback at 5% dirty
|
||||
# vm.dirty_writeback_centisecs=1500 — flush dirty pages every 15s (less I/O churn)
|
||||
# vm.page-cluster=0 — read one page at a time from swap (reduces latency on SSD)
|
||||
vm.swappiness = 10
|
||||
vm.vfs_cache_pressure = 50
|
||||
vm.dirty_ratio = 15
|
||||
vm.dirty_background_ratio = 5
|
||||
vm.dirty_writeback_centisecs = 1500
|
||||
vm.page-cluster = 0
|
||||
VMEOF
|
||||
|
||||
sysctl --system >/dev/null 2>&1
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 4. Network: TCP BBR + fastopen + buffer tuning
|
||||
# ===================================================================
|
||||
tweak_network_sysctl() {
|
||||
local dropin="/etc/sysctl.d/91-desktop-network.conf"
|
||||
|
||||
# Check if BBR module is available
|
||||
if ! modprobe tcp_bbr 2>/dev/null; then
|
||||
log_warn "tcp_bbr kernel module unavailable — skipping network tuning."
|
||||
return 0
|
||||
fi
|
||||
|
||||
local -A params=(
|
||||
["net.core.default_qdisc"]="fq"
|
||||
["net.ipv4.tcp_congestion_control"]="bbr"
|
||||
["net.ipv4.tcp_fastopen"]="3"
|
||||
["net.core.rmem_max"]="16777216"
|
||||
["net.core.wmem_max"]="16777216"
|
||||
["net.ipv4.tcp_rmem"]="4096 1048576 16777216"
|
||||
["net.ipv4.tcp_wmem"]="4096 1048576 16777216"
|
||||
["net.ipv4.tcp_mtu_probing"]="1"
|
||||
)
|
||||
|
||||
local needs_update=false
|
||||
local key
|
||||
for key in "${!params[@]}"; do
|
||||
local current
|
||||
current=$(sysctl -n "$key" 2>/dev/null || true)
|
||||
# Normalize whitespace for comparison (kernel uses tabs)
|
||||
current=$(echo "$current" | xargs)
|
||||
local expected
|
||||
expected=$(echo "${params[$key]}" | xargs)
|
||||
if [[ $current != "$expected" ]]; then
|
||||
needs_update=true
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $needs_update == "false" && -f $dropin ]]; then
|
||||
log_ok "Network sysctl parameters already tuned — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
cat >"$dropin" <<'NETEOF'
|
||||
# Network performance tuning — managed by optimize_arch_desktop.sh
|
||||
#
|
||||
# BBR congestion control — better throughput and lower latency than cubic
|
||||
# TCP fastopen — saves one RTT on repeated connections (both client and server)
|
||||
# Larger buffers — helps on high-bandwidth or high-latency links
|
||||
net.core.default_qdisc = fq
|
||||
net.ipv4.tcp_congestion_control = bbr
|
||||
net.ipv4.tcp_fastopen = 3
|
||||
net.core.rmem_max = 16777216
|
||||
net.core.wmem_max = 16777216
|
||||
net.ipv4.tcp_rmem = 4096 1048576 16777216
|
||||
net.ipv4.tcp_wmem = 4096 1048576 16777216
|
||||
net.ipv4.tcp_mtu_probing = 1
|
||||
NETEOF
|
||||
|
||||
sysctl --system >/dev/null 2>&1
|
||||
return 0
|
||||
}
|
||||
@ -113,435 +113,13 @@ apply_tweak() {
|
||||
fi
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 1. CPU Governor → performance
|
||||
# ===================================================================
|
||||
tweak_cpu_governor() {
|
||||
local gov_files
|
||||
gov_files=$(find /sys/devices/system/cpu -maxdepth 3 -name scaling_governor 2>/dev/null || true)
|
||||
# shellcheck source=lib/arch_cpu.sh
|
||||
source "$SCRIPT_DIR/lib/arch_cpu.sh"
|
||||
# shellcheck source=lib/arch_sysctl.sh
|
||||
source "$SCRIPT_DIR/lib/arch_sysctl.sh"
|
||||
# shellcheck source=lib/arch_hardware.sh
|
||||
source "$SCRIPT_DIR/lib/arch_hardware.sh"
|
||||
|
||||
if [[ -z $gov_files ]]; then
|
||||
log_warn "No CPU governor sysfs files found — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check current state
|
||||
local all_performance=true
|
||||
local f
|
||||
for f in $gov_files; do
|
||||
if [[ $(cat "$f") != "performance" ]]; then
|
||||
all_performance=false
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $all_performance == "true" ]]; then
|
||||
log_ok "All CPU cores already on 'performance' governor — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
for f in $gov_files; do
|
||||
echo "performance" >"$f"
|
||||
done
|
||||
|
||||
# Make it persistent via a sysctl-style drop-in using udev rule
|
||||
local udev_rule="/etc/udev/rules.d/60-cpu-governor-performance.rules"
|
||||
if [[ ! -f $udev_rule ]]; then
|
||||
cat >"$udev_rule" <<'UDEVEOF'
|
||||
# Set CPU governor to performance on all cores at boot
|
||||
SUBSYSTEM=="module", DEVPATH=="*/cpu/*", ATTR{scaling_governor}=="*", ATTR{scaling_governor}="performance"
|
||||
UDEVEOF
|
||||
fi
|
||||
|
||||
# Also install cpupower hook as a more reliable persistence method
|
||||
local cpupower_conf="/etc/default/cpupower"
|
||||
if has_cmd cpupower; then
|
||||
if [[ ! -f $cpupower_conf ]] || ! grep -q "^governor='performance'" "$cpupower_conf" 2>/dev/null; then
|
||||
mkdir -p "$(dirname "$cpupower_conf")"
|
||||
cat >"$cpupower_conf" <<'CPUEOF'
|
||||
# /etc/default/cpupower — managed by optimize_arch_desktop.sh
|
||||
governor='performance'
|
||||
CPUEOF
|
||||
systemctl enable cpupower.service 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 2. I/O Scheduler per drive type
|
||||
# ===================================================================
|
||||
tweak_io_scheduler() {
|
||||
local changed=false
|
||||
|
||||
local block_dev
|
||||
for block_dev in /sys/block/sd* /sys/block/nvme* /sys/block/vd*; do
|
||||
[[ -d $block_dev ]] || continue
|
||||
local sched_file="$block_dev/queue/scheduler"
|
||||
[[ -f $sched_file ]] || continue
|
||||
|
||||
local dev_name
|
||||
dev_name=$(basename "$block_dev")
|
||||
local rotational
|
||||
rotational=$(cat "$block_dev/queue/rotational" 2>/dev/null || echo 1)
|
||||
local current
|
||||
current=$(sed 's/.*\[\(.*\)\].*/\1/' "$sched_file" 2>/dev/null || true)
|
||||
|
||||
local target
|
||||
if [[ $dev_name == nvme* ]]; then
|
||||
target="none"
|
||||
elif [[ $rotational -eq 0 ]]; then
|
||||
target="mq-deadline"
|
||||
else
|
||||
target="bfq"
|
||||
fi
|
||||
|
||||
if [[ $current == "$target" ]]; then
|
||||
log_ok "$dev_name: already using '$target' scheduler."
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "$target" >"$sched_file" 2>/dev/null || true
|
||||
log_info "$dev_name: scheduler changed from '$current' to '$target'."
|
||||
changed=true
|
||||
done
|
||||
|
||||
# Persist via udev rule
|
||||
local udev_rule="/etc/udev/rules.d/60-io-scheduler.rules"
|
||||
if [[ ! -f $udev_rule ]]; then
|
||||
cat >"$udev_rule" <<'IOEOF'
|
||||
# NVMe: no scheduler (multi-queue hardware handles it)
|
||||
ACTION=="add|change", KERNEL=="nvme[0-9]*", ATTR{queue/scheduler}="none"
|
||||
# SATA SSD: mq-deadline (low latency)
|
||||
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="mq-deadline"
|
||||
# HDD: BFQ (fair bandwidth allocation)
|
||||
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="1", ATTR{queue/scheduler}="bfq"
|
||||
IOEOF
|
||||
fi
|
||||
|
||||
if [[ $changed == "false" ]]; then
|
||||
log_ok "All I/O schedulers already optimal."
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 3. Memory & swap tuning via sysctl
|
||||
# ===================================================================
|
||||
tweak_vm_sysctl() {
|
||||
local dropin="/etc/sysctl.d/90-desktop-performance.conf"
|
||||
|
||||
# Desktop workloads: low swappiness, aggressive VFS caching, tuned dirty ratios
|
||||
local -A params=(
|
||||
["vm.swappiness"]="10"
|
||||
["vm.vfs_cache_pressure"]="50"
|
||||
["vm.dirty_ratio"]="15"
|
||||
["vm.dirty_background_ratio"]="5"
|
||||
["vm.dirty_writeback_centisecs"]="1500"
|
||||
["vm.page-cluster"]="0"
|
||||
)
|
||||
|
||||
local needs_update=false
|
||||
local key
|
||||
for key in "${!params[@]}"; do
|
||||
local current
|
||||
current=$(sysctl -n "$key" 2>/dev/null || true)
|
||||
if [[ $current != "${params[$key]}" ]]; then
|
||||
needs_update=true
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $needs_update == "false" && -f $dropin ]]; then
|
||||
log_ok "VM sysctl parameters already tuned — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
cat >"$dropin" <<'VMEOF'
|
||||
# Desktop performance tuning — managed by optimize_arch_desktop.sh
|
||||
#
|
||||
# vm.swappiness=10 — prefer keeping data in RAM over swapping
|
||||
# vm.vfs_cache_pressure=50 — favor keeping inode/dentry caches (speeds up file operations)
|
||||
# vm.dirty_ratio=15 — allow up to 15% RAM dirty before synchronous writeback
|
||||
# vm.dirty_background_ratio=5 — start async writeback at 5% dirty
|
||||
# vm.dirty_writeback_centisecs=1500 — flush dirty pages every 15s (less I/O churn)
|
||||
# vm.page-cluster=0 — read one page at a time from swap (reduces latency on SSD)
|
||||
vm.swappiness = 10
|
||||
vm.vfs_cache_pressure = 50
|
||||
vm.dirty_ratio = 15
|
||||
vm.dirty_background_ratio = 5
|
||||
vm.dirty_writeback_centisecs = 1500
|
||||
vm.page-cluster = 0
|
||||
VMEOF
|
||||
|
||||
sysctl --system >/dev/null 2>&1
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 4. Network: TCP BBR + fastopen + buffer tuning
|
||||
# ===================================================================
|
||||
tweak_network_sysctl() {
|
||||
local dropin="/etc/sysctl.d/91-desktop-network.conf"
|
||||
|
||||
# Check if BBR module is available
|
||||
if ! modprobe tcp_bbr 2>/dev/null; then
|
||||
log_warn "tcp_bbr kernel module unavailable — skipping network tuning."
|
||||
return 0
|
||||
fi
|
||||
|
||||
local -A params=(
|
||||
["net.core.default_qdisc"]="fq"
|
||||
["net.ipv4.tcp_congestion_control"]="bbr"
|
||||
["net.ipv4.tcp_fastopen"]="3"
|
||||
["net.core.rmem_max"]="16777216"
|
||||
["net.core.wmem_max"]="16777216"
|
||||
["net.ipv4.tcp_rmem"]="4096 1048576 16777216"
|
||||
["net.ipv4.tcp_wmem"]="4096 1048576 16777216"
|
||||
["net.ipv4.tcp_mtu_probing"]="1"
|
||||
)
|
||||
|
||||
local needs_update=false
|
||||
local key
|
||||
for key in "${!params[@]}"; do
|
||||
local current
|
||||
current=$(sysctl -n "$key" 2>/dev/null || true)
|
||||
# Normalize whitespace for comparison (kernel uses tabs)
|
||||
current=$(echo "$current" | xargs)
|
||||
local expected
|
||||
expected=$(echo "${params[$key]}" | xargs)
|
||||
if [[ $current != "$expected" ]]; then
|
||||
needs_update=true
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $needs_update == "false" && -f $dropin ]]; then
|
||||
log_ok "Network sysctl parameters already tuned — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
cat >"$dropin" <<'NETEOF'
|
||||
# Network performance tuning — managed by optimize_arch_desktop.sh
|
||||
#
|
||||
# BBR congestion control — better throughput and lower latency than cubic
|
||||
# TCP fastopen — saves one RTT on repeated connections (both client and server)
|
||||
# Larger buffers — helps on high-bandwidth or high-latency links
|
||||
net.core.default_qdisc = fq
|
||||
net.ipv4.tcp_congestion_control = bbr
|
||||
net.ipv4.tcp_fastopen = 3
|
||||
net.core.rmem_max = 16777216
|
||||
net.core.wmem_max = 16777216
|
||||
net.ipv4.tcp_rmem = 4096 1048576 16777216
|
||||
net.ipv4.tcp_wmem = 4096 1048576 16777216
|
||||
net.ipv4.tcp_mtu_probing = 1
|
||||
NETEOF
|
||||
|
||||
sysctl --system >/dev/null 2>&1
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 5. fstrim timer
|
||||
# ===================================================================
|
||||
tweak_fstrim() {
|
||||
if systemctl is-enabled fstrim.timer >/dev/null 2>&1; then
|
||||
log_ok "fstrim.timer already enabled — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
systemctl enable --now fstrim.timer
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 6. NVIDIA GPU — max performance
|
||||
# ===================================================================
|
||||
tweak_nvidia_gpu() {
|
||||
if ! has_cmd nvidia-smi; then
|
||||
log_info "nvidia-smi not found — skipping GPU tuning."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Enable persistence mode (keeps driver loaded, faster app launches)
|
||||
local persist_status
|
||||
persist_status=$(nvidia-smi --query-gpu=persistence_mode --format=csv,noheader 2>/dev/null | head -n 1 | xargs || true)
|
||||
if [[ $persist_status != "Enabled" ]]; then
|
||||
nvidia-smi -pm 1 >/dev/null 2>&1 || true
|
||||
log_info "NVIDIA persistence mode enabled."
|
||||
else
|
||||
log_ok "NVIDIA persistence mode already enabled."
|
||||
fi
|
||||
|
||||
# Set power management to prefer maximum performance
|
||||
# PowerMizerMode: 1 = prefer max perf
|
||||
nvidia-smi -gps 0 >/dev/null 2>&1 || true
|
||||
|
||||
# Persist via systemd service
|
||||
local service_file="/etc/systemd/system/nvidia-performance.service"
|
||||
if [[ ! -f $service_file ]]; then
|
||||
cat >"$service_file" <<'NVSVC'
|
||||
[Unit]
|
||||
Description=Set NVIDIA GPU to max performance mode
|
||||
After=nvidia-persistenced.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/nvidia-smi -pm 1
|
||||
RemainAfterExit=yes
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
NVSVC
|
||||
systemctl daemon-reload
|
||||
systemctl enable nvidia-performance.service 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# Ensure nvidia-persistenced is enabled
|
||||
if has_cmd nvidia-persistenced; then
|
||||
systemctl enable nvidia-persistenced.service 2>/dev/null || true
|
||||
if ! systemctl is-active nvidia-persistenced.service >/dev/null 2>&1; then
|
||||
systemctl start nvidia-persistenced.service 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 7. [AGGRESSIVE] Disable CPU vulnerability mitigations
|
||||
# ===================================================================
|
||||
tweak_mitigations() {
|
||||
if [[ $AGGRESSIVE != "true" ]]; then
|
||||
log_info "Skipping CPU mitigation disable (use --aggressive to enable)."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Detect boot loader
|
||||
local boot_method=""
|
||||
if [[ -d /boot/loader/entries ]]; then
|
||||
boot_method="systemd-boot"
|
||||
elif [[ -f /etc/default/grub ]]; then
|
||||
boot_method="grub"
|
||||
else
|
||||
log_warn "Could not detect boot loader — skipping mitigation tweak."
|
||||
log_info "Manually add 'mitigations=off' to your kernel command line for extra speed."
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [[ $boot_method == "systemd-boot" ]]; then
|
||||
local entry
|
||||
entry=$(find /boot/loader/entries -name '*.conf' -print -quit 2>/dev/null || true)
|
||||
if [[ -n $entry ]]; then
|
||||
if grep -q 'mitigations=off' "$entry" 2>/dev/null; then
|
||||
log_ok "mitigations=off already set in systemd-boot — skipping."
|
||||
return 0
|
||||
fi
|
||||
# Append to the options line
|
||||
sed -i '/^options / s/$/ mitigations=off/' "$entry"
|
||||
log_warn "Added mitigations=off to $entry. REBOOT REQUIRED."
|
||||
log_warn "This trades security for ~5-15% performance. Only for isolated desktops."
|
||||
fi
|
||||
elif [[ $boot_method == "grub" ]]; then
|
||||
if grep -q 'mitigations=off' /etc/default/grub 2>/dev/null; then
|
||||
log_ok "mitigations=off already set in GRUB — skipping."
|
||||
return 0
|
||||
fi
|
||||
sed -i 's/^GRUB_CMDLINE_LINUX_DEFAULT="\(.*\)"/GRUB_CMDLINE_LINUX_DEFAULT="\1 mitigations=off"/' /etc/default/grub
|
||||
grub-mkconfig -o /boot/grub/grub.cfg
|
||||
log_warn "Added mitigations=off to GRUB config. REBOOT REQUIRED."
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 8. Disable NetworkManager-wait-online
|
||||
# ===================================================================
|
||||
tweak_nm_wait_online() {
|
||||
if ! systemctl is-enabled NetworkManager-wait-online.service >/dev/null 2>&1; then
|
||||
log_ok "NetworkManager-wait-online already disabled — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
systemctl disable NetworkManager-wait-online.service
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 9. Journal vacuum + permanent cap
|
||||
# ===================================================================
|
||||
tweak_journal() {
|
||||
local usage_line
|
||||
usage_line=$(journalctl --disk-usage 2>/dev/null || true)
|
||||
|
||||
local needs_vacuum=false
|
||||
if [[ $usage_line =~ ([0-9]+\.?[0-9]*)\ G ]]; then
|
||||
needs_vacuum=true
|
||||
fi
|
||||
|
||||
if [[ $needs_vacuum == "true" ]]; then
|
||||
journalctl --vacuum-size=300M
|
||||
else
|
||||
log_ok "Journal already under 1GiB."
|
||||
fi
|
||||
|
||||
local dropin_dir="/etc/systemd/journald.conf.d"
|
||||
local dropin_file="$dropin_dir/size-limit.conf"
|
||||
|
||||
if [[ -f $dropin_file ]] && grep -q 'SystemMaxUse=300M' "$dropin_file"; then
|
||||
log_ok "Journal size cap already configured."
|
||||
else
|
||||
mkdir -p "$dropin_dir"
|
||||
cat >"$dropin_file" <<'JOURNALEOF'
|
||||
[Journal]
|
||||
SystemMaxUse=300M
|
||||
JOURNALEOF
|
||||
systemctl restart systemd-journald
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# 10. ananicy-cpp — automatic process nice/ionice/scheduler tuning
|
||||
# ===================================================================
|
||||
tweak_ananicy() {
|
||||
# ananicy-cpp is the C++ rewrite, available in the AUR via ananicy-cpp
|
||||
if systemctl is-enabled ananicy-cpp.service >/dev/null 2>&1; then
|
||||
log_ok "ananicy-cpp is already enabled — skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
if pacman -Qi ananicy-cpp >/dev/null 2>&1; then
|
||||
systemctl enable --now ananicy-cpp.service
|
||||
log_info "Enabled ananicy-cpp.service."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check for the original ananicy
|
||||
if pacman -Qi ananicy >/dev/null 2>&1; then
|
||||
if ! systemctl is-enabled ananicy.service >/dev/null 2>&1; then
|
||||
systemctl enable --now ananicy.service
|
||||
log_info "Enabled ananicy.service."
|
||||
else
|
||||
log_ok "ananicy is already enabled."
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
|
||||
log_info "ananicy-cpp is not installed."
|
||||
log_info "Install from AUR for automatic per-process priority tuning:"
|
||||
log_info " yay -S ananicy-cpp cachyos-ananicy-rules-git"
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# ===================================================================
|
||||
# Apply all tweaks
|
||||
# ===================================================================
|
||||
main() {
|
||||
apply_tweak \
|
||||
"Tweak 1/10: Set CPU governor to performance on all cores" \
|
||||
|
||||
@ -0,0 +1,92 @@
|
||||
#!/bin/bash
|
||||
# System dependency and CUDA runtime installation.
|
||||
#
|
||||
# Sourced by transcribe.sh; split out to keep it under the 250-line
|
||||
# cap. Sourced rather than run, so it inherits the caller's strict mode
|
||||
# and the variables defined above the source line.
|
||||
|
||||
install_system_deps() {
|
||||
have_cmd() { command -v "$1" > /dev/null 2>&1; }
|
||||
local need_ffmpeg=0 need_espeak=0
|
||||
have_cmd ffmpeg || need_ffmpeg=1
|
||||
have_cmd espeak-ng || need_espeak=1
|
||||
|
||||
# If diarization requested and online, we may also try to ensure libsndfile
|
||||
local need_libsndfile=0
|
||||
if [[ ${FW_DIARIZE:-} == "1" ]]; then
|
||||
# Heuristic: check common library file
|
||||
if [[ ! -e /usr/lib/x86_64-linux-gnu/libsndfile.so && ! -e /usr/lib/libsndfile.so && ! -e /usr/lib64/libsndfile.so ]]; then
|
||||
need_libsndfile=1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ $need_ffmpeg -eq 0 && $need_espeak -eq 0 && $need_libsndfile -eq 0 ]]; then
|
||||
log "System deps present: ffmpeg, espeak-ng${FW_DIARIZE:+, libsndfile}"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [[ $OFFLINE -eq 1 ]]; then
|
||||
echo "Missing system dependencies (ffmpeg/espeak-ng) but running in offline mode. Install them or rerun with --online." >&2
|
||||
exit 5
|
||||
fi
|
||||
|
||||
local mgr
|
||||
mgr="$(detect_pkg_mgr)"
|
||||
log "Detected package manager: $mgr (installing missing: $([[ $need_ffmpeg -eq 1 ]] && echo ffmpeg)$([[ $need_espeak -eq 1 ]] && echo espeak-ng)$([[ $need_libsndfile -eq 1 ]] && echo libsndfile))"
|
||||
|
||||
if ! command -v sudo > /dev/null 2>&1; then
|
||||
log "sudo not found; skipping system package installation attempt."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Avoid exiting on install errors; continue best-effort
|
||||
set +e
|
||||
case "$mgr" in
|
||||
apt)
|
||||
sudo apt-get update -y || log "apt-get update failed; continuing"
|
||||
pkgs=(python3-venv python3-pip)
|
||||
[[ $need_ffmpeg -eq 1 ]] && pkgs+=(ffmpeg)
|
||||
[[ $need_espeak -eq 1 ]] && pkgs+=(espeak-ng)
|
||||
if [[ $need_libsndfile -eq 1 ]]; then
|
||||
# Try both names across releases
|
||||
pkgs+=(libsndfile1)
|
||||
sudo apt-get install -y libsndfile1 || true
|
||||
# If that failed, try libsndfile2 (newer distros)
|
||||
sudo apt-get install -y libsndfile2 || true
|
||||
fi
|
||||
sudo apt-get install -y "${pkgs[@]}" || log "apt-get install failed; continuing"
|
||||
;;
|
||||
dnf)
|
||||
pkgs=(python3-venv python3-pip)
|
||||
[[ $need_ffmpeg -eq 1 ]] && pkgs+=(ffmpeg)
|
||||
[[ $need_espeak -eq 1 ]] && pkgs+=(espeak-ng)
|
||||
[[ $need_libsndfile -eq 1 ]] && pkgs+=(libsndfile)
|
||||
sudo dnf install -y "${pkgs[@]}" || log "dnf install failed; continuing"
|
||||
;;
|
||||
yum)
|
||||
pkgs=(python3-venv python3-pip)
|
||||
[[ $need_ffmpeg -eq 1 ]] && pkgs+=(ffmpeg)
|
||||
[[ $need_espeak -eq 1 ]] && pkgs+=(espeak-ng)
|
||||
[[ $need_libsndfile -eq 1 ]] && pkgs+=(libsndfile)
|
||||
sudo yum install -y "${pkgs[@]}" || log "yum install failed; continuing"
|
||||
;;
|
||||
pacman)
|
||||
pkgs=(python-virtualenv python-pip)
|
||||
[[ $need_ffmpeg -eq 1 ]] && pkgs+=(ffmpeg)
|
||||
[[ $need_espeak -eq 1 ]] && pkgs+=(espeak-ng)
|
||||
[[ $need_libsndfile -eq 1 ]] && pkgs+=(libsndfile)
|
||||
sudo pacman -Sy --noconfirm "${pkgs[@]}" || log "pacman install failed; continuing"
|
||||
;;
|
||||
zypper)
|
||||
pkgs=(python311-virtualenv python311-pip)
|
||||
[[ $need_ffmpeg -eq 1 ]] && pkgs+=(ffmpeg)
|
||||
[[ $need_espeak -eq 1 ]] && pkgs+=(espeak-ng)
|
||||
[[ $need_libsndfile -eq 1 ]] && pkgs+=(libsndfile1)
|
||||
sudo zypper install -y "${pkgs[@]}" || log "zypper install failed; continuing"
|
||||
;;
|
||||
*)
|
||||
log "Unknown package manager; please ensure ffmpeg and espeak-ng are installed."
|
||||
;;
|
||||
esac
|
||||
set -e
|
||||
}
|
||||
@ -0,0 +1,101 @@
|
||||
#!/bin/bash
|
||||
# Package manager detection and CUDA runtime checks.
|
||||
#
|
||||
# Sourced by transcribe.sh; split out to keep it under the 250-line cap.
|
||||
# Sourced rather than run, so it inherits the caller's strict mode and
|
||||
# the helper functions and variables defined above the source line.
|
||||
|
||||
detect_pkg_mgr() {
|
||||
if command -v apt-get > /dev/null 2>&1; then
|
||||
echo apt
|
||||
return
|
||||
fi
|
||||
if command -v dnf > /dev/null 2>&1; then
|
||||
echo dnf
|
||||
return
|
||||
fi
|
||||
if command -v yum > /dev/null 2>&1; then
|
||||
echo yum
|
||||
return
|
||||
fi
|
||||
if command -v pacman > /dev/null 2>&1; then
|
||||
echo pacman
|
||||
return
|
||||
fi
|
||||
if command -v zypper > /dev/null 2>&1; then
|
||||
echo zypper
|
||||
return
|
||||
fi
|
||||
echo none
|
||||
}
|
||||
|
||||
has_libcublas12() {
|
||||
# Common system locations
|
||||
for d in \
|
||||
/usr/lib \
|
||||
/usr/lib64 \
|
||||
/usr/local/cuda/lib64 \
|
||||
/usr/local/cuda-12*/lib64 \
|
||||
/opt/cuda/lib64 \
|
||||
/opt/cuda/targets/x86_64-linux/lib; do
|
||||
if [[ -e "$d/libcublas.so.12" ]]; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
# venv-provided NVIDIA CUDA libs
|
||||
if [[ -x "$VENV_DIR/bin/python" ]]; then
|
||||
local pyver
|
||||
pyver="$("$VENV_DIR"/bin/python "$PY_HELPERS" python-version 2> /dev/null || true)"
|
||||
if [[ -n $pyver ]]; then
|
||||
for d in "$VENV_DIR/lib/python$pyver/site-packages/nvidia/cublas/lib" \
|
||||
"$VENV_DIR/lib/python$pyver/site-packages/nvidia/cudnn/lib" \
|
||||
"$VENV_DIR/lib/python$pyver/site-packages/nvidia/cuda_runtime/lib"; do
|
||||
if [[ -e "$d/libcublas.so.12" ]]; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
fi
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
ensure_cuda_runtime() {
|
||||
local mgr
|
||||
mgr="$(detect_pkg_mgr)"
|
||||
if [[ $OFFLINE -eq 1 ]]; then
|
||||
if has_libcublas12; then return 0; fi
|
||||
echo "CUDA runtime (libcublas.so.12) not found and offline mode is enabled. Install CUDA 12 runtime or rerun with --online." >&2
|
||||
exit 6
|
||||
fi
|
||||
if has_libcublas12; then
|
||||
return 0
|
||||
fi
|
||||
if ! command -v sudo > /dev/null 2>&1; then
|
||||
log "sudo not found; skipping CUDA runtime install attempt."
|
||||
else
|
||||
log "CUDA cuBLAS 12 not found; attempting to install CUDA runtime (manager: $mgr)"
|
||||
set +e
|
||||
case "$mgr" in
|
||||
pacman)
|
||||
sudo pacman -Sy --noconfirm cuda cudnn || true
|
||||
;;
|
||||
apt)
|
||||
sudo apt-get update -y || true
|
||||
sudo apt-get install -y nvidia-cuda-toolkit || true
|
||||
;;
|
||||
dnf | yum)
|
||||
sudo "$mgr" install -y cuda cudnn || true
|
||||
;;
|
||||
zypper)
|
||||
sudo zypper install -y cuda cudnn || true
|
||||
;;
|
||||
*) log "Unknown package manager; cannot install CUDA automatically." ;;
|
||||
esac
|
||||
set -e
|
||||
fi
|
||||
# Re-check
|
||||
if ! has_libcublas12; then
|
||||
echo "CUDA runtime (libcublas.so.12) not found after attempted install. Please install CUDA 12 toolkit/runtime and re-run." >&2
|
||||
exit 6
|
||||
fi
|
||||
}
|
||||
@ -0,0 +1,101 @@
|
||||
#!/bin/bash
|
||||
# Virtualenv setup and the model download.
|
||||
#
|
||||
# Sourced by transcribe.sh; split out to keep it under the 250-line
|
||||
# cap. Sourced rather than run, so it inherits the caller's strict mode
|
||||
# and the variables defined above the source line.
|
||||
|
||||
setup_venv() {
|
||||
if [[ ! -d $VENV_DIR ]]; then
|
||||
log "Creating venv at $VENV_DIR"
|
||||
python3 -m venv "$VENV_DIR"
|
||||
fi
|
||||
# shellcheck disable=SC1091
|
||||
source "$VENV_DIR/bin/activate"
|
||||
if [[ $OFFLINE -eq 0 ]]; then
|
||||
python -m pip install --upgrade pip wheel setuptools
|
||||
fi
|
||||
}
|
||||
|
||||
install_python_deps() {
|
||||
# Install deps; if NVIDIA GPU is present, prefer CUDA-capable stack (cu12)
|
||||
local has_nvidia_flag="${1:-0}"
|
||||
log "Installing faster-whisper and dependencies"
|
||||
export PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||
export PIP_DEFAULT_TIMEOUT=${PIP_DEFAULT_TIMEOUT:-20}
|
||||
if [[ $OFFLINE -eq 1 ]]; then
|
||||
# Offline: do not install, just verify modules
|
||||
if ! python "$PY_HELPERS" check-faster-whisper; then
|
||||
exit 7
|
||||
fi
|
||||
# If diarization requested offline, check for its deps too (warn-only)
|
||||
if [[ ${FW_DIARIZE:-} == "1" ]]; then
|
||||
python "$PY_HELPERS" check-diarization || true
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
if [[ $has_nvidia_flag -eq 1 ]]; then
|
||||
# If ctranslate2 is not installed, attempt CUDA-enabled wheel (with fallback)
|
||||
if ! "$VENV_DIR/bin/python" "$PY_HELPERS" check-ctranslate2 2> /dev/null; then
|
||||
log "Installing CUDA-enabled CTranslate2 (cu12 wheel)"
|
||||
python -m pip install --progress-bar on --retries 1 --upgrade "ctranslate2<5,>=4.0" --extra-index-url https://download.opennmt.net/ctranslate2/cu12 ||
|
||||
log "Warning: could not reach cu12 wheel index; will proceed with available ctranslate2"
|
||||
fi
|
||||
# Ensure NVIDIA CUDA 12 runtime libs are available inside the venv
|
||||
python -m pip install --progress-bar on --retries 1 --upgrade nvidia-cublas-cu12 nvidia-cuda-runtime-cu12 nvidia-cudnn-cu12 ||
|
||||
log "Warning: failed to install NVIDIA cu12 runtime libs via pip"
|
||||
fi
|
||||
python -m pip install --progress-bar on --retries 1 --upgrade faster-whisper ffmpeg-python
|
||||
|
||||
# If diarization requested and online, install its Python deps best-effort
|
||||
if [[ ${FW_DIARIZE:-} == "1" ]]; then
|
||||
python -m pip install --progress-bar on --retries 1 --upgrade soundfile speechbrain ||
|
||||
log "Warning: failed to install soundfile/speechbrain"
|
||||
# Torch and torchaudio CPU wheels (force to avoid mismatched CUDA builds)
|
||||
python -m pip install --progress-bar on --retries 1 --upgrade --force-reinstall --index-url https://download.pytorch.org/whl/cpu torch torchaudio ||
|
||||
log "Warning: failed to install torch/torchaudio CPU wheels"
|
||||
fi
|
||||
python "$PY_HELPERS" deps-installed
|
||||
}
|
||||
|
||||
ensure_runner() {
|
||||
if [[ ! -f $PY_RUNNER ]]; then
|
||||
echo "Runner not found: $PY_RUNNER" >&2
|
||||
exit 3
|
||||
fi
|
||||
}
|
||||
|
||||
generate_test_audio() {
|
||||
local tmpwav
|
||||
tmpwav="${PROJECT_DIR}/test_fw.wav"
|
||||
if command -v espeak-ng > /dev/null 2>&1; then
|
||||
log "Generating test audio via espeak-ng -> $tmpwav" >&2
|
||||
espeak-ng -w "$tmpwav" "This is a quick test of faster whisper transcription." > /dev/null 2>&1 || true
|
||||
fi
|
||||
# If espeak-ng failed or not present, try espeak
|
||||
if [[ ! -s $tmpwav ]] && command -v espeak > /dev/null 2>&1; then
|
||||
log "espeak-ng unavailable or failed; trying espeak -> $tmpwav" >&2
|
||||
espeak -w "$tmpwav" "This is a quick test of faster whisper transcription." > /dev/null 2>&1 || true
|
||||
fi
|
||||
# Fallback: generate tone via Python stdlib (no external deps)
|
||||
if [[ ! -s $tmpwav ]]; then
|
||||
log "Generating 3s 1kHz WAV via Python stdlib -> $tmpwav" >&2
|
||||
python3 "$PY_HELPERS" generate-wav --file "$tmpwav" || true
|
||||
fi
|
||||
# Final fallback: tone via ffmpeg
|
||||
if [[ ! -s $tmpwav ]]; then
|
||||
log "Creating a 3s sine tone WAV via ffmpeg -> $tmpwav" >&2
|
||||
ffmpeg -f lavfi -i sine=frequency=1000:duration=3 -ar 16000 -ac 1 -f wav -y "$tmpwav" > /dev/null 2>&1 || true
|
||||
fi
|
||||
echo "$tmpwav"
|
||||
}
|
||||
|
||||
prepare_model() {
|
||||
# Download a model for offline use into MODEL_DIR
|
||||
local name="$1"
|
||||
mkdir -p "$MODEL_DIR"
|
||||
# shellcheck disable=SC1091
|
||||
source "$VENV_DIR/bin/activate"
|
||||
log "Preparing model '$name' into $MODEL_DIR"
|
||||
python "$PY_HELPERS" prepare-model --model "$name" --model-dir "$MODEL_DIR"
|
||||
}
|
||||
@ -34,281 +34,12 @@ log() {
|
||||
echo "[$(date +'%H:%M:%S')]" "$@"
|
||||
}
|
||||
|
||||
detect_pkg_mgr() {
|
||||
if command -v apt-get > /dev/null 2>&1; then
|
||||
echo apt
|
||||
return
|
||||
fi
|
||||
if command -v dnf > /dev/null 2>&1; then
|
||||
echo dnf
|
||||
return
|
||||
fi
|
||||
if command -v yum > /dev/null 2>&1; then
|
||||
echo yum
|
||||
return
|
||||
fi
|
||||
if command -v pacman > /dev/null 2>&1; then
|
||||
echo pacman
|
||||
return
|
||||
fi
|
||||
if command -v zypper > /dev/null 2>&1; then
|
||||
echo zypper
|
||||
return
|
||||
fi
|
||||
echo none
|
||||
}
|
||||
|
||||
has_libcublas12() {
|
||||
# Common system locations
|
||||
for d in \
|
||||
/usr/lib \
|
||||
/usr/lib64 \
|
||||
/usr/local/cuda/lib64 \
|
||||
/usr/local/cuda-12*/lib64 \
|
||||
/opt/cuda/lib64 \
|
||||
/opt/cuda/targets/x86_64-linux/lib; do
|
||||
if [[ -e "$d/libcublas.so.12" ]]; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
# venv-provided NVIDIA CUDA libs
|
||||
if [[ -x "$VENV_DIR/bin/python" ]]; then
|
||||
local pyver
|
||||
pyver="$("$VENV_DIR"/bin/python "$PY_HELPERS" python-version 2> /dev/null || true)"
|
||||
if [[ -n $pyver ]]; then
|
||||
for d in "$VENV_DIR/lib/python$pyver/site-packages/nvidia/cublas/lib" \
|
||||
"$VENV_DIR/lib/python$pyver/site-packages/nvidia/cudnn/lib" \
|
||||
"$VENV_DIR/lib/python$pyver/site-packages/nvidia/cuda_runtime/lib"; do
|
||||
if [[ -e "$d/libcublas.so.12" ]]; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
fi
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
ensure_cuda_runtime() {
|
||||
local mgr
|
||||
mgr="$(detect_pkg_mgr)"
|
||||
if [[ $OFFLINE -eq 1 ]]; then
|
||||
if has_libcublas12; then return 0; fi
|
||||
echo "CUDA runtime (libcublas.so.12) not found and offline mode is enabled. Install CUDA 12 runtime or rerun with --online." >&2
|
||||
exit 6
|
||||
fi
|
||||
if has_libcublas12; then
|
||||
return 0
|
||||
fi
|
||||
if ! command -v sudo > /dev/null 2>&1; then
|
||||
log "sudo not found; skipping CUDA runtime install attempt."
|
||||
else
|
||||
log "CUDA cuBLAS 12 not found; attempting to install CUDA runtime (manager: $mgr)"
|
||||
set +e
|
||||
case "$mgr" in
|
||||
pacman)
|
||||
sudo pacman -Sy --noconfirm cuda cudnn || true
|
||||
;;
|
||||
apt)
|
||||
sudo apt-get update -y || true
|
||||
sudo apt-get install -y nvidia-cuda-toolkit || true
|
||||
;;
|
||||
dnf | yum)
|
||||
sudo "$mgr" install -y cuda cudnn || true
|
||||
;;
|
||||
zypper)
|
||||
sudo zypper install -y cuda cudnn || true
|
||||
;;
|
||||
*) log "Unknown package manager; cannot install CUDA automatically." ;;
|
||||
esac
|
||||
set -e
|
||||
fi
|
||||
# Re-check
|
||||
if ! has_libcublas12; then
|
||||
echo "CUDA runtime (libcublas.so.12) not found after attempted install. Please install CUDA 12 toolkit/runtime and re-run." >&2
|
||||
exit 6
|
||||
fi
|
||||
}
|
||||
|
||||
install_system_deps() {
|
||||
have_cmd() { command -v "$1" > /dev/null 2>&1; }
|
||||
local need_ffmpeg=0 need_espeak=0
|
||||
have_cmd ffmpeg || need_ffmpeg=1
|
||||
have_cmd espeak-ng || need_espeak=1
|
||||
|
||||
# If diarization requested and online, we may also try to ensure libsndfile
|
||||
local need_libsndfile=0
|
||||
if [[ ${FW_DIARIZE:-} == "1" ]]; then
|
||||
# Heuristic: check common library file
|
||||
if [[ ! -e /usr/lib/x86_64-linux-gnu/libsndfile.so && ! -e /usr/lib/libsndfile.so && ! -e /usr/lib64/libsndfile.so ]]; then
|
||||
need_libsndfile=1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ $need_ffmpeg -eq 0 && $need_espeak -eq 0 && $need_libsndfile -eq 0 ]]; then
|
||||
log "System deps present: ffmpeg, espeak-ng${FW_DIARIZE:+, libsndfile}"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [[ $OFFLINE -eq 1 ]]; then
|
||||
echo "Missing system dependencies (ffmpeg/espeak-ng) but running in offline mode. Install them or rerun with --online." >&2
|
||||
exit 5
|
||||
fi
|
||||
|
||||
local mgr
|
||||
mgr="$(detect_pkg_mgr)"
|
||||
log "Detected package manager: $mgr (installing missing: $([[ $need_ffmpeg -eq 1 ]] && echo ffmpeg)$([[ $need_espeak -eq 1 ]] && echo espeak-ng)$([[ $need_libsndfile -eq 1 ]] && echo libsndfile))"
|
||||
|
||||
if ! command -v sudo > /dev/null 2>&1; then
|
||||
log "sudo not found; skipping system package installation attempt."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Avoid exiting on install errors; continue best-effort
|
||||
set +e
|
||||
case "$mgr" in
|
||||
apt)
|
||||
sudo apt-get update -y || log "apt-get update failed; continuing"
|
||||
pkgs=(python3-venv python3-pip)
|
||||
[[ $need_ffmpeg -eq 1 ]] && pkgs+=(ffmpeg)
|
||||
[[ $need_espeak -eq 1 ]] && pkgs+=(espeak-ng)
|
||||
if [[ $need_libsndfile -eq 1 ]]; then
|
||||
# Try both names across releases
|
||||
pkgs+=(libsndfile1)
|
||||
sudo apt-get install -y libsndfile1 || true
|
||||
# If that failed, try libsndfile2 (newer distros)
|
||||
sudo apt-get install -y libsndfile2 || true
|
||||
fi
|
||||
sudo apt-get install -y "${pkgs[@]}" || log "apt-get install failed; continuing"
|
||||
;;
|
||||
dnf)
|
||||
pkgs=(python3-venv python3-pip)
|
||||
[[ $need_ffmpeg -eq 1 ]] && pkgs+=(ffmpeg)
|
||||
[[ $need_espeak -eq 1 ]] && pkgs+=(espeak-ng)
|
||||
[[ $need_libsndfile -eq 1 ]] && pkgs+=(libsndfile)
|
||||
sudo dnf install -y "${pkgs[@]}" || log "dnf install failed; continuing"
|
||||
;;
|
||||
yum)
|
||||
pkgs=(python3-venv python3-pip)
|
||||
[[ $need_ffmpeg -eq 1 ]] && pkgs+=(ffmpeg)
|
||||
[[ $need_espeak -eq 1 ]] && pkgs+=(espeak-ng)
|
||||
[[ $need_libsndfile -eq 1 ]] && pkgs+=(libsndfile)
|
||||
sudo yum install -y "${pkgs[@]}" || log "yum install failed; continuing"
|
||||
;;
|
||||
pacman)
|
||||
pkgs=(python-virtualenv python-pip)
|
||||
[[ $need_ffmpeg -eq 1 ]] && pkgs+=(ffmpeg)
|
||||
[[ $need_espeak -eq 1 ]] && pkgs+=(espeak-ng)
|
||||
[[ $need_libsndfile -eq 1 ]] && pkgs+=(libsndfile)
|
||||
sudo pacman -Sy --noconfirm "${pkgs[@]}" || log "pacman install failed; continuing"
|
||||
;;
|
||||
zypper)
|
||||
pkgs=(python311-virtualenv python311-pip)
|
||||
[[ $need_ffmpeg -eq 1 ]] && pkgs+=(ffmpeg)
|
||||
[[ $need_espeak -eq 1 ]] && pkgs+=(espeak-ng)
|
||||
[[ $need_libsndfile -eq 1 ]] && pkgs+=(libsndfile1)
|
||||
sudo zypper install -y "${pkgs[@]}" || log "zypper install failed; continuing"
|
||||
;;
|
||||
*)
|
||||
log "Unknown package manager; please ensure ffmpeg and espeak-ng are installed."
|
||||
;;
|
||||
esac
|
||||
set -e
|
||||
}
|
||||
|
||||
setup_venv() {
|
||||
if [[ ! -d $VENV_DIR ]]; then
|
||||
log "Creating venv at $VENV_DIR"
|
||||
python3 -m venv "$VENV_DIR"
|
||||
fi
|
||||
# shellcheck disable=SC1091
|
||||
source "$VENV_DIR/bin/activate"
|
||||
if [[ $OFFLINE -eq 0 ]]; then
|
||||
python -m pip install --upgrade pip wheel setuptools
|
||||
fi
|
||||
}
|
||||
|
||||
install_python_deps() {
|
||||
# Install deps; if NVIDIA GPU is present, prefer CUDA-capable stack (cu12)
|
||||
local has_nvidia_flag="${1:-0}"
|
||||
log "Installing faster-whisper and dependencies"
|
||||
export PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||
export PIP_DEFAULT_TIMEOUT=${PIP_DEFAULT_TIMEOUT:-20}
|
||||
if [[ $OFFLINE -eq 1 ]]; then
|
||||
# Offline: do not install, just verify modules
|
||||
if ! python "$PY_HELPERS" check-faster-whisper; then
|
||||
exit 7
|
||||
fi
|
||||
# If diarization requested offline, check for its deps too (warn-only)
|
||||
if [[ ${FW_DIARIZE:-} == "1" ]]; then
|
||||
python "$PY_HELPERS" check-diarization || true
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
if [[ $has_nvidia_flag -eq 1 ]]; then
|
||||
# If ctranslate2 is not installed, attempt CUDA-enabled wheel (with fallback)
|
||||
if ! "$VENV_DIR/bin/python" "$PY_HELPERS" check-ctranslate2 2> /dev/null; then
|
||||
log "Installing CUDA-enabled CTranslate2 (cu12 wheel)"
|
||||
python -m pip install --progress-bar on --retries 1 --upgrade "ctranslate2<5,>=4.0" --extra-index-url https://download.opennmt.net/ctranslate2/cu12 ||
|
||||
log "Warning: could not reach cu12 wheel index; will proceed with available ctranslate2"
|
||||
fi
|
||||
# Ensure NVIDIA CUDA 12 runtime libs are available inside the venv
|
||||
python -m pip install --progress-bar on --retries 1 --upgrade nvidia-cublas-cu12 nvidia-cuda-runtime-cu12 nvidia-cudnn-cu12 ||
|
||||
log "Warning: failed to install NVIDIA cu12 runtime libs via pip"
|
||||
fi
|
||||
python -m pip install --progress-bar on --retries 1 --upgrade faster-whisper ffmpeg-python
|
||||
|
||||
# If diarization requested and online, install its Python deps best-effort
|
||||
if [[ ${FW_DIARIZE:-} == "1" ]]; then
|
||||
python -m pip install --progress-bar on --retries 1 --upgrade soundfile speechbrain ||
|
||||
log "Warning: failed to install soundfile/speechbrain"
|
||||
# Torch and torchaudio CPU wheels (force to avoid mismatched CUDA builds)
|
||||
python -m pip install --progress-bar on --retries 1 --upgrade --force-reinstall --index-url https://download.pytorch.org/whl/cpu torch torchaudio ||
|
||||
log "Warning: failed to install torch/torchaudio CPU wheels"
|
||||
fi
|
||||
python "$PY_HELPERS" deps-installed
|
||||
}
|
||||
|
||||
ensure_runner() {
|
||||
if [[ ! -f $PY_RUNNER ]]; then
|
||||
echo "Runner not found: $PY_RUNNER" >&2
|
||||
exit 3
|
||||
fi
|
||||
}
|
||||
|
||||
generate_test_audio() {
|
||||
local tmpwav
|
||||
tmpwav="${PROJECT_DIR}/test_fw.wav"
|
||||
if command -v espeak-ng > /dev/null 2>&1; then
|
||||
log "Generating test audio via espeak-ng -> $tmpwav" >&2
|
||||
espeak-ng -w "$tmpwav" "This is a quick test of faster whisper transcription." > /dev/null 2>&1 || true
|
||||
fi
|
||||
# If espeak-ng failed or not present, try espeak
|
||||
if [[ ! -s $tmpwav ]] && command -v espeak > /dev/null 2>&1; then
|
||||
log "espeak-ng unavailable or failed; trying espeak -> $tmpwav" >&2
|
||||
espeak -w "$tmpwav" "This is a quick test of faster whisper transcription." > /dev/null 2>&1 || true
|
||||
fi
|
||||
# Fallback: generate tone via Python stdlib (no external deps)
|
||||
if [[ ! -s $tmpwav ]]; then
|
||||
log "Generating 3s 1kHz WAV via Python stdlib -> $tmpwav" >&2
|
||||
python3 "$PY_HELPERS" generate-wav --file "$tmpwav" || true
|
||||
fi
|
||||
# Final fallback: tone via ffmpeg
|
||||
if [[ ! -s $tmpwav ]]; then
|
||||
log "Creating a 3s sine tone WAV via ffmpeg -> $tmpwav" >&2
|
||||
ffmpeg -f lavfi -i sine=frequency=1000:duration=3 -ar 16000 -ac 1 -f wav -y "$tmpwav" > /dev/null 2>&1 || true
|
||||
fi
|
||||
echo "$tmpwav"
|
||||
}
|
||||
|
||||
prepare_model() {
|
||||
# Download a model for offline use into MODEL_DIR
|
||||
local name="$1"
|
||||
mkdir -p "$MODEL_DIR"
|
||||
# shellcheck disable=SC1091
|
||||
source "$VENV_DIR/bin/activate"
|
||||
log "Preparing model '$name' into $MODEL_DIR"
|
||||
python "$PY_HELPERS" prepare-model --model "$name" --model-dir "$MODEL_DIR"
|
||||
}
|
||||
# shellcheck source=lib/transcribe_pkgmgr.sh
|
||||
source "$SCRIPT_DIR/lib/transcribe_pkgmgr.sh"
|
||||
# shellcheck source=lib/transcribe_deps.sh
|
||||
source "$SCRIPT_DIR/lib/transcribe_deps.sh"
|
||||
# shellcheck source=lib/transcribe_venv.sh
|
||||
source "$SCRIPT_DIR/lib/transcribe_venv.sh"
|
||||
|
||||
main() {
|
||||
# Defaults
|
||||
|
||||
122
linux_configuration/scripts/single_use/utils/lib/offline_cpp.sh
Executable file
122
linux_configuration/scripts/single_use/utils/lib/offline_cpp.sh
Executable file
@ -0,0 +1,122 @@
|
||||
#!/bin/bash
|
||||
# C++ documentation download and indexing.
|
||||
#
|
||||
# Sourced by setup_offline_docs.sh; split out to keep it under the 250-line
|
||||
# cap. Sourced rather than run, so it inherits the caller's strict mode
|
||||
# and the variables defined above the source line.
|
||||
|
||||
#==============================================================================
|
||||
# C/C++ Documentation (cppreference)
|
||||
# Uses cppman tool which caches pages from cppreference.com
|
||||
# Fallback: AUR cppreference package or direct download
|
||||
#==============================================================================
|
||||
download_cpp_docs() {
|
||||
print_header "C/C++ Documentation (cppreference)"
|
||||
local dest="$DOCS_DIR/c_cpp"
|
||||
|
||||
if [ -f "$dest/en/index.html" ] || [ -d "$dest/reference" ] || [ -L "$dest/system" ]; then
|
||||
print_status "C/C++ docs already present"
|
||||
return 0
|
||||
fi
|
||||
|
||||
mkdir -p "$dest"
|
||||
|
||||
# Method 1: Use cppman if available (best - fetches and caches on demand)
|
||||
if command -v cppman &> /dev/null; then
|
||||
print_status "Found cppman, caching common C++ references..."
|
||||
cppman -s cppreference.com 2> /dev/null
|
||||
cppman -c 2> /dev/null # Cache all pages
|
||||
print_success "cppman configured - use 'cppman <term>' for lookups"
|
||||
print_status "Cppman cache at: ~/.cache/cppman/"
|
||||
ln -sf ~/.cache/cppman "$dest/cppman_cache" 2> /dev/null
|
||||
build_cpp_index
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Method 2: Check if system package already installed
|
||||
if [ -d /usr/share/doc/cppreference/en ]; then
|
||||
print_status "Found system cppreference package"
|
||||
ln -sf /usr/share/doc/cppreference "$dest/system"
|
||||
print_success "C/C++ documentation linked from system package"
|
||||
build_cpp_index
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Method 3: Try AUR package (Arch Linux)
|
||||
if command -v yay &> /dev/null; then
|
||||
print_status "Installing cppreference from AUR..."
|
||||
if yay -S --noconfirm cppreference 2> /dev/null; then
|
||||
# Link to installed docs (the package uses /en not /html)
|
||||
if [ -d /usr/share/doc/cppreference/en ]; then
|
||||
ln -sf /usr/share/doc/cppreference "$dest/system"
|
||||
print_success "C/C++ documentation linked from system package"
|
||||
build_cpp_index
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Method 4: Direct download (try multiple mirrors)
|
||||
print_status "Downloading cppreference offline archive..."
|
||||
local archive="/tmp/cppreference.tar.xz"
|
||||
local urls=(
|
||||
"https://upload.cppreference.com/mwiki/images/1/16/html_book_20241110.tar.xz"
|
||||
"https://github.com/nicovank/cppreference-doc/releases/latest/download/html_book.tar.xz"
|
||||
)
|
||||
|
||||
for url in "${urls[@]}"; do
|
||||
print_status "Trying: $url"
|
||||
if curl -fL -o "$archive" "$url" 2> /dev/null; then
|
||||
print_status "Extracting (this may take a while)..."
|
||||
if tar -xJf "$archive" -C "$dest" 2> /dev/null; then
|
||||
rm -f "$archive"
|
||||
print_success "C/C++ documentation installed to $dest"
|
||||
build_cpp_index
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
print_error "Failed to download cppreference"
|
||||
print_status "Manual install: yay -S cppreference OR yay -S cppman"
|
||||
return 1
|
||||
}
|
||||
|
||||
build_cpp_index() {
|
||||
print_status "Building C/C++ documentation index..."
|
||||
local dest="$DOCS_DIR/c_cpp"
|
||||
local index="$INDEX_DIR/cpp_index.txt"
|
||||
|
||||
# Resolve symlink if present
|
||||
local search_dir="$dest"
|
||||
[ -L "$dest/system" ] && search_dir="$dest/system"
|
||||
|
||||
{
|
||||
# Find all HTML files and extract identifiers
|
||||
# Format: term|filepath (using | as separator to handle spaces)
|
||||
find "$search_dir" -name "*.html" -type f 2> /dev/null | while read -r file; do
|
||||
# Extract meaningful term from path (e.g., /en/cpp/container/vector.html -> vector)
|
||||
local term
|
||||
term=$(basename "$file" .html)
|
||||
# Skip index files and overly generic names
|
||||
[[ $term == "index" ]] && continue
|
||||
echo "${term}|${file}"
|
||||
done
|
||||
|
||||
# Also index by path components for better discoverability
|
||||
# e.g., cpp/container/vector -> vector
|
||||
find "$search_dir/en" -name "*.html" -type f 2> /dev/null | while read -r file; do
|
||||
# Extract path relative to en/ and create searchable term
|
||||
local relpath
|
||||
relpath=$(echo "$file" | sed "s|$search_dir/en/||" | sed 's|\.html$||')
|
||||
# Get the last component as primary term
|
||||
local term
|
||||
term=$(basename "$relpath")
|
||||
[[ $term == "index" ]] && continue
|
||||
# Also add the full path as a searchable term (cpp/vector, c/stdlib/malloc)
|
||||
echo "${relpath}|${file}"
|
||||
done
|
||||
} | sort -u > "$index"
|
||||
|
||||
print_success "C/C++ index created with $(wc -l < "$index") entries"
|
||||
}
|
||||
202
linux_configuration/scripts/single_use/utils/lib/offline_index.sh
Executable file
202
linux_configuration/scripts/single_use/utils/lib/offline_index.sh
Executable file
@ -0,0 +1,202 @@
|
||||
#!/bin/bash
|
||||
# Index building and the combined docs summary.
|
||||
#
|
||||
# Sourced by setup_offline_docs.sh; split out to keep offline_rust.sh
|
||||
# under the 250-line cap. Sourced rather than run, so it inherits the
|
||||
# caller's strict mode and the variables defined above the source line.
|
||||
|
||||
build_rust_index() {
|
||||
print_status "Building Rust documentation index..."
|
||||
local index="$INDEX_DIR/rust_index.txt"
|
||||
|
||||
if command -v rustup &> /dev/null; then
|
||||
local rust_doc_path
|
||||
rust_doc_path=$(rustup doc --path 2> /dev/null | head -1 | xargs dirname 2> /dev/null)
|
||||
|
||||
if [ -d "$rust_doc_path/std" ]; then
|
||||
find "$rust_doc_path/std" -name "*.html" 2> /dev/null | head -2000 | while read -r file; do
|
||||
basename "$file" .html
|
||||
done | sort -u > "$index"
|
||||
fi
|
||||
fi
|
||||
|
||||
print_success "Rust index created"
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Go Documentation
|
||||
#==============================================================================
|
||||
download_go_docs() {
|
||||
print_header "Go Documentation"
|
||||
local dest="$DOCS_DIR/go"
|
||||
|
||||
if command -v go &> /dev/null; then
|
||||
print_status "Go docs available via 'go doc'"
|
||||
|
||||
# Create a reference of standard library packages
|
||||
mkdir -p "$dest"
|
||||
go list std 2> /dev/null > "$dest/stdlib_packages.txt"
|
||||
|
||||
print_success "Go stdlib package list created"
|
||||
build_go_index
|
||||
else
|
||||
print_status "Go not installed"
|
||||
fi
|
||||
}
|
||||
|
||||
build_go_index() {
|
||||
print_status "Building Go documentation index..."
|
||||
local dest="$DOCS_DIR/go"
|
||||
local index="$INDEX_DIR/go_index.txt"
|
||||
|
||||
if [ -f "$dest/stdlib_packages.txt" ]; then
|
||||
cp "$dest/stdlib_packages.txt" "$index"
|
||||
fi
|
||||
|
||||
print_success "Go index created"
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Shell/Bash Documentation (man pages + built-in help)
|
||||
#==============================================================================
|
||||
download_shell_docs() {
|
||||
print_header "Shell/Bash Documentation"
|
||||
local dest="$DOCS_DIR/shell"
|
||||
mkdir -p "$dest"
|
||||
|
||||
print_status "Extracting bash built-in help..."
|
||||
|
||||
# Extract help for all bash builtins
|
||||
{
|
||||
echo "# Bash Built-in Commands Reference"
|
||||
echo "# Generated from 'help' command"
|
||||
echo ""
|
||||
|
||||
# Get list of builtins
|
||||
compgen -b 2> /dev/null | while read -r builtin; do
|
||||
echo "=== $builtin ==="
|
||||
help "$builtin" 2> /dev/null || echo "No help available"
|
||||
echo ""
|
||||
done
|
||||
} > "$dest/bash_builtins.txt"
|
||||
|
||||
# Create quick reference for common commands
|
||||
cat > "$dest/common_commands.txt" << 'SHELLREF'
|
||||
# Common Shell Commands Quick Reference
|
||||
|
||||
## File Operations
|
||||
ls - List directory contents
|
||||
cd - Change directory
|
||||
pwd - Print working directory
|
||||
cp - Copy files
|
||||
mv - Move/rename files
|
||||
rm - Remove files
|
||||
mkdir - Create directory
|
||||
rmdir - Remove empty directory
|
||||
touch - Create empty file / update timestamp
|
||||
cat - Concatenate and display files
|
||||
head - Display first lines
|
||||
tail - Display last lines
|
||||
less - Page through file
|
||||
find - Search for files
|
||||
locate - Find files by name (uses database)
|
||||
|
||||
## Text Processing
|
||||
grep - Search text patterns
|
||||
sed - Stream editor
|
||||
awk - Pattern scanning and processing
|
||||
cut - Remove sections from lines
|
||||
sort - Sort lines
|
||||
uniq - Report or omit repeated lines
|
||||
wc - Word, line, character count
|
||||
tr - Translate characters
|
||||
diff - Compare files
|
||||
|
||||
## Process Management
|
||||
ps - Report process status
|
||||
top - Display processes
|
||||
kill - Send signal to process
|
||||
pkill - Kill processes by name
|
||||
bg - Background a process
|
||||
fg - Foreground a process
|
||||
jobs - List background jobs
|
||||
nohup - Run immune to hangups
|
||||
|
||||
## Networking
|
||||
curl - Transfer data from URL
|
||||
wget - Download files
|
||||
ssh - Secure shell
|
||||
scp - Secure copy
|
||||
rsync - Remote sync
|
||||
ping - Test connectivity
|
||||
netstat - Network statistics
|
||||
ss - Socket statistics
|
||||
|
||||
## Archives
|
||||
tar - Tape archive
|
||||
gzip - Compress files
|
||||
gunzip - Decompress files
|
||||
zip - Package and compress
|
||||
unzip - Extract zip archives
|
||||
|
||||
## Permissions
|
||||
chmod - Change file permissions
|
||||
chown - Change file owner
|
||||
chgrp - Change file group
|
||||
|
||||
## Disk
|
||||
df - Disk free space
|
||||
du - Disk usage
|
||||
mount - Mount filesystem
|
||||
umount - Unmount filesystem
|
||||
|
||||
## System
|
||||
uname - System information
|
||||
hostname - Show/set hostname
|
||||
uptime - System uptime
|
||||
free - Memory usage
|
||||
date - Display/set date
|
||||
cal - Display calendar
|
||||
|
||||
## Bash Builtins
|
||||
echo - Display text
|
||||
printf - Formatted output
|
||||
read - Read input
|
||||
export - Set environment variable
|
||||
source - Execute script in current shell
|
||||
alias - Create command alias
|
||||
type - Display command type
|
||||
which - Locate command
|
||||
declare - Declare variables
|
||||
local - Local variable
|
||||
set - Set shell options
|
||||
shopt - Shell options
|
||||
trap - Trap signals
|
||||
eval - Evaluate arguments
|
||||
exec - Execute command
|
||||
SHELLREF
|
||||
|
||||
print_success "Shell documentation created"
|
||||
build_shell_index
|
||||
}
|
||||
|
||||
build_shell_index() {
|
||||
print_status "Building Shell documentation index..."
|
||||
local dest="$DOCS_DIR/shell"
|
||||
local index="$INDEX_DIR/shell_index.txt"
|
||||
|
||||
{
|
||||
# Bash builtins
|
||||
compgen -b 2> /dev/null | while read -r cmd; do
|
||||
echo "$cmd $dest/bash_builtins.txt"
|
||||
done
|
||||
|
||||
# Common commands from man pages
|
||||
for cmd in ls cd cp mv rm mkdir cat grep sed awk find sort curl wget tar chmod; do
|
||||
man_path=$(man -w "$cmd" 2> /dev/null)
|
||||
[ -n "$man_path" ] && echo "$cmd $man_path"
|
||||
done
|
||||
} | sort -u > "$index"
|
||||
|
||||
print_success "Shell index created"
|
||||
}
|
||||
142
linux_configuration/scripts/single_use/utils/lib/offline_js.sh
Executable file
142
linux_configuration/scripts/single_use/utils/lib/offline_js.sh
Executable file
@ -0,0 +1,142 @@
|
||||
#!/bin/bash
|
||||
# JavaScript documentation download and indexing.
|
||||
#
|
||||
# Sourced by setup_offline_docs.sh; split out to keep offline_cpp.sh under the
|
||||
# 250-line cap. Sourced rather than run, so it inherits the caller's
|
||||
# strict mode and the variables defined above the source line.
|
||||
|
||||
#==============================================================================
|
||||
# JavaScript/MDN Documentation
|
||||
# Clone the actual MDN content repository for full documentation
|
||||
# https://github.com/mdn/content
|
||||
#==============================================================================
|
||||
download_js_docs() {
|
||||
print_header "JavaScript/MDN Documentation"
|
||||
local dest="$DOCS_DIR/javascript"
|
||||
local mdn_repo="$DOCS_DIR/mdn-content"
|
||||
|
||||
# Check if already cloned
|
||||
if [ -d "$mdn_repo/files/en-us/web/javascript" ]; then
|
||||
print_status "MDN content already present"
|
||||
build_js_index
|
||||
return 0
|
||||
fi
|
||||
|
||||
print_status "Cloning MDN content repository (sparse checkout for web docs)..."
|
||||
print_status "This may take a few minutes on first run..."
|
||||
|
||||
mkdir -p "$mdn_repo"
|
||||
cd "$mdn_repo" || exit 1
|
||||
|
||||
# Initialize sparse checkout to only get what we need
|
||||
if [ ! -d ".git" ]; then
|
||||
git init
|
||||
git remote add origin https://github.com/mdn/content.git
|
||||
git config core.sparseCheckout true
|
||||
|
||||
# Only checkout web-related documentation (JS, HTML, CSS, Web APIs)
|
||||
cat > .git/info/sparse-checkout << 'SPARSE'
|
||||
/files/en-us/web/javascript/
|
||||
/files/en-us/web/api/
|
||||
/files/en-us/web/html/
|
||||
/files/en-us/web/css/
|
||||
/files/en-us/glossary/
|
||||
SPARSE
|
||||
|
||||
print_status "Fetching MDN content (JavaScript, HTML, CSS, Web APIs)..."
|
||||
git fetch --depth 1 origin main
|
||||
git checkout main
|
||||
else
|
||||
print_status "Updating MDN content..."
|
||||
git pull --depth 1 origin main 2> /dev/null || true
|
||||
fi
|
||||
|
||||
cd - > /dev/null || exit 1
|
||||
|
||||
# Create symlink for easier access
|
||||
mkdir -p "$dest"
|
||||
ln -sf "$mdn_repo/files/en-us/web/javascript" "$dest/javascript"
|
||||
ln -sf "$mdn_repo/files/en-us/web/api" "$dest/web-api"
|
||||
ln -sf "$mdn_repo/files/en-us/web/html" "$dest/html"
|
||||
ln -sf "$mdn_repo/files/en-us/web/css" "$dest/css"
|
||||
ln -sf "$mdn_repo/files/en-us/glossary" "$dest/glossary"
|
||||
|
||||
build_js_index
|
||||
print_success "MDN offline documentation ready"
|
||||
|
||||
local doc_count
|
||||
doc_count=$(find "$mdn_repo/files" -name "index.md" 2> /dev/null | wc -l)
|
||||
print_status "Downloaded $doc_count documentation pages"
|
||||
}
|
||||
|
||||
build_js_index() {
|
||||
print_status "Building MDN documentation index..."
|
||||
local mdn_repo="$DOCS_DIR/mdn-content"
|
||||
local index="$INDEX_DIR/js_index.txt"
|
||||
|
||||
if [ ! -d "$mdn_repo/files" ]; then
|
||||
print_error "MDN content not found"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Build comprehensive index from MDN markdown files
|
||||
{
|
||||
# Index JavaScript reference
|
||||
find "$mdn_repo/files/en-us/web/javascript/reference" -name "index.md" 2> /dev/null | while read -r file; do
|
||||
local dir
|
||||
dir=$(dirname "$file")
|
||||
local term
|
||||
term=$(basename "$dir")
|
||||
# Extract title from frontmatter if available
|
||||
local title
|
||||
title=$(grep -m1 "^title:" "$file" 2> /dev/null | sed 's/^title:\s*//' | tr -d '"')
|
||||
echo "${term}|${file}|${title:-$term}"
|
||||
done
|
||||
|
||||
# Index Web APIs
|
||||
find "$mdn_repo/files/en-us/web/api" -name "index.md" 2> /dev/null | while read -r file; do
|
||||
local dir
|
||||
dir=$(dirname "$file")
|
||||
local term
|
||||
term=$(basename "$dir")
|
||||
local title
|
||||
title=$(grep -m1 "^title:" "$file" 2> /dev/null | sed 's/^title:\s*//' | tr -d '"')
|
||||
echo "${term}|${file}|${title:-$term}"
|
||||
done
|
||||
|
||||
# Index HTML elements
|
||||
find "$mdn_repo/files/en-us/web/html/element" -name "index.md" 2> /dev/null | while read -r file; do
|
||||
local dir
|
||||
dir=$(dirname "$file")
|
||||
local term
|
||||
term=$(basename "$dir")
|
||||
echo "${term}|${file}|HTML <${term}> element"
|
||||
done
|
||||
|
||||
# Index CSS properties
|
||||
find "$mdn_repo/files/en-us/web/css" -maxdepth 2 -name "index.md" 2> /dev/null | while read -r file; do
|
||||
local dir
|
||||
dir=$(dirname "$file")
|
||||
local term
|
||||
term=$(basename "$dir")
|
||||
local title
|
||||
title=$(grep -m1 "^title:" "$file" 2> /dev/null | sed 's/^title:\s*//' | tr -d '"')
|
||||
echo "${term}|${file}|${title:-$term}"
|
||||
done
|
||||
|
||||
# Index Glossary
|
||||
find "$mdn_repo/files/en-us/glossary" -name "index.md" 2> /dev/null | while read -r file; do
|
||||
local dir
|
||||
dir=$(dirname "$file")
|
||||
local term
|
||||
term=$(basename "$dir")
|
||||
local title
|
||||
title=$(grep -m1 "^title:" "$file" 2> /dev/null | sed 's/^title:\s*//' | tr -d '"')
|
||||
echo "${term}|${file}|${title:-$term}"
|
||||
done
|
||||
} | sort -t'|' -k1,1 -u > "$index"
|
||||
|
||||
local count
|
||||
count=$(wc -l < "$index")
|
||||
print_success "MDN index created with $count entries"
|
||||
}
|
||||
69
linux_configuration/scripts/single_use/utils/lib/offline_python.sh
Executable file
69
linux_configuration/scripts/single_use/utils/lib/offline_python.sh
Executable file
@ -0,0 +1,69 @@
|
||||
#!/bin/bash
|
||||
# Python documentation download and indexing.
|
||||
#
|
||||
# Sourced by setup_offline_docs.sh; split out to keep it under the 250-line
|
||||
# cap. Sourced rather than run, so it inherits the caller's strict mode
|
||||
# and the variables defined above the source line.
|
||||
|
||||
#==============================================================================
|
||||
# Python Documentation
|
||||
# Source: https://docs.python.org/3/download.html
|
||||
#==============================================================================
|
||||
download_python_docs() {
|
||||
print_header "Python Documentation"
|
||||
local dest="$DOCS_DIR/python"
|
||||
|
||||
# Check if already downloaded
|
||||
if [ -f "$dest/library/index.html" ]; then
|
||||
print_status "Python docs already present, checking for updates..."
|
||||
fi
|
||||
|
||||
print_status "Downloading Python 3.12 documentation..."
|
||||
|
||||
# Download HTML documentation (most searchable)
|
||||
local url="https://www.python.org/ftp/python/doc/3.12.8/python-3.12.8-docs-html.tar.bz2"
|
||||
local archive="/tmp/python-docs.tar.bz2"
|
||||
|
||||
if curl -L -o "$archive" "$url" 2> /dev/null; then
|
||||
print_status "Extracting..."
|
||||
tar -xjf "$archive" -C "$dest" --strip-components=1
|
||||
rm -f "$archive"
|
||||
print_success "Python documentation installed to $dest"
|
||||
|
||||
# Build index
|
||||
build_python_index
|
||||
else
|
||||
print_error "Failed to download Python docs"
|
||||
print_status "Alternative: Use 'python -m pydoc' for built-in docs"
|
||||
fi
|
||||
}
|
||||
|
||||
build_python_index() {
|
||||
print_status "Building Python documentation index..."
|
||||
local dest="$DOCS_DIR/python"
|
||||
local index="$INDEX_DIR/python_index.txt"
|
||||
|
||||
# Create searchable index: term -> file path
|
||||
{
|
||||
# Index library modules
|
||||
find "$dest/library" -name "*.html" -exec basename {} .html \; 2> /dev/null | while read -r mod; do
|
||||
echo "$mod $dest/library/$mod.html"
|
||||
done
|
||||
|
||||
# Index built-in functions from functions.html
|
||||
if [ -f "$dest/library/functions.html" ]; then
|
||||
grep -oP '(?<=id=")[^"]+' "$dest/library/functions.html" 2> /dev/null | while read -r func; do
|
||||
echo "$func $dest/library/functions.html#$func"
|
||||
done
|
||||
fi
|
||||
|
||||
# Index from general index
|
||||
if [ -f "$dest/genindex.html" ]; then
|
||||
grep -oP 'href="([^"]+)"[^>]*>([^<]+)' "$dest/genindex.html" 2> /dev/null |
|
||||
sed -E 's/href="([^"]+)"[^>]*>([^<]+)/\2 \1/' |
|
||||
head -5000
|
||||
fi
|
||||
} | sort -u > "$index"
|
||||
|
||||
print_success "Python index created with $(wc -l < "$index") entries"
|
||||
}
|
||||
30
linux_configuration/scripts/single_use/utils/lib/offline_rust.sh
Executable file
30
linux_configuration/scripts/single_use/utils/lib/offline_rust.sh
Executable file
@ -0,0 +1,30 @@
|
||||
#!/bin/bash
|
||||
# Rust documentation download and indexing.
|
||||
#
|
||||
# Sourced by setup_offline_docs.sh; split out to keep offline_js.sh under the
|
||||
# 250-line cap. Sourced rather than run, so it inherits the caller's
|
||||
# strict mode and the variables defined above the source line.
|
||||
|
||||
#==============================================================================
|
||||
# Rust Documentation (via rustup)
|
||||
#==============================================================================
|
||||
download_rust_docs() {
|
||||
print_header "Rust Documentation"
|
||||
local dest="$DOCS_DIR/rust"
|
||||
|
||||
if command -v rustup &> /dev/null; then
|
||||
print_status "Rust docs available via 'rustup doc'"
|
||||
|
||||
# Get the rust doc path
|
||||
local rust_doc_path
|
||||
rust_doc_path=$(rustup doc --path 2> /dev/null | head -1 | xargs dirname 2> /dev/null)
|
||||
|
||||
if [ -n "$rust_doc_path" ] && [ -d "$rust_doc_path" ]; then
|
||||
ln -sf "$rust_doc_path" "$dest/std"
|
||||
print_success "Linked Rust std docs from $rust_doc_path"
|
||||
build_rust_index
|
||||
fi
|
||||
else
|
||||
print_status "Rust not installed. Install with: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh"
|
||||
fi
|
||||
}
|
||||
73
linux_configuration/scripts/single_use/utils/lib/offline_status.sh
Executable file
73
linux_configuration/scripts/single_use/utils/lib/offline_status.sh
Executable file
@ -0,0 +1,73 @@
|
||||
#!/bin/bash
|
||||
# Zeal docset setup, usage text and the status report.
|
||||
#
|
||||
# Sourced by setup_offline_docs.sh; split out to keep offline_index.sh
|
||||
# under the 250-line cap. Sourced rather than run, so it inherits the
|
||||
# caller's strict mode and the variables defined above the source line.
|
||||
|
||||
#==============================================================================
|
||||
# Zeal Docsets (cross-platform dash alternative)
|
||||
#==============================================================================
|
||||
setup_zeal_docsets() {
|
||||
print_header "Zeal Docsets (Optional)"
|
||||
|
||||
if ! command -v zeal &> /dev/null; then
|
||||
print_status "Zeal not installed."
|
||||
print_status "Install with: pacman -S zeal (or your package manager)"
|
||||
print_status "Zeal provides a GUI for offline documentation"
|
||||
return 0
|
||||
fi
|
||||
|
||||
print_status "Zeal is installed. You can download docsets from within Zeal."
|
||||
print_status "Recommended docsets: Python 3, JavaScript, TypeScript, C, C++"
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Main
|
||||
#==============================================================================
|
||||
usage() {
|
||||
cat << EOF
|
||||
Usage: $0 [OPTIONS]
|
||||
|
||||
Download and setup offline documentation for programming languages.
|
||||
|
||||
Options:
|
||||
--all Download all available documentation
|
||||
--python Download Python documentation
|
||||
--cpp, --c Download C/C++ documentation (cppreference)
|
||||
--js Download JavaScript documentation
|
||||
--rust Download/link Rust documentation
|
||||
--go Download/link Go documentation
|
||||
--shell Generate Shell/Bash documentation
|
||||
--zeal Setup Zeal docsets info
|
||||
--status Show what's installed
|
||||
--help Show this help
|
||||
|
||||
Documentation is stored in: $DOCS_DIR
|
||||
|
||||
Examples:
|
||||
$0 --all # Download everything
|
||||
$0 --python --cpp # Download Python and C++ docs
|
||||
$0 --status # Check what's installed
|
||||
EOF
|
||||
}
|
||||
|
||||
show_status() {
|
||||
print_header "Offline Documentation Status"
|
||||
echo "Documentation directory: $DOCS_DIR"
|
||||
echo ""
|
||||
|
||||
for lang in python c_cpp javascript rust go shell; do
|
||||
dir="$DOCS_DIR/$lang"
|
||||
if [ -d "$dir" ] && [ "$(ls -A "$dir" 2> /dev/null)" ]; then
|
||||
size=$(du -sh "$dir" 2> /dev/null | cut -f1)
|
||||
print_success "$lang: installed ($size)"
|
||||
else
|
||||
print_error "$lang: not installed"
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "Index files:"
|
||||
ls -la "$INDEX_DIR"/*.txt 2> /dev/null || echo "No indexes built yet"
|
||||
}
|
||||
@ -45,607 +45,21 @@ setup_dirs() {
|
||||
mkdir -p "$INDEX_DIR"
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Python Documentation
|
||||
# Source: https://docs.python.org/3/download.html
|
||||
#==============================================================================
|
||||
download_python_docs() {
|
||||
print_header "Python Documentation"
|
||||
local dest="$DOCS_DIR/python"
|
||||
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
|
||||
|
||||
# shellcheck source=lib/offline_python.sh
|
||||
source "$SCRIPT_DIR/lib/offline_python.sh"
|
||||
# shellcheck source=lib/offline_cpp.sh
|
||||
source "$SCRIPT_DIR/lib/offline_cpp.sh"
|
||||
# shellcheck source=lib/offline_js.sh
|
||||
source "$SCRIPT_DIR/lib/offline_js.sh"
|
||||
# shellcheck source=lib/offline_rust.sh
|
||||
source "$SCRIPT_DIR/lib/offline_rust.sh"
|
||||
# shellcheck source=lib/offline_index.sh
|
||||
source "$SCRIPT_DIR/lib/offline_index.sh"
|
||||
# shellcheck source=lib/offline_status.sh
|
||||
source "$SCRIPT_DIR/lib/offline_status.sh"
|
||||
|
||||
# Check if already downloaded
|
||||
if [ -f "$dest/library/index.html" ]; then
|
||||
print_status "Python docs already present, checking for updates..."
|
||||
fi
|
||||
|
||||
print_status "Downloading Python 3.12 documentation..."
|
||||
|
||||
# Download HTML documentation (most searchable)
|
||||
local url="https://www.python.org/ftp/python/doc/3.12.8/python-3.12.8-docs-html.tar.bz2"
|
||||
local archive="/tmp/python-docs.tar.bz2"
|
||||
|
||||
if curl -L -o "$archive" "$url" 2> /dev/null; then
|
||||
print_status "Extracting..."
|
||||
tar -xjf "$archive" -C "$dest" --strip-components=1
|
||||
rm -f "$archive"
|
||||
print_success "Python documentation installed to $dest"
|
||||
|
||||
# Build index
|
||||
build_python_index
|
||||
else
|
||||
print_error "Failed to download Python docs"
|
||||
print_status "Alternative: Use 'python -m pydoc' for built-in docs"
|
||||
fi
|
||||
}
|
||||
|
||||
build_python_index() {
|
||||
print_status "Building Python documentation index..."
|
||||
local dest="$DOCS_DIR/python"
|
||||
local index="$INDEX_DIR/python_index.txt"
|
||||
|
||||
# Create searchable index: term -> file path
|
||||
{
|
||||
# Index library modules
|
||||
find "$dest/library" -name "*.html" -exec basename {} .html \; 2> /dev/null | while read -r mod; do
|
||||
echo "$mod $dest/library/$mod.html"
|
||||
done
|
||||
|
||||
# Index built-in functions from functions.html
|
||||
if [ -f "$dest/library/functions.html" ]; then
|
||||
grep -oP '(?<=id=")[^"]+' "$dest/library/functions.html" 2> /dev/null | while read -r func; do
|
||||
echo "$func $dest/library/functions.html#$func"
|
||||
done
|
||||
fi
|
||||
|
||||
# Index from general index
|
||||
if [ -f "$dest/genindex.html" ]; then
|
||||
grep -oP 'href="([^"]+)"[^>]*>([^<]+)' "$dest/genindex.html" 2> /dev/null |
|
||||
sed -E 's/href="([^"]+)"[^>]*>([^<]+)/\2 \1/' |
|
||||
head -5000
|
||||
fi
|
||||
} | sort -u > "$index"
|
||||
|
||||
print_success "Python index created with $(wc -l < "$index") entries"
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# C/C++ Documentation (cppreference)
|
||||
# Uses cppman tool which caches pages from cppreference.com
|
||||
# Fallback: AUR cppreference package or direct download
|
||||
#==============================================================================
|
||||
download_cpp_docs() {
|
||||
print_header "C/C++ Documentation (cppreference)"
|
||||
local dest="$DOCS_DIR/c_cpp"
|
||||
|
||||
if [ -f "$dest/en/index.html" ] || [ -d "$dest/reference" ] || [ -L "$dest/system" ]; then
|
||||
print_status "C/C++ docs already present"
|
||||
return 0
|
||||
fi
|
||||
|
||||
mkdir -p "$dest"
|
||||
|
||||
# Method 1: Use cppman if available (best - fetches and caches on demand)
|
||||
if command -v cppman &> /dev/null; then
|
||||
print_status "Found cppman, caching common C++ references..."
|
||||
cppman -s cppreference.com 2> /dev/null
|
||||
cppman -c 2> /dev/null # Cache all pages
|
||||
print_success "cppman configured - use 'cppman <term>' for lookups"
|
||||
print_status "Cppman cache at: ~/.cache/cppman/"
|
||||
ln -sf ~/.cache/cppman "$dest/cppman_cache" 2> /dev/null
|
||||
build_cpp_index
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Method 2: Check if system package already installed
|
||||
if [ -d /usr/share/doc/cppreference/en ]; then
|
||||
print_status "Found system cppreference package"
|
||||
ln -sf /usr/share/doc/cppreference "$dest/system"
|
||||
print_success "C/C++ documentation linked from system package"
|
||||
build_cpp_index
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Method 3: Try AUR package (Arch Linux)
|
||||
if command -v yay &> /dev/null; then
|
||||
print_status "Installing cppreference from AUR..."
|
||||
if yay -S --noconfirm cppreference 2> /dev/null; then
|
||||
# Link to installed docs (the package uses /en not /html)
|
||||
if [ -d /usr/share/doc/cppreference/en ]; then
|
||||
ln -sf /usr/share/doc/cppreference "$dest/system"
|
||||
print_success "C/C++ documentation linked from system package"
|
||||
build_cpp_index
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Method 4: Direct download (try multiple mirrors)
|
||||
print_status "Downloading cppreference offline archive..."
|
||||
local archive="/tmp/cppreference.tar.xz"
|
||||
local urls=(
|
||||
"https://upload.cppreference.com/mwiki/images/1/16/html_book_20241110.tar.xz"
|
||||
"https://github.com/nicovank/cppreference-doc/releases/latest/download/html_book.tar.xz"
|
||||
)
|
||||
|
||||
for url in "${urls[@]}"; do
|
||||
print_status "Trying: $url"
|
||||
if curl -fL -o "$archive" "$url" 2> /dev/null; then
|
||||
print_status "Extracting (this may take a while)..."
|
||||
if tar -xJf "$archive" -C "$dest" 2> /dev/null; then
|
||||
rm -f "$archive"
|
||||
print_success "C/C++ documentation installed to $dest"
|
||||
build_cpp_index
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
print_error "Failed to download cppreference"
|
||||
print_status "Manual install: yay -S cppreference OR yay -S cppman"
|
||||
return 1
|
||||
}
|
||||
|
||||
build_cpp_index() {
|
||||
print_status "Building C/C++ documentation index..."
|
||||
local dest="$DOCS_DIR/c_cpp"
|
||||
local index="$INDEX_DIR/cpp_index.txt"
|
||||
|
||||
# Resolve symlink if present
|
||||
local search_dir="$dest"
|
||||
[ -L "$dest/system" ] && search_dir="$dest/system"
|
||||
|
||||
{
|
||||
# Find all HTML files and extract identifiers
|
||||
# Format: term|filepath (using | as separator to handle spaces)
|
||||
find "$search_dir" -name "*.html" -type f 2> /dev/null | while read -r file; do
|
||||
# Extract meaningful term from path (e.g., /en/cpp/container/vector.html -> vector)
|
||||
local term
|
||||
term=$(basename "$file" .html)
|
||||
# Skip index files and overly generic names
|
||||
[[ $term == "index" ]] && continue
|
||||
echo "${term}|${file}"
|
||||
done
|
||||
|
||||
# Also index by path components for better discoverability
|
||||
# e.g., cpp/container/vector -> vector
|
||||
find "$search_dir/en" -name "*.html" -type f 2> /dev/null | while read -r file; do
|
||||
# Extract path relative to en/ and create searchable term
|
||||
local relpath
|
||||
relpath=$(echo "$file" | sed "s|$search_dir/en/||" | sed 's|\.html$||')
|
||||
# Get the last component as primary term
|
||||
local term
|
||||
term=$(basename "$relpath")
|
||||
[[ $term == "index" ]] && continue
|
||||
# Also add the full path as a searchable term (cpp/vector, c/stdlib/malloc)
|
||||
echo "${relpath}|${file}"
|
||||
done
|
||||
} | sort -u > "$index"
|
||||
|
||||
print_success "C/C++ index created with $(wc -l < "$index") entries"
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# JavaScript/MDN Documentation
|
||||
# Clone the actual MDN content repository for full documentation
|
||||
# https://github.com/mdn/content
|
||||
#==============================================================================
|
||||
download_js_docs() {
|
||||
print_header "JavaScript/MDN Documentation"
|
||||
local dest="$DOCS_DIR/javascript"
|
||||
local mdn_repo="$DOCS_DIR/mdn-content"
|
||||
|
||||
# Check if already cloned
|
||||
if [ -d "$mdn_repo/files/en-us/web/javascript" ]; then
|
||||
print_status "MDN content already present"
|
||||
build_js_index
|
||||
return 0
|
||||
fi
|
||||
|
||||
print_status "Cloning MDN content repository (sparse checkout for web docs)..."
|
||||
print_status "This may take a few minutes on first run..."
|
||||
|
||||
mkdir -p "$mdn_repo"
|
||||
cd "$mdn_repo" || exit 1
|
||||
|
||||
# Initialize sparse checkout to only get what we need
|
||||
if [ ! -d ".git" ]; then
|
||||
git init
|
||||
git remote add origin https://github.com/mdn/content.git
|
||||
git config core.sparseCheckout true
|
||||
|
||||
# Only checkout web-related documentation (JS, HTML, CSS, Web APIs)
|
||||
cat > .git/info/sparse-checkout << 'SPARSE'
|
||||
/files/en-us/web/javascript/
|
||||
/files/en-us/web/api/
|
||||
/files/en-us/web/html/
|
||||
/files/en-us/web/css/
|
||||
/files/en-us/glossary/
|
||||
SPARSE
|
||||
|
||||
print_status "Fetching MDN content (JavaScript, HTML, CSS, Web APIs)..."
|
||||
git fetch --depth 1 origin main
|
||||
git checkout main
|
||||
else
|
||||
print_status "Updating MDN content..."
|
||||
git pull --depth 1 origin main 2> /dev/null || true
|
||||
fi
|
||||
|
||||
cd - > /dev/null || exit 1
|
||||
|
||||
# Create symlink for easier access
|
||||
mkdir -p "$dest"
|
||||
ln -sf "$mdn_repo/files/en-us/web/javascript" "$dest/javascript"
|
||||
ln -sf "$mdn_repo/files/en-us/web/api" "$dest/web-api"
|
||||
ln -sf "$mdn_repo/files/en-us/web/html" "$dest/html"
|
||||
ln -sf "$mdn_repo/files/en-us/web/css" "$dest/css"
|
||||
ln -sf "$mdn_repo/files/en-us/glossary" "$dest/glossary"
|
||||
|
||||
build_js_index
|
||||
print_success "MDN offline documentation ready"
|
||||
|
||||
local doc_count
|
||||
doc_count=$(find "$mdn_repo/files" -name "index.md" 2> /dev/null | wc -l)
|
||||
print_status "Downloaded $doc_count documentation pages"
|
||||
}
|
||||
|
||||
build_js_index() {
|
||||
print_status "Building MDN documentation index..."
|
||||
local mdn_repo="$DOCS_DIR/mdn-content"
|
||||
local index="$INDEX_DIR/js_index.txt"
|
||||
|
||||
if [ ! -d "$mdn_repo/files" ]; then
|
||||
print_error "MDN content not found"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Build comprehensive index from MDN markdown files
|
||||
{
|
||||
# Index JavaScript reference
|
||||
find "$mdn_repo/files/en-us/web/javascript/reference" -name "index.md" 2> /dev/null | while read -r file; do
|
||||
local dir
|
||||
dir=$(dirname "$file")
|
||||
local term
|
||||
term=$(basename "$dir")
|
||||
# Extract title from frontmatter if available
|
||||
local title
|
||||
title=$(grep -m1 "^title:" "$file" 2> /dev/null | sed 's/^title:\s*//' | tr -d '"')
|
||||
echo "${term}|${file}|${title:-$term}"
|
||||
done
|
||||
|
||||
# Index Web APIs
|
||||
find "$mdn_repo/files/en-us/web/api" -name "index.md" 2> /dev/null | while read -r file; do
|
||||
local dir
|
||||
dir=$(dirname "$file")
|
||||
local term
|
||||
term=$(basename "$dir")
|
||||
local title
|
||||
title=$(grep -m1 "^title:" "$file" 2> /dev/null | sed 's/^title:\s*//' | tr -d '"')
|
||||
echo "${term}|${file}|${title:-$term}"
|
||||
done
|
||||
|
||||
# Index HTML elements
|
||||
find "$mdn_repo/files/en-us/web/html/element" -name "index.md" 2> /dev/null | while read -r file; do
|
||||
local dir
|
||||
dir=$(dirname "$file")
|
||||
local term
|
||||
term=$(basename "$dir")
|
||||
echo "${term}|${file}|HTML <${term}> element"
|
||||
done
|
||||
|
||||
# Index CSS properties
|
||||
find "$mdn_repo/files/en-us/web/css" -maxdepth 2 -name "index.md" 2> /dev/null | while read -r file; do
|
||||
local dir
|
||||
dir=$(dirname "$file")
|
||||
local term
|
||||
term=$(basename "$dir")
|
||||
local title
|
||||
title=$(grep -m1 "^title:" "$file" 2> /dev/null | sed 's/^title:\s*//' | tr -d '"')
|
||||
echo "${term}|${file}|${title:-$term}"
|
||||
done
|
||||
|
||||
# Index Glossary
|
||||
find "$mdn_repo/files/en-us/glossary" -name "index.md" 2> /dev/null | while read -r file; do
|
||||
local dir
|
||||
dir=$(dirname "$file")
|
||||
local term
|
||||
term=$(basename "$dir")
|
||||
local title
|
||||
title=$(grep -m1 "^title:" "$file" 2> /dev/null | sed 's/^title:\s*//' | tr -d '"')
|
||||
echo "${term}|${file}|${title:-$term}"
|
||||
done
|
||||
} | sort -t'|' -k1,1 -u > "$index"
|
||||
|
||||
local count
|
||||
count=$(wc -l < "$index")
|
||||
print_success "MDN index created with $count entries"
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Rust Documentation (via rustup)
|
||||
#==============================================================================
|
||||
download_rust_docs() {
|
||||
print_header "Rust Documentation"
|
||||
local dest="$DOCS_DIR/rust"
|
||||
|
||||
if command -v rustup &> /dev/null; then
|
||||
print_status "Rust docs available via 'rustup doc'"
|
||||
|
||||
# Get the rust doc path
|
||||
local rust_doc_path
|
||||
rust_doc_path=$(rustup doc --path 2> /dev/null | head -1 | xargs dirname 2> /dev/null)
|
||||
|
||||
if [ -n "$rust_doc_path" ] && [ -d "$rust_doc_path" ]; then
|
||||
ln -sf "$rust_doc_path" "$dest/std"
|
||||
print_success "Linked Rust std docs from $rust_doc_path"
|
||||
build_rust_index
|
||||
fi
|
||||
else
|
||||
print_status "Rust not installed. Install with: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh"
|
||||
fi
|
||||
}
|
||||
|
||||
build_rust_index() {
|
||||
print_status "Building Rust documentation index..."
|
||||
local index="$INDEX_DIR/rust_index.txt"
|
||||
|
||||
if command -v rustup &> /dev/null; then
|
||||
local rust_doc_path
|
||||
rust_doc_path=$(rustup doc --path 2> /dev/null | head -1 | xargs dirname 2> /dev/null)
|
||||
|
||||
if [ -d "$rust_doc_path/std" ]; then
|
||||
find "$rust_doc_path/std" -name "*.html" 2> /dev/null | head -2000 | while read -r file; do
|
||||
basename "$file" .html
|
||||
done | sort -u > "$index"
|
||||
fi
|
||||
fi
|
||||
|
||||
print_success "Rust index created"
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Go Documentation
|
||||
#==============================================================================
|
||||
download_go_docs() {
|
||||
print_header "Go Documentation"
|
||||
local dest="$DOCS_DIR/go"
|
||||
|
||||
if command -v go &> /dev/null; then
|
||||
print_status "Go docs available via 'go doc'"
|
||||
|
||||
# Create a reference of standard library packages
|
||||
mkdir -p "$dest"
|
||||
go list std 2> /dev/null > "$dest/stdlib_packages.txt"
|
||||
|
||||
print_success "Go stdlib package list created"
|
||||
build_go_index
|
||||
else
|
||||
print_status "Go not installed"
|
||||
fi
|
||||
}
|
||||
|
||||
build_go_index() {
|
||||
print_status "Building Go documentation index..."
|
||||
local dest="$DOCS_DIR/go"
|
||||
local index="$INDEX_DIR/go_index.txt"
|
||||
|
||||
if [ -f "$dest/stdlib_packages.txt" ]; then
|
||||
cp "$dest/stdlib_packages.txt" "$index"
|
||||
fi
|
||||
|
||||
print_success "Go index created"
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Shell/Bash Documentation (man pages + built-in help)
|
||||
#==============================================================================
|
||||
download_shell_docs() {
|
||||
print_header "Shell/Bash Documentation"
|
||||
local dest="$DOCS_DIR/shell"
|
||||
mkdir -p "$dest"
|
||||
|
||||
print_status "Extracting bash built-in help..."
|
||||
|
||||
# Extract help for all bash builtins
|
||||
{
|
||||
echo "# Bash Built-in Commands Reference"
|
||||
echo "# Generated from 'help' command"
|
||||
echo ""
|
||||
|
||||
# Get list of builtins
|
||||
compgen -b 2> /dev/null | while read -r builtin; do
|
||||
echo "=== $builtin ==="
|
||||
help "$builtin" 2> /dev/null || echo "No help available"
|
||||
echo ""
|
||||
done
|
||||
} > "$dest/bash_builtins.txt"
|
||||
|
||||
# Create quick reference for common commands
|
||||
cat > "$dest/common_commands.txt" << 'SHELLREF'
|
||||
# Common Shell Commands Quick Reference
|
||||
|
||||
## File Operations
|
||||
ls - List directory contents
|
||||
cd - Change directory
|
||||
pwd - Print working directory
|
||||
cp - Copy files
|
||||
mv - Move/rename files
|
||||
rm - Remove files
|
||||
mkdir - Create directory
|
||||
rmdir - Remove empty directory
|
||||
touch - Create empty file / update timestamp
|
||||
cat - Concatenate and display files
|
||||
head - Display first lines
|
||||
tail - Display last lines
|
||||
less - Page through file
|
||||
find - Search for files
|
||||
locate - Find files by name (uses database)
|
||||
|
||||
## Text Processing
|
||||
grep - Search text patterns
|
||||
sed - Stream editor
|
||||
awk - Pattern scanning and processing
|
||||
cut - Remove sections from lines
|
||||
sort - Sort lines
|
||||
uniq - Report or omit repeated lines
|
||||
wc - Word, line, character count
|
||||
tr - Translate characters
|
||||
diff - Compare files
|
||||
|
||||
## Process Management
|
||||
ps - Report process status
|
||||
top - Display processes
|
||||
kill - Send signal to process
|
||||
pkill - Kill processes by name
|
||||
bg - Background a process
|
||||
fg - Foreground a process
|
||||
jobs - List background jobs
|
||||
nohup - Run immune to hangups
|
||||
|
||||
## Networking
|
||||
curl - Transfer data from URL
|
||||
wget - Download files
|
||||
ssh - Secure shell
|
||||
scp - Secure copy
|
||||
rsync - Remote sync
|
||||
ping - Test connectivity
|
||||
netstat - Network statistics
|
||||
ss - Socket statistics
|
||||
|
||||
## Archives
|
||||
tar - Tape archive
|
||||
gzip - Compress files
|
||||
gunzip - Decompress files
|
||||
zip - Package and compress
|
||||
unzip - Extract zip archives
|
||||
|
||||
## Permissions
|
||||
chmod - Change file permissions
|
||||
chown - Change file owner
|
||||
chgrp - Change file group
|
||||
|
||||
## Disk
|
||||
df - Disk free space
|
||||
du - Disk usage
|
||||
mount - Mount filesystem
|
||||
umount - Unmount filesystem
|
||||
|
||||
## System
|
||||
uname - System information
|
||||
hostname - Show/set hostname
|
||||
uptime - System uptime
|
||||
free - Memory usage
|
||||
date - Display/set date
|
||||
cal - Display calendar
|
||||
|
||||
## Bash Builtins
|
||||
echo - Display text
|
||||
printf - Formatted output
|
||||
read - Read input
|
||||
export - Set environment variable
|
||||
source - Execute script in current shell
|
||||
alias - Create command alias
|
||||
type - Display command type
|
||||
which - Locate command
|
||||
declare - Declare variables
|
||||
local - Local variable
|
||||
set - Set shell options
|
||||
shopt - Shell options
|
||||
trap - Trap signals
|
||||
eval - Evaluate arguments
|
||||
exec - Execute command
|
||||
SHELLREF
|
||||
|
||||
print_success "Shell documentation created"
|
||||
build_shell_index
|
||||
}
|
||||
|
||||
build_shell_index() {
|
||||
print_status "Building Shell documentation index..."
|
||||
local dest="$DOCS_DIR/shell"
|
||||
local index="$INDEX_DIR/shell_index.txt"
|
||||
|
||||
{
|
||||
# Bash builtins
|
||||
compgen -b 2> /dev/null | while read -r cmd; do
|
||||
echo "$cmd $dest/bash_builtins.txt"
|
||||
done
|
||||
|
||||
# Common commands from man pages
|
||||
for cmd in ls cd cp mv rm mkdir cat grep sed awk find sort curl wget tar chmod; do
|
||||
man_path=$(man -w "$cmd" 2> /dev/null)
|
||||
[ -n "$man_path" ] && echo "$cmd $man_path"
|
||||
done
|
||||
} | sort -u > "$index"
|
||||
|
||||
print_success "Shell index created"
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Zeal Docsets (cross-platform dash alternative)
|
||||
#==============================================================================
|
||||
setup_zeal_docsets() {
|
||||
print_header "Zeal Docsets (Optional)"
|
||||
|
||||
if ! command -v zeal &> /dev/null; then
|
||||
print_status "Zeal not installed."
|
||||
print_status "Install with: pacman -S zeal (or your package manager)"
|
||||
print_status "Zeal provides a GUI for offline documentation"
|
||||
return 0
|
||||
fi
|
||||
|
||||
print_status "Zeal is installed. You can download docsets from within Zeal."
|
||||
print_status "Recommended docsets: Python 3, JavaScript, TypeScript, C, C++"
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Main
|
||||
#==============================================================================
|
||||
usage() {
|
||||
cat << EOF
|
||||
Usage: $0 [OPTIONS]
|
||||
|
||||
Download and setup offline documentation for programming languages.
|
||||
|
||||
Options:
|
||||
--all Download all available documentation
|
||||
--python Download Python documentation
|
||||
--cpp, --c Download C/C++ documentation (cppreference)
|
||||
--js Download JavaScript documentation
|
||||
--rust Download/link Rust documentation
|
||||
--go Download/link Go documentation
|
||||
--shell Generate Shell/Bash documentation
|
||||
--zeal Setup Zeal docsets info
|
||||
--status Show what's installed
|
||||
--help Show this help
|
||||
|
||||
Documentation is stored in: $DOCS_DIR
|
||||
|
||||
Examples:
|
||||
$0 --all # Download everything
|
||||
$0 --python --cpp # Download Python and C++ docs
|
||||
$0 --status # Check what's installed
|
||||
EOF
|
||||
}
|
||||
|
||||
show_status() {
|
||||
print_header "Offline Documentation Status"
|
||||
echo "Documentation directory: $DOCS_DIR"
|
||||
echo ""
|
||||
|
||||
for lang in python c_cpp javascript rust go shell; do
|
||||
dir="$DOCS_DIR/$lang"
|
||||
if [ -d "$dir" ] && [ "$(ls -A "$dir" 2> /dev/null)" ]; then
|
||||
size=$(du -sh "$dir" 2> /dev/null | cut -f1)
|
||||
print_success "$lang: installed ($size)"
|
||||
else
|
||||
print_error "$lang: not installed"
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "Index files:"
|
||||
ls -la "$INDEX_DIR"/*.txt 2> /dev/null || echo "No indexes built yet"
|
||||
}
|
||||
|
||||
main() {
|
||||
setup_dirs
|
||||
|
||||
@ -27,13 +27,18 @@ tmp="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
|
||||
echo "--- $(basename "$script")"
|
||||
bash -n "$script" || exit 1
|
||||
shellcheck -x "$script" || exit 1
|
||||
for lib in "$dir"/lib/*.sh; do
|
||||
[[ -e $lib ]] || continue
|
||||
bash -n "$lib" || exit 1
|
||||
# bash -n first: a split landing inside a heredoc produces a file the
|
||||
# linter only warns about (SC1094 in the caller) but which bash rejects.
|
||||
bash -n "$lib" || {
|
||||
echo " $lib does not parse -- the split probably cut inside a heredoc" >&2
|
||||
exit 1
|
||||
}
|
||||
shellcheck "$lib" || exit 1
|
||||
done
|
||||
bash -n "$script" || exit 1
|
||||
shellcheck -x "$script" || exit 1
|
||||
|
||||
dollar='$'
|
||||
grep -q "source \"${dollar}SCRIPT_DIR/" "$script" || {
|
||||
|
||||
@ -6,8 +6,8 @@
|
||||
|
||||
## Where things stand
|
||||
|
||||
**116 files** over 250 lines (was 183). Everything is committed and pushed to
|
||||
`main` at `194b006`; the tree is clean.
|
||||
**92 files** over 250 lines (was 183 — exactly half cleared). Everything is
|
||||
committed and pushed to `main` at `776e04d`; the tree is clean.
|
||||
|
||||
**`python_pkg/` is DONE — 50 violations → 0.** Do not reopen it. Cleared one
|
||||
package per tranche, pushing after each: `brother_printer` (15→0, suite pinned
|
||||
@ -15,8 +15,17 @@ at 402), `code_tutor` (13→0, 216→217), then `android_ui`, `app_icons`,
|
||||
`token_audit`, `focus_policy`, `random_jpg` (57/44/81/137/14), then
|
||||
`wsg_grabber`'s six test modules (277).
|
||||
|
||||
**`linux_configuration` is 84 → 58**, in nine batches. The pattern is settled
|
||||
and scripted — read `docs/shell-split-recipes.md` before touching another one.
|
||||
**`linux_configuration` is 84 → 49**, in eleven batches. **All 12 prose files
|
||||
are done** (8 split, 2 deleted as completed-work records on the user's ruling).
|
||||
**`kcd2_dice_solver` is 12 → 4**, all four remaining being source files. The
|
||||
shell pattern is settled and scripted — read `docs/shell-split-recipes.md`
|
||||
before touching another one.
|
||||
|
||||
**Four deferred for shared state across the seam** in `kcd2_dice_solver` and
|
||||
`linux_configuration` alike (see the table below); the TypeScript ones are
|
||||
`search.ts` (findBestSet ⇄ hillClimb) and `badgeValue.ts` (valueBadge ⇄
|
||||
format). In TS a bad seam **compiles clean and fails at runtime** — an import
|
||||
cycle leaves a constant `undefined` at module-init. Always run the suite.
|
||||
|
||||
Earlier sessions had already done: the `~/utils` exemptions, the
|
||||
`no-inline-python` hook, `CLAUDE.md`, `poker-stakes/`, and every `wsg_grabber`
|
||||
@ -28,9 +37,9 @@ Earlier sessions had already done: the `~/utils` exemptions, the
|
||||
|
||||
| Directory | Count |
|
||||
| ------------------------------------- | ------------ |
|
||||
| `linux_configuration` | 58 |
|
||||
| `phone_focus_mode` | 13 (do LAST) |
|
||||
| `kcd2_dice_solver` | 12 |
|
||||
| `linux_configuration` | 49 |
|
||||
| `phone_focus_mode` | 12 (do LAST) |
|
||||
| `kcd2_dice_solver` | 4 |
|
||||
| `focus_owner` | 11 |
|
||||
| `billsplit` | 6 |
|
||||
| `reverse_survivors` / `meta` / `docs` | 4 each |
|
||||
@ -56,14 +65,6 @@ Next: the remaining `main()`-shaped shell scripts, then
|
||||
`kcd2_dice_solver` / `focus_owner` / `billsplit` (TS+Dart+Kotlin, untouched so
|
||||
far), then the four prose files — zero execution risk.
|
||||
|
||||
## The seam-selection rule
|
||||
|
||||
Settled over eight `python_pkg` packages and written up in
|
||||
`docs/python-split-recipes.md` under "The seam-selection rule". In one line:
|
||||
**a block may move if every patch reaching it comes from one test module; if
|
||||
two modules patch a shared collaborator, keep the collaborator and move its
|
||||
callers.** Read the doc before splitting anything with tests.
|
||||
|
||||
## The live worklist
|
||||
|
||||
Do not work from a list in this file — it goes stale. Run:
|
||||
@ -135,11 +136,10 @@ Plus `.github/workflows/file-length.yml` modelled on
|
||||
|
||||
## Language recipes
|
||||
|
||||
- `docs/python-split-recipes.md` — the `__all__` re-export form, the `TC001`
|
||||
trap that lints clean and breaks at runtime, the mixin shape for splitting a
|
||||
class, what the tests pin in place, and the coverage behaviour of new sibling
|
||||
modules. `python_pkg` is done, so this now matters only if a stray `.py`
|
||||
turns up outside it.
|
||||
- `docs/python-split-recipes.md` — the seam-selection rule, the `__all__`
|
||||
re-export form, the `TC001` trap, the mixin shape, and the coverage
|
||||
behaviour of new sibling modules. `python_pkg` is done; read it if a stray
|
||||
`.py` turns up, or for the seam rule, which generalises to any language.
|
||||
- `docs/shell-split-recipes.md` — **read this before the next
|
||||
`linux_configuration` split.** What replaces the pass count when there is no
|
||||
test suite, which scripts escape the repo, the lib shape that satisfies both
|
||||
|
||||
Loading…
Reference in New Issue
Block a user