@termwire/cli 0.5.0 → 0.6.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.
@@ -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,28 @@
1
1
  import { Command } from "commander";
2
+ import { type DownRequest, type DownResult } from "./down.js";
2
3
  import { type InstallRequest, type InstallResult } from "./install.js";
3
4
  import { type OpenRequest, type OpenResult } from "./open.js";
4
5
  import type { CliRuntime } from "./runtime.js";
5
6
  import { type UpRequest } from "./up.js";
7
+ import { type Workspace } from "./workspaces.js";
6
8
  export interface ProgramDependencies {
7
9
  up: (request: UpRequest) => Promise<void>;
10
+ ls: () => Promise<Workspace[]>;
11
+ down: (request: DownRequest) => Promise<DownResult>;
8
12
  open: (request: OpenRequest) => Promise<OpenResult>;
9
13
  reap: (session: string) => Promise<void>;
10
14
  install: (request: InstallRequest) => Promise<InstallResult>;
15
+ /** Only the table shortens `$HOME` to `~`; the JSON rows keep absolute paths. */
16
+ homedir: () => string;
11
17
  writeError: (message: string) => void;
12
18
  writeOutput: (message: string) => void;
13
19
  }
14
20
  export declare function removeStaleSocket(path: string, unlink: (path: string) => Promise<void>): Promise<void>;
15
21
  export declare function createUp({ fs, host, git, tmux, }: CliRuntime): (request: UpRequest) => Promise<void>;
22
+ export declare function createLs({ fs, git, tmux, createScanner }: CliRuntime): () => Promise<Workspace[]>;
23
+ export declare function createDown({ host, git, tmux, }: CliRuntime): (request: DownRequest) => Promise<DownResult>;
16
24
  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>;
25
+ export declare function createReap({ fs, host, createScanner, }: CliRuntime): (session: string) => Promise<void>;
18
26
  export declare function createInstall({ fs, host, git, createPrompter, }: CliRuntime): (request: InstallRequest) => Promise<InstallResult>;
19
27
  /** Binds every command to one runtime. The only caller that needs the real one. */
20
28
  export declare function createCommands(runtime: CliRuntime): ProgramDependencies;
package/dist/program.js CHANGED
@@ -6,16 +6,18 @@ import { prepareBranch } from "./branch.js";
6
6
  import { configHome, createConfigLoader, globalConfigPath } from "./config-loader.js";
7
7
  import { resolveLayout } from "./config-validation.js";
8
8
  import { writeConfigFile } from "./config-writer.js";
9
+ import { down } from "./down.js";
9
10
  import { install, noLayout } from "./install.js";
10
11
  import { createLayout } from "./layout.js";
11
12
  import { open } from "./open.js";
12
- import { createProcessScanner } from "./process-scan.js";
13
+ import { toSingleSession } from "./process-scan.js";
13
14
  import { formatReapFailure, formatReapReport, parseTmuxServerPid, reapLogPath, reapSession, } from "./reap.js";
14
15
  import { ensureReapHook, reapCommandName } from "./reap-hook.js";
15
16
  import { skillSourcePath } from "./skill.js";
16
17
  import { layoutTemplateIds } from "./templates.js";
17
18
  import { up } from "./up.js";
18
- import { findGitRoot, prepareWorktree } from "./worktree.js";
19
+ import { collectWorkspaces, formatWorkspacesJson, formatWorkspaceTable, } from "./workspaces.js";
20
+ import { findGitRoot, inspectWorktree, prepareWorktree, removeWorktree } from "./worktree.js";
19
21
  /**
20
22
  * Read at runtime rather than baked in at build time, the way `@termwire/mcp`
21
23
  * reports its own version. `dist/program.js` and `src/program.ts` both sit one
@@ -78,22 +80,39 @@ function resolveScriptPath(scriptPath) {
78
80
  }
79
81
  return resolvePath(scriptPath);
80
82
  }
83
+ export function createLs({ fs, git, tmux, createScanner }) {
84
+ return () => collectWorkspaces({
85
+ listSessions: () => tmux.listSessions(),
86
+ showEnvironment: (session) => tmux.showEnvironment(session),
87
+ git,
88
+ pathExists: fs.exists,
89
+ // Built per run, not while the program is composed: an unsupported platform
90
+ // has to fail `ls` alone, not every command.
91
+ scan: createScanner(),
92
+ });
93
+ }
94
+ export function createDown({ host, git, tmux, }) {
95
+ return (request) => down(request, {
96
+ cwd: host.cwd,
97
+ chdir: host.chdir,
98
+ env: host.env,
99
+ findGitRoot: (directory) => findGitRoot(git, directory),
100
+ listSessions: () => tmux.listSessions(),
101
+ killSession: (session) => tmux.killSession(session),
102
+ inspectWorktree: (path) => inspectWorktree(git, path),
103
+ removeWorktree: (path, options) => removeWorktree(git, path, options),
104
+ });
105
+ }
81
106
  export function createOpen({ host, nvim, tmux, }) {
82
107
  return (request) => open(request, { cwd: host.cwd, env: host.env, nvim, tmux });
83
108
  }
84
- export function createReap({ fs, host, exec }) {
109
+ export function createReap({ fs, host, createScanner, }) {
85
110
  const record = (line) => appendQuietly(reapLogPath({ env: host.env, homedir: host.homedir }), line, fs);
86
111
  return async (session) => {
87
112
  try {
88
113
  const serverPid = parseTmuxServerPid(host.env.TMUX);
89
114
  const report = await reapSession(session, {
90
- scan: createProcessScanner({
91
- platform: host.platform,
92
- exec,
93
- uid: host.uid,
94
- readdir: fs.readdir,
95
- readFile: fs.readFile,
96
- }),
115
+ scan: toSingleSession(createScanner()),
97
116
  kill: host.kill,
98
117
  wait: host.wait,
99
118
  selfPid: host.pid,
@@ -144,9 +163,12 @@ export function createInstall({ fs, host, git, createPrompter, }) {
144
163
  export function createCommands(runtime) {
145
164
  return {
146
165
  up: createUp(runtime),
166
+ ls: createLs(runtime),
167
+ down: createDown(runtime),
147
168
  open: createOpen(runtime),
148
169
  reap: createReap(runtime),
149
170
  install: createInstall(runtime),
171
+ homedir: runtime.host.homedir,
150
172
  writeError: runtime.host.writeError,
151
173
  writeOutput: runtime.host.writeOutput,
152
174
  };
@@ -185,6 +207,50 @@ Branch and worktree selection:
185
207
  ...(options.branch === undefined ? {} : { branch: options.branch }),
186
208
  });
187
209
  });
210
+ program
211
+ .command("ls")
212
+ .description("list the termwire workspaces on this machine")
213
+ .option("--json", "print the same rows as JSON, with absolute directories")
214
+ .addHelpText("after", `
215
+ Columns:
216
+ A marks an attached session, and DIRECTORY is where it was created, $HOME as ~.
217
+ BRANCH is the Git branch there, a short sha on a detached HEAD, - outside a repository.
218
+ PROCS and RSS count every process still labeled with the session, pane or not.
219
+ A workspace whose directory is gone is listed and marked, never fatal.
220
+ A session is a workspace only when its tmux environment carries TERMWIRE_SESSION.
221
+ `)
222
+ .action(async (options) => {
223
+ const workspaces = await dependencies.ls();
224
+ dependencies.writeOutput(options.json === true
225
+ ? formatWorkspacesJson(workspaces)
226
+ : formatWorkspaceTable(workspaces, dependencies.homedir()));
227
+ });
228
+ program
229
+ .command("down [name]")
230
+ .description("kill a workspace tmux session, this one when [name] is omitted")
231
+ .option("-w, --worktree", "also remove that workspace's Git worktree")
232
+ .option("-f, --force", "with -w, remove a worktree that has uncommitted changes")
233
+ .addHelpText("after", `
234
+ Teardown:
235
+ [name] resolves exactly as it does for up, so down names the session up created.
236
+ Without it the target is the workspace this command runs in, from TERMWIRE_SESSION.
237
+ That bare form is the only one that works inside a worktree, where the Git root moves.
238
+ Closing the session kills what ran in it; the branch always outlives the workspace.
239
+ -w also removes the worktree the session sits in, refusing the main checkout.
240
+ A worktree with uncommitted changes, or the directory you stand in, is refused too.
241
+ Tearing down your own workspace removes its worktree first: the kill ends this process.
242
+ `)
243
+ .action(async (name, options) => {
244
+ const result = await dependencies.down({
245
+ ...(name === undefined ? {} : { name }),
246
+ ...(options.worktree === undefined ? {} : { worktree: true }),
247
+ ...(options.force === undefined ? {} : { force: true }),
248
+ });
249
+ dependencies.writeOutput(`Killed session ${result.session}\n`);
250
+ if (result.worktree !== undefined) {
251
+ dependencies.writeOutput(`Removed worktree ${result.worktree}\n`);
252
+ }
253
+ });
188
254
  program
189
255
  .command("open <target>")
190
256
  .description("open a file in this workspace's editor and focus it")
package/dist/runtime.d.ts CHANGED
@@ -2,11 +2,11 @@ import { createNvim } from "@termwire/nvim";
2
2
  import { createTmux } from "@termwire/tmux";
3
3
  import { type Exec } from "./exec.js";
4
4
  import type { InstallPrompter } from "./install.js";
5
+ import type { SessionScanner } from "./process-scan.js";
5
6
  import type { KillOutcome, ReapSignal } from "./reap.js";
6
7
  import type { GitExec } from "./worktree.js";
7
8
  export interface RuntimeFileSystem {
8
9
  readFile: (path: string) => Promise<string>;
9
- readdir: (path: string) => Promise<string[]>;
10
10
  exists: (path: string) => Promise<boolean>;
11
11
  mkdir: (path: string) => Promise<void>;
12
12
  /** `flag: "wx"` fails on an existing file instead of replacing it. */
@@ -20,9 +20,9 @@ export interface RuntimeFileSystem {
20
20
  export interface RuntimeHost {
21
21
  env: Record<string, string | undefined>;
22
22
  cwd: () => string;
23
+ /** Leaves a directory before it is removed: a spawn from a deleted cwd fails. */
24
+ chdir: (path: string) => void;
23
25
  homedir: () => string;
24
- platform: string;
25
- uid: number;
26
26
  pid: number;
27
27
  execPath: string;
28
28
  /** The launched script, which the tmux hook has to name by absolute path. */
@@ -50,9 +50,12 @@ export interface RuntimeHost {
50
50
  export interface CliRuntime {
51
51
  fs: RuntimeFileSystem;
52
52
  host: RuntimeHost;
53
- /** Used for anything without an adapter, currently the process scanner. */
54
- exec: Exec;
55
53
  git: GitExec;
54
+ /**
55
+ * Built on demand, so a platform that cannot be scanned fails the command that
56
+ * scans rather than every command, `--help` included.
57
+ */
58
+ createScanner: () => SessionScanner;
56
59
  tmux: ReturnType<typeof createTmux>;
57
60
  nvim: ReturnType<typeof createNvim>;
58
61
  /** Built on demand, so a command that never asks anything loads no terminal UI. */
@@ -69,6 +72,13 @@ export declare function createAdapters({ exec, env, }: {
69
72
  }): Pick<CliRuntime, "tmux" | "nvim">;
70
73
  /** The one place where the real world is bound. Nothing else imports `node:*`. */
71
74
  export declare function createNodeRuntime(): CliRuntime;
75
+ /**
76
+ * The one place that knows which platforms can be scanned. A platform module takes
77
+ * only its own dependencies, which a registry keyed by platform could not express:
78
+ * every entry would have to accept the union of what all of them need. So a new
79
+ * platform is a new module plus a branch here.
80
+ */
81
+ export declare function createPlatformScanner(platform: string): SessionScanner;
72
82
  export declare function fileExists(path: string): Promise<boolean>;
73
83
  export declare function killProcess(pid: number, signal: ReapSignal): KillOutcome;
74
84
  export declare const executeGit: GitExec;
package/dist/runtime.js CHANGED
@@ -5,6 +5,8 @@ import { homedir as getHomeDirectory } from "node:os";
5
5
  import { createNvim } from "@termwire/nvim";
6
6
  import { createTmux } from "@termwire/tmux";
7
7
  import { spawnCapture } from "./exec.js";
8
+ import { createDarwinScanner } from "./process-scan-darwin.js";
9
+ import { createLinuxScanner } from "./process-scan-linux.js";
8
10
  /**
9
11
  * Binds both adapters to one exec and one environment. The exec has to forward
10
12
  * `ExecOptions`: `attach` asks for an inherited terminal, and tmux refuses to attach
@@ -19,7 +21,6 @@ export function createNodeRuntime() {
19
21
  return {
20
22
  fs: {
21
23
  readFile: (path) => readFileFromDisk(path, "utf8"),
22
- readdir: readDirectory,
23
24
  exists: fileExists,
24
25
  mkdir: async (path) => {
25
26
  await mkdirDirectory(path, { recursive: true });
@@ -32,9 +33,8 @@ export function createNodeRuntime() {
32
33
  host: {
33
34
  env,
34
35
  cwd: () => process.cwd(),
36
+ chdir: (path) => process.chdir(path),
35
37
  homedir: getHomeDirectory,
36
- platform: process.platform,
37
- uid: process.getuid?.() ?? 0,
38
38
  pid: process.pid,
39
39
  execPath: process.execPath,
40
40
  scriptPath: process.argv[1],
@@ -46,8 +46,8 @@ export function createNodeRuntime() {
46
46
  writeOutput: (message) => process.stdout.write(message),
47
47
  writeError: (message) => process.stderr.write(message),
48
48
  },
49
- exec: spawnCapture,
50
49
  git: executeGit,
50
+ createScanner: () => createPlatformScanner(process.platform),
51
51
  ...createAdapters({ exec: spawnCapture, env }),
52
52
  // Imported here and not at the top, so `up` and `open` never load the prompts.
53
53
  createPrompter: async () => (await import("./install-prompt.js")).createClackPrompter({
@@ -55,6 +55,24 @@ export function createNodeRuntime() {
55
55
  }),
56
56
  };
57
57
  }
58
+ /**
59
+ * The one place that knows which platforms can be scanned. A platform module takes
60
+ * only its own dependencies, which a registry keyed by platform could not express:
61
+ * every entry would have to accept the union of what all of them need. So a new
62
+ * platform is a new module plus a branch here.
63
+ */
64
+ export function createPlatformScanner(platform) {
65
+ if (platform === "darwin") {
66
+ return createDarwinScanner({ exec: spawnCapture, uid: process.getuid?.() ?? 0 });
67
+ }
68
+ if (platform === "linux") {
69
+ return createLinuxScanner({
70
+ readdir: readDirectory,
71
+ readFile: (path) => readFileFromDisk(path, "utf8"),
72
+ });
73
+ }
74
+ throw new Error(`process scanning is not supported on ${platform}`);
75
+ }
58
76
  export async function fileExists(path) {
59
77
  try {
60
78
  await stat(path);
@@ -0,0 +1,45 @@
1
+ import { type SessionScanner } from "./process-scan.js";
2
+ import type { GitExec } from "./worktree.js";
3
+ /** What `ls` knows about one workspace. Collected from tmux and Git, never from disk. */
4
+ export interface Workspace {
5
+ session: string;
6
+ attached: boolean;
7
+ /** The Git branch, a short sha on a detached HEAD, or `-` outside a repository. */
8
+ branch: string;
9
+ /** The session path, absolute: shortening to `~` is for the table, not for machines. */
10
+ directory: string;
11
+ /** The session outlived its directory, which is listed and marked rather than fatal. */
12
+ missing: boolean;
13
+ procs: number;
14
+ rssKib: number;
15
+ }
16
+ /** The fields of a tmux session this module reads, as the adapter reports them. */
17
+ export interface WorkspaceSession {
18
+ name: string;
19
+ attached: boolean;
20
+ path: string;
21
+ }
22
+ export interface WorkspacesDependencies {
23
+ listSessions: () => Promise<WorkspaceSession[]>;
24
+ showEnvironment: (session: string) => Promise<Record<string, string>>;
25
+ git: GitExec;
26
+ pathExists: (path: string) => Promise<boolean>;
27
+ /** One walk over the process table, asked for every workspace at once. */
28
+ scan: SessionScanner;
29
+ }
30
+ /**
31
+ * A session is a workspace when its tmux environment carries `TERMWIRE_SESSION`,
32
+ * never because its name looks like `<project>-<name>`: the user picks the name and
33
+ * `up` sets the label, so a session of their own is never mistaken for ours.
34
+ */
35
+ export declare function collectWorkspaces({ listSessions, showEnvironment, git, pathExists, scan, }: WorkspacesDependencies): Promise<Workspace[]>;
36
+ /** Git answers through `-C`, so a directory that is gone fails instead of the spawn. */
37
+ export declare function readBranch(git: GitExec, directory: string): Promise<string>;
38
+ /** `$HOME` as `~`. A path that lies elsewhere, or an unknown home, is left alone. */
39
+ export declare function shortenHome(path: string, home: string): string;
40
+ /** KiB as the column shows it: K under a megabyte, M under a gigabyte, then one decimal. */
41
+ export declare function formatRss(kib: number): string;
42
+ /** The table `ls` prints, padded to its own contents. */
43
+ export declare function formatWorkspaceTable(workspaces: readonly Workspace[], home: string): string;
44
+ /** The same rows for machines: absolute directories, and `rssKib` in KiB. */
45
+ export declare function formatWorkspacesJson(workspaces: readonly Workspace[]): string;
@@ -0,0 +1,116 @@
1
+ import { sep } from "node:path";
2
+ import { sessionVariable } from "./process-scan.js";
3
+ const unknownBranch = "-";
4
+ /**
5
+ * A session is a workspace when its tmux environment carries `TERMWIRE_SESSION`,
6
+ * never because its name looks like `<project>-<name>`: the user picks the name and
7
+ * `up` sets the label, so a session of their own is never mistaken for ours.
8
+ */
9
+ export async function collectWorkspaces({ listSessions, showEnvironment, git, pathExists, scan, }) {
10
+ const sessions = await listSessions();
11
+ const labeled = [];
12
+ for (const session of sessions) {
13
+ const environment = await showEnvironment(session.name);
14
+ if (environment[sessionVariable] !== undefined)
15
+ labeled.push(session);
16
+ }
17
+ if (labeled.length === 0)
18
+ return [];
19
+ const usage = await measureSessions(scan, labeled.map((session) => session.name));
20
+ return await Promise.all(labeled.map((session) => describeWorkspace(session, usage.get(session.name) ?? noUsage, { git, pathExists })));
21
+ }
22
+ async function describeWorkspace(session, usage, { git, pathExists }) {
23
+ const exists = await pathExists(session.path);
24
+ return {
25
+ session: session.name,
26
+ attached: session.attached,
27
+ branch: exists ? await readBranch(git, session.path) : unknownBranch,
28
+ directory: session.path,
29
+ missing: !exists,
30
+ ...usage,
31
+ };
32
+ }
33
+ /** Git answers through `-C`, so a directory that is gone fails instead of the spawn. */
34
+ export async function readBranch(git, directory) {
35
+ const current = await git(["git", "-C", directory, "branch", "--show-current"]);
36
+ if (current.exitCode !== 0)
37
+ return unknownBranch;
38
+ const branch = current.stdout.trim();
39
+ if (branch.length > 0)
40
+ return branch;
41
+ // No current branch: a detached HEAD, which the short sha names.
42
+ const head = await git(["git", "-C", directory, "rev-parse", "--short", "HEAD"]);
43
+ const sha = head.stdout.trim();
44
+ return head.exitCode === 0 && sha.length > 0 ? sha : unknownBranch;
45
+ }
46
+ const noUsage = { procs: 0, rssKib: 0 };
47
+ async function measureSessions(scan, sessions) {
48
+ const { processes, labeled } = await scan(sessions);
49
+ const resident = new Map(processes.map(({ pid, rss }) => [pid, rss]));
50
+ const usage = new Map();
51
+ for (const [session, pids] of labeled) {
52
+ let rssKib = 0;
53
+ for (const pid of pids)
54
+ rssKib += resident.get(pid) ?? 0;
55
+ usage.set(session, { procs: pids.length, rssKib });
56
+ }
57
+ return usage;
58
+ }
59
+ /** `$HOME` as `~`. A path that lies elsewhere, or an unknown home, is left alone. */
60
+ export function shortenHome(path, home) {
61
+ const root = home.endsWith(sep) ? home.slice(0, -sep.length) : home;
62
+ if (root.length === 0)
63
+ return path;
64
+ if (path === root)
65
+ return "~";
66
+ return path.startsWith(`${root}${sep}`) ? `~${path.slice(root.length)}` : path;
67
+ }
68
+ /** KiB as the column shows it: K under a megabyte, M under a gigabyte, then one decimal. */
69
+ export function formatRss(kib) {
70
+ if (kib < 1024)
71
+ return `${kib}K`;
72
+ const mib = kib / 1024;
73
+ if (mib < 1024)
74
+ return `${Math.round(mib)}M`;
75
+ return `${(mib / 1024).toFixed(1)}G`;
76
+ }
77
+ /**
78
+ * One column: its header, how it pads, and where its value comes from. Each column
79
+ * carries its own cell so the header row and the data rows cannot fall out of step.
80
+ */
81
+ const columns = [
82
+ { header: "SESSION", align: "left", cell: ({ session }) => session },
83
+ { header: "A", align: "left", cell: ({ attached }) => (attached ? "*" : "") },
84
+ { header: "BRANCH", align: "left", cell: ({ branch }) => branch },
85
+ { header: "DIRECTORY", align: "left", cell: formatDirectory },
86
+ { header: "PROCS", align: "right", cell: ({ procs }) => String(procs) },
87
+ { header: "RSS", align: "right", cell: ({ rssKib }) => formatRss(rssKib) },
88
+ ];
89
+ /** Empty is not an error: nothing running is a normal answer. */
90
+ const noWorkspaces = "no termwire workspaces";
91
+ /** The table `ls` prints, padded to its own contents. */
92
+ export function formatWorkspaceTable(workspaces, home) {
93
+ if (workspaces.length === 0)
94
+ return `${noWorkspaces}\n`;
95
+ const rows = workspaces.map((workspace) => columns.map(({ cell }) => cell(workspace, home)));
96
+ const widths = columns.map(({ header }, index) => rows.reduce((width, cells) => Math.max(width, cells[index].length), header.length));
97
+ const lines = [columns.map(({ header }) => header), ...rows].map((cells) => formatRow(cells, widths));
98
+ return `${lines.join("\n")}\n`;
99
+ }
100
+ /** The same rows for machines: absolute directories, and `rssKib` in KiB. */
101
+ export function formatWorkspacesJson(workspaces) {
102
+ return `${JSON.stringify(workspaces, null, 2)}\n`;
103
+ }
104
+ function formatDirectory(workspace, home) {
105
+ const directory = shortenHome(workspace.directory, home);
106
+ return workspace.missing ? `${directory} (missing)` : directory;
107
+ }
108
+ function formatRow(cells, widths) {
109
+ return cells
110
+ .map((cell, index) => pad(cell, widths[index], columns[index].align))
111
+ .join(" ")
112
+ .trimEnd();
113
+ }
114
+ function pad(cell, width, align) {
115
+ return align === "right" ? cell.padStart(width) : cell.padEnd(width);
116
+ }
@@ -24,3 +24,18 @@ export declare function prepareWorktree(options: {
24
24
  name: string;
25
25
  branch?: string;
26
26
  }): Promise<string>;
27
+ export interface WorktreeState {
28
+ /** The main checkout, which owns the repository and is never a workspace to remove. */
29
+ main: boolean;
30
+ /** Tracked or untracked changes. Ignored files are not changes, so a `.env` is not. */
31
+ dirty: boolean;
32
+ }
33
+ /**
34
+ * A worktree's own Git directory lives inside the common one, so the two paths are
35
+ * equal only in the main checkout.
36
+ */
37
+ export declare function inspectWorktree(exec: GitExec, path: string): Promise<WorktreeState>;
38
+ /** Removes the worktree and its registration. The branch it held outlives it. */
39
+ export declare function removeWorktree(exec: GitExec, path: string, options: {
40
+ force: boolean;
41
+ }): Promise<void>;