@termwire/cli 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +125 -4
  3. package/dist/click.d.ts +52 -0
  4. package/dist/click.js +138 -0
  5. package/dist/config-schema.d.ts +7 -0
  6. package/dist/config-schema.js +19 -0
  7. package/dist/config-validation.d.ts +2 -0
  8. package/dist/config-validation.js +14 -0
  9. package/dist/config-writer.d.ts +4 -2
  10. package/dist/config-writer.js +15 -3
  11. package/dist/down.d.ts +40 -0
  12. package/dist/down.js +99 -0
  13. package/dist/identity.js +4 -1
  14. package/dist/install-prompt.js +7 -0
  15. package/dist/install.d.ts +6 -0
  16. package/dist/install.js +101 -25
  17. package/dist/mouse-binding.d.ts +60 -0
  18. package/dist/mouse-binding.js +91 -0
  19. package/dist/mouse-config.d.ts +17 -0
  20. package/dist/mouse-config.js +63 -0
  21. package/dist/process-scan-darwin.d.ts +24 -0
  22. package/dist/process-scan-darwin.js +102 -0
  23. package/dist/process-scan-linux.d.ts +13 -0
  24. package/dist/process-scan-linux.js +66 -0
  25. package/dist/process-scan.d.ts +37 -23
  26. package/dist/process-scan.js +30 -131
  27. package/dist/program.d.ts +14 -1
  28. package/dist/program.js +174 -38
  29. package/dist/reap-hook.js +1 -19
  30. package/dist/reap.d.ts +0 -5
  31. package/dist/reap.js +3 -10
  32. package/dist/runtime.d.ts +20 -5
  33. package/dist/runtime.js +44 -5
  34. package/dist/shell-quote.d.ts +6 -0
  35. package/dist/shell-quote.js +19 -0
  36. package/dist/state-log.d.ts +8 -0
  37. package/dist/state-log.js +12 -0
  38. package/dist/up.d.ts +5 -2
  39. package/dist/up.js +5 -5
  40. package/dist/workspaces.d.ts +45 -0
  41. package/dist/workspaces.js +116 -0
  42. package/dist/worktree.d.ts +16 -1
  43. package/dist/worktree.js +66 -9
  44. package/package.json +21 -7
@@ -0,0 +1,102 @@
1
+ import { emptyLabels, sessionLabel, } from "./process-scan.js";
2
+ /**
3
+ * One row of `ps -o pid=,ppid=,rss=,command=`: three right-aligned numbers, then
4
+ * everything after the first space as a single field, because the command line and
5
+ * the environment `-E` appends to it are not separable here.
6
+ */
7
+ const processRow = /^\s*(\d+)\s+(\d+)\s+(\d+)\s(.*)$/;
8
+ /** One row of `ps -o pid=,args=`: the pid, then the command line by itself. */
9
+ const argumentsRow = /^\s*(\d+)\s(.*)$/;
10
+ export function parseDarwinProcesses(stdout) {
11
+ const rows = [];
12
+ for (const line of stdout.split("\n")) {
13
+ const parsed = processRow.exec(line);
14
+ if (!parsed)
15
+ continue;
16
+ rows.push({
17
+ pid: Number(parsed[1]),
18
+ ppid: Number(parsed[2]),
19
+ rss: Number(parsed[3]),
20
+ details: parsed[4],
21
+ });
22
+ }
23
+ return rows;
24
+ }
25
+ export function parseDarwinArguments(stdout) {
26
+ const args = new Map();
27
+ for (const line of stdout.split("\n")) {
28
+ const parsed = argumentsRow.exec(line);
29
+ if (!parsed)
30
+ continue;
31
+ args.set(Number(parsed[1]), parsed[2]);
32
+ }
33
+ return args;
34
+ }
35
+ /**
36
+ * True when `text` assigns `needle`, meaning the match is a whole space-separated
37
+ * token. A command line that merely mentions the variable never qualifies.
38
+ */
39
+ export function containsAssignment(text, needle) {
40
+ let index = text.indexOf(needle);
41
+ while (index !== -1) {
42
+ const before = index === 0 ? " " : text.charAt(index - 1);
43
+ const after = index + needle.length >= text.length ? " " : text.charAt(index + needle.length);
44
+ if (/\s/.test(before) && /\s/.test(after))
45
+ return true;
46
+ index = text.indexOf(needle, index + 1);
47
+ }
48
+ return false;
49
+ }
50
+ /**
51
+ * macOS has no `/proc`, so the environment comes from `ps -E`, which appends it to
52
+ * the command column. A process that only mentions the label on its command line
53
+ * would look identical, so every candidate is re-read without `-E` and the command
54
+ * line is stripped off before the label is looked up in what remains.
55
+ */
56
+ export function createDarwinScanner(dependencies) {
57
+ return async (sessions) => {
58
+ const needles = new Map(sessions.map((session) => [session, sessionLabel(session)]));
59
+ const rows = parseDarwinProcesses(await runPs(dependencies.exec, [
60
+ "ps",
61
+ "-Eww",
62
+ "-o",
63
+ "pid=,ppid=,rss=,command=",
64
+ "-U",
65
+ String(dependencies.uid),
66
+ ]));
67
+ const processes = rows.map(({ pid, ppid, rss }) => ({ pid, ppid, rss }));
68
+ const labeled = emptyLabels(sessions);
69
+ // Hoisted: this runs once per process on the machine, times the sessions asked for.
70
+ const wanted = [...needles.values()];
71
+ const candidates = rows.filter((row) => wanted.some((needle) => containsAssignment(row.details, needle)));
72
+ if (candidates.length === 0) {
73
+ return { processes, labeled };
74
+ }
75
+ const args = parseDarwinArguments(await runPs(dependencies.exec, ["ps", "-ww", "-o", "pid=,args=", "-p", candidates.map((c) => c.pid).join(",")],
76
+ // `ps` exits non-zero when none of the requested pids exist any more, and a
77
+ // candidate that just died is simply not a target.
78
+ { allowMissingPids: true }));
79
+ for (const row of candidates) {
80
+ const argv = args.get(row.pid);
81
+ if (argv === undefined || !row.details.startsWith(argv))
82
+ continue;
83
+ const environment = row.details.slice(argv.length);
84
+ for (const [session, needle] of needles) {
85
+ if (containsAssignment(environment, needle))
86
+ labeled.get(session)?.push(row.pid);
87
+ }
88
+ }
89
+ return { processes, labeled };
90
+ };
91
+ }
92
+ async function runPs(exec, argv, options = {}) {
93
+ const execution = await exec(argv);
94
+ if (execution.exitCode === 0)
95
+ return execution.stdout;
96
+ if (options.allowMissingPids && execution.stdout.trim().length === 0)
97
+ return "";
98
+ // A failed listing must not read as an empty one: that would log a clean reap
99
+ // while the processes it exists to kill keep running.
100
+ const details = execution.stderr.trim();
101
+ throw new Error(`${argv.join(" ")} failed (exit ${execution.exitCode})${details ? `: ${details}` : ""}`);
102
+ }
@@ -0,0 +1,13 @@
1
+ import { type SessionScanner } from "./process-scan.js";
2
+ export interface LinuxScanDependencies {
3
+ readdir: (path: string) => Promise<string[]>;
4
+ readFile: (path: string) => Promise<string>;
5
+ }
6
+ /** The second field of `statm` is the resident set, in pages. */
7
+ export declare function parseLinuxRss(statm: string): number;
8
+ export declare function parseLinuxPpid(stat: string): number | undefined;
9
+ /**
10
+ * Linux reads the environment straight out of `/proc`, where it is NUL-separated, so
11
+ * a label is an exact element and no command line can be mistaken for one.
12
+ */
13
+ export declare function createLinuxScanner(dependencies: LinuxScanDependencies): SessionScanner;
@@ -0,0 +1,66 @@
1
+ import { emptyLabels, sessionLabel, } from "./process-scan.js";
2
+ /**
3
+ * `/proc/<pid>/statm` counts pages, and Node exposes no page size, so the common
4
+ * 4 KiB is assumed: a kernel with larger pages only understates the column.
5
+ */
6
+ const pageKib = 4;
7
+ /** A `/proc` entry that is a process rather than `self` or `uptime`: digits only. */
8
+ const processDirectory = /^\d+$/;
9
+ /** The second field of `statm` is the resident set, in pages. */
10
+ export function parseLinuxRss(statm) {
11
+ const pages = Number(statm.trim().split(/\s+/)[1]);
12
+ return Number.isInteger(pages) ? pages * pageKib : 0;
13
+ }
14
+ export function parseLinuxPpid(stat) {
15
+ const commandEnd = stat.lastIndexOf(")");
16
+ if (commandEnd === -1)
17
+ return undefined;
18
+ const fields = stat
19
+ .slice(commandEnd + 1)
20
+ .trim()
21
+ .split(/\s+/);
22
+ const ppid = Number(fields[1]);
23
+ return Number.isInteger(ppid) ? ppid : undefined;
24
+ }
25
+ /**
26
+ * Linux reads the environment straight out of `/proc`, where it is NUL-separated, so
27
+ * a label is an exact element and no command line can be mistaken for one.
28
+ */
29
+ export function createLinuxScanner(dependencies) {
30
+ return async (sessions) => {
31
+ const needles = new Map(sessions.map((session) => [session, sessionLabel(session)]));
32
+ const processes = [];
33
+ const labeled = emptyLabels(sessions);
34
+ for (const entry of await dependencies.readdir("/proc")) {
35
+ if (!processDirectory.test(entry))
36
+ continue;
37
+ const pid = Number(entry);
38
+ const stat = await readOptional(dependencies, `/proc/${entry}/stat`);
39
+ if (stat === undefined)
40
+ continue;
41
+ const ppid = parseLinuxPpid(stat);
42
+ if (ppid === undefined)
43
+ continue;
44
+ const statm = await readOptional(dependencies, `/proc/${entry}/statm`);
45
+ processes.push({ pid, ppid, rss: statm === undefined ? 0 : parseLinuxRss(statm) });
46
+ // Readable only for our own processes, so other users are skipped silently.
47
+ const environ = await readOptional(dependencies, `/proc/${entry}/environ`);
48
+ if (environ === undefined)
49
+ continue;
50
+ const assignments = new Set(environ.split("\0"));
51
+ for (const [session, needle] of needles) {
52
+ if (assignments.has(needle))
53
+ labeled.get(session)?.push(pid);
54
+ }
55
+ }
56
+ return { processes, labeled };
57
+ };
58
+ }
59
+ async function readOptional(dependencies, path) {
60
+ try {
61
+ return await dependencies.readFile(path);
62
+ }
63
+ catch {
64
+ return undefined;
65
+ }
66
+ }
@@ -1,8 +1,31 @@
1
- import type { Exec } from "./exec.js";
1
+ /**
2
+ * What a process scan is, independent of how a platform performs one.
3
+ *
4
+ * A platform module exports a factory that takes only its own dependencies and
5
+ * returns a `SessionScanner`; `runtime.ts` picks one. Adding a platform is a new
6
+ * module beside this one plus a branch there, and nothing else changes: `reap` and
7
+ * `ls` depend on the type, never on a platform.
8
+ *
9
+ * A new module has to honour five things, and the first two have teeth:
10
+ *
11
+ * 1. `processes` lists **every** process visible to this user, labeled or not. The
12
+ * reap protects itself, the tmux server and their ancestors with it, so a partial
13
+ * list is how a reap comes to signal its own parent.
14
+ * 2. A listing that fails throws. Returning an empty scan reads as "nothing to kill",
15
+ * and the reap would log a clean sweep while the processes it exists to kill keep
16
+ * running.
17
+ * 3. A pid counts as labeled only when `TERMWIRE_SESSION=<session>` is in its
18
+ * environment. A command line that merely mentions the label is not a match.
19
+ * 4. `labeled` carries a key for every requested session, empty list included, which
20
+ * `emptyLabels` is for.
21
+ * 5. `rss` is in KiB, and 0 when the platform cannot say.
22
+ */
2
23
  export declare const sessionVariable = "TERMWIRE_SESSION";
3
24
  export interface ProcessEntry {
4
25
  pid: number;
5
26
  ppid: number;
27
+ /** Resident set size in KiB, the unit `ps -o rss=` already reports. */
28
+ rss: number;
6
29
  }
7
30
  export interface ProcessScan {
8
31
  /** Every process visible to the current user, used to protect our own ancestors. */
@@ -10,28 +33,19 @@ export interface ProcessScan {
10
33
  /** Processes whose environment carries the scanned session label. */
11
34
  labeled: number[];
12
35
  }
13
- export type ProcessScanner = (session: string) => Promise<ProcessScan>;
14
- export interface DarwinScanDependencies {
15
- exec: Exec;
16
- uid: number;
17
- }
18
- export interface LinuxScanDependencies {
19
- readdir: (path: string) => Promise<string[]>;
20
- readFile: (path: string) => Promise<string>;
21
- }
22
- export interface ProcessScannerDependencies extends DarwinScanDependencies, LinuxScanDependencies {
23
- platform: string;
24
- }
25
- export interface DarwinProcessRow extends ProcessEntry {
26
- /** The command line, followed by the environment when `ps -E` could read it. */
27
- details: string;
36
+ export interface SessionScan {
37
+ processes: ProcessEntry[];
38
+ /** The labeled pids of each requested session, that session's own key. */
39
+ labeled: Map<string, number[]>;
28
40
  }
29
- export declare function createProcessScanner(dependencies: ProcessScannerDependencies): ProcessScanner;
30
- export declare function parseDarwinProcesses(stdout: string): DarwinProcessRow[];
31
- export declare function parseDarwinArguments(stdout: string): Map<number, string>;
32
- export declare function parseLinuxPpid(stat: string): number | undefined;
41
+ export type ProcessScanner = (session: string) => Promise<ProcessScan>;
33
42
  /**
34
- * True when `text` assigns `needle`, meaning the match is a whole space-separated
35
- * token. A command line that merely mentions the variable never qualifies.
43
+ * Several sessions from one walk over the process table. `ls` reads every workspace
44
+ * at once, and a walk per workspace would cost a full process listing each time.
36
45
  */
37
- export declare function containsAssignment(text: string, needle: string): boolean;
46
+ export type SessionScanner = (sessions: readonly string[]) => Promise<SessionScan>;
47
+ /** The assignment a labeled process carries, and what a scanner looks for. */
48
+ export declare function sessionLabel(session: string): string;
49
+ export declare function emptyLabels(sessions: readonly string[]): Map<string, number[]>;
50
+ /** The reap works one session at a time, and asks a scanner for exactly that. */
51
+ export declare function toSingleSession(scan: SessionScanner): ProcessScanner;
@@ -1,138 +1,37 @@
1
- export const sessionVariable = "TERMWIRE_SESSION";
2
- export function createProcessScanner(dependencies) {
3
- if (dependencies.platform === "darwin") {
4
- return createDarwinScanner(dependencies);
5
- }
6
- if (dependencies.platform === "linux") {
7
- return createLinuxScanner(dependencies);
8
- }
9
- throw new Error(`process scanning is not supported on ${dependencies.platform}`);
10
- }
11
- export function parseDarwinProcesses(stdout) {
12
- const rows = [];
13
- for (const line of stdout.split("\n")) {
14
- const parsed = /^\s*(\d+)\s+(\d+)\s(.*)$/.exec(line);
15
- if (!parsed)
16
- continue;
17
- rows.push({ pid: Number(parsed[1]), ppid: Number(parsed[2]), details: parsed[3] });
18
- }
19
- return rows;
20
- }
21
- export function parseDarwinArguments(stdout) {
22
- const args = new Map();
23
- for (const line of stdout.split("\n")) {
24
- const parsed = /^\s*(\d+)\s(.*)$/.exec(line);
25
- if (!parsed)
26
- continue;
27
- args.set(Number(parsed[1]), parsed[2]);
28
- }
29
- return args;
30
- }
31
- export function parseLinuxPpid(stat) {
32
- const commandEnd = stat.lastIndexOf(")");
33
- if (commandEnd === -1)
34
- return undefined;
35
- const fields = stat
36
- .slice(commandEnd + 1)
37
- .trim()
38
- .split(/\s+/);
39
- const ppid = Number(fields[1]);
40
- return Number.isInteger(ppid) ? ppid : undefined;
41
- }
42
1
  /**
43
- * True when `text` assigns `needle`, meaning the match is a whole space-separated
44
- * token. A command line that merely mentions the variable never qualifies.
2
+ * What a process scan is, independent of how a platform performs one.
3
+ *
4
+ * A platform module exports a factory that takes only its own dependencies and
5
+ * returns a `SessionScanner`; `runtime.ts` picks one. Adding a platform is a new
6
+ * module beside this one plus a branch there, and nothing else changes: `reap` and
7
+ * `ls` depend on the type, never on a platform.
8
+ *
9
+ * A new module has to honour five things, and the first two have teeth:
10
+ *
11
+ * 1. `processes` lists **every** process visible to this user, labeled or not. The
12
+ * reap protects itself, the tmux server and their ancestors with it, so a partial
13
+ * list is how a reap comes to signal its own parent.
14
+ * 2. A listing that fails throws. Returning an empty scan reads as "nothing to kill",
15
+ * and the reap would log a clean sweep while the processes it exists to kill keep
16
+ * running.
17
+ * 3. A pid counts as labeled only when `TERMWIRE_SESSION=<session>` is in its
18
+ * environment. A command line that merely mentions the label is not a match.
19
+ * 4. `labeled` carries a key for every requested session, empty list included, which
20
+ * `emptyLabels` is for.
21
+ * 5. `rss` is in KiB, and 0 when the platform cannot say.
45
22
  */
46
- export function containsAssignment(text, needle) {
47
- let index = text.indexOf(needle);
48
- while (index !== -1) {
49
- const before = index === 0 ? " " : text.charAt(index - 1);
50
- const after = index + needle.length >= text.length ? " " : text.charAt(index + needle.length);
51
- if (/\s/.test(before) && /\s/.test(after))
52
- return true;
53
- index = text.indexOf(needle, index + 1);
54
- }
55
- return false;
23
+ export const sessionVariable = "TERMWIRE_SESSION";
24
+ /** The assignment a labeled process carries, and what a scanner looks for. */
25
+ export function sessionLabel(session) {
26
+ return `${sessionVariable}=${session}`;
56
27
  }
57
- /**
58
- * macOS has no `/proc`, so the environment comes from `ps -E`, which appends it to
59
- * the command column. A process that only mentions the label on its command line
60
- * would look identical, so every candidate is re-read without `-E` and the command
61
- * line is stripped off before the label is looked up in what remains.
62
- */
63
- function createDarwinScanner(dependencies) {
64
- return async (session) => {
65
- const needle = `${sessionVariable}=${session}`;
66
- const rows = parseDarwinProcesses(await runPs(dependencies.exec, [
67
- "ps",
68
- "-Eww",
69
- "-o",
70
- "pid=,ppid=,command=",
71
- "-U",
72
- String(dependencies.uid),
73
- ]));
74
- const processes = rows.map(({ pid, ppid }) => ({ pid, ppid }));
75
- const candidates = rows.filter((row) => containsAssignment(row.details, needle));
76
- if (candidates.length === 0) {
77
- return { processes, labeled: [] };
78
- }
79
- const args = parseDarwinArguments(await runPs(dependencies.exec, ["ps", "-ww", "-o", "pid=,args=", "-p", candidates.map((c) => c.pid).join(",")],
80
- // `ps` exits non-zero when none of the requested pids exist any more, and a
81
- // candidate that just died is simply not a target.
82
- { allowMissingPids: true }));
83
- const labeled = candidates
84
- .filter((row) => {
85
- const argv = args.get(row.pid);
86
- if (argv === undefined || !row.details.startsWith(argv))
87
- return false;
88
- return containsAssignment(row.details.slice(argv.length), needle);
89
- })
90
- .map((row) => row.pid);
91
- return { processes, labeled };
92
- };
28
+ export function emptyLabels(sessions) {
29
+ return new Map(sessions.map((session) => [session, []]));
93
30
  }
94
- function createLinuxScanner(dependencies) {
31
+ /** The reap works one session at a time, and asks a scanner for exactly that. */
32
+ export function toSingleSession(scan) {
95
33
  return async (session) => {
96
- const label = `${sessionVariable}=${session}`;
97
- const processes = [];
98
- const labeled = [];
99
- for (const entry of await dependencies.readdir("/proc")) {
100
- if (!/^\d+$/.test(entry))
101
- continue;
102
- const pid = Number(entry);
103
- const stat = await readOptional(dependencies, `/proc/${entry}/stat`);
104
- if (stat === undefined)
105
- continue;
106
- const ppid = parseLinuxPpid(stat);
107
- if (ppid === undefined)
108
- continue;
109
- processes.push({ pid, ppid });
110
- // Readable only for our own processes, so other users are skipped silently.
111
- const environ = await readOptional(dependencies, `/proc/${entry}/environ`);
112
- if (environ === undefined)
113
- continue;
114
- if (environ.split("\0").includes(label))
115
- labeled.push(pid);
116
- }
117
- return { processes, labeled };
34
+ const { processes, labeled } = await scan([session]);
35
+ return { processes, labeled: labeled.get(session) ?? [] };
118
36
  };
119
37
  }
120
- async function runPs(exec, argv, options = {}) {
121
- const execution = await exec(argv);
122
- if (execution.exitCode === 0)
123
- return execution.stdout;
124
- if (options.allowMissingPids && execution.stdout.trim().length === 0)
125
- return "";
126
- // A failed listing must not read as an empty one: that would log a clean reap
127
- // while the processes it exists to kill keep running.
128
- const details = execution.stderr.trim();
129
- throw new Error(`${argv.join(" ")} failed (exit ${execution.exitCode})${details ? `: ${details}` : ""}`);
130
- }
131
- async function readOptional(dependencies, path) {
132
- try {
133
- return await dependencies.readFile(path);
134
- }
135
- catch {
136
- return undefined;
137
- }
138
- }
package/dist/program.d.ts CHANGED
@@ -1,20 +1,33 @@
1
1
  import { Command } from "commander";
2
+ import { type ClickRequest } from "./click.js";
3
+ import { type DownRequest, type DownResult } from "./down.js";
2
4
  import { type InstallRequest, type InstallResult } from "./install.js";
3
5
  import { type OpenRequest, type OpenResult } from "./open.js";
4
6
  import type { CliRuntime } from "./runtime.js";
5
7
  import { type UpRequest } from "./up.js";
8
+ import { type Workspace } from "./workspaces.js";
6
9
  export interface ProgramDependencies {
7
10
  up: (request: UpRequest) => Promise<void>;
11
+ ls: () => Promise<Workspace[]>;
12
+ down: (request: DownRequest) => Promise<DownResult>;
8
13
  open: (request: OpenRequest) => Promise<OpenResult>;
9
14
  reap: (session: string) => Promise<void>;
15
+ /** Never throws: a click that opens nothing is logged, not shown in tmux. */
16
+ click: (request: ClickRequest) => Promise<void>;
10
17
  install: (request: InstallRequest) => Promise<InstallResult>;
18
+ /** Only the table shortens `$HOME` to `~`; the JSON rows keep absolute paths. */
19
+ homedir: () => string;
20
+ version: string;
11
21
  writeError: (message: string) => void;
12
22
  writeOutput: (message: string) => void;
13
23
  }
14
24
  export declare function removeStaleSocket(path: string, unlink: (path: string) => Promise<void>): Promise<void>;
15
25
  export declare function createUp({ fs, host, git, tmux, }: CliRuntime): (request: UpRequest) => Promise<void>;
26
+ export declare function createLs({ fs, git, tmux, createScanner }: CliRuntime): () => Promise<Workspace[]>;
27
+ export declare function createDown({ host, git, tmux, }: CliRuntime): (request: DownRequest) => Promise<DownResult>;
16
28
  export declare function createOpen({ host, nvim, tmux, }: CliRuntime): (request: OpenRequest) => Promise<OpenResult>;
17
- export declare function createReap({ fs, host, exec }: CliRuntime): (session: string) => Promise<void>;
29
+ export declare function createReap({ fs, host, createScanner, }: CliRuntime): (session: string) => Promise<void>;
30
+ export declare function createClick({ fs, host, nvim, tmux, }: CliRuntime): (request: ClickRequest) => Promise<void>;
18
31
  export declare function createInstall({ fs, host, git, createPrompter, }: CliRuntime): (request: InstallRequest) => Promise<InstallResult>;
19
32
  /** Binds every command to one runtime. The only caller that needs the real one. */
20
33
  export declare function createCommands(runtime: CliRuntime): ProgramDependencies;