@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.
- package/CHANGELOG.md +84 -0
- package/README.md +66 -0
- package/dist/down.d.ts +40 -0
- package/dist/down.js +99 -0
- package/dist/process-scan-darwin.d.ts +24 -0
- package/dist/process-scan-darwin.js +102 -0
- package/dist/process-scan-linux.d.ts +13 -0
- package/dist/process-scan-linux.js +66 -0
- package/dist/process-scan.d.ts +37 -23
- package/dist/process-scan.js +30 -131
- package/dist/program.d.ts +9 -1
- package/dist/program.js +76 -10
- package/dist/runtime.d.ts +15 -5
- package/dist/runtime.js +22 -4
- package/dist/workspaces.d.ts +45 -0
- package/dist/workspaces.js +116 -0
- package/dist/worktree.d.ts +15 -0
- package/dist/worktree.js +65 -7
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,89 @@
|
|
|
1
1
|
# @termwire/cli
|
|
2
2
|
|
|
3
|
+
## 0.6.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- cfdcc19: `termwire ls` and `termwire down`: the workspaces you have, and a way to put one away.
|
|
8
|
+
|
|
9
|
+
A tool that creates workspaces owes you a way to see them and a way to remove them.
|
|
10
|
+
Until now tearing one down was `tmux kill-session` plus `git worktree remove`, typed
|
|
11
|
+
by hand, and there was nothing at all that answered "what is running where".
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
$ termwire ls
|
|
15
|
+
SESSION A BRANCH DIRECTORY PROCS RSS
|
|
16
|
+
termwire-dev * master ~/projects/termwire 7 1.2G
|
|
17
|
+
termwire-demo demo ~/projects/termwire-demo 4 780M
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
One row per workspace, printed once and then done: `ls` is not a monitor. `A` marks an
|
|
21
|
+
attached session, `BRANCH` is the Git branch of the session directory — a short sha on a
|
|
22
|
+
detached `HEAD`, `-` outside a repository — and `PROCS` and `RSS` count the processes
|
|
23
|
+
still carrying `TERMWIRE_SESSION=<session>`, from the same scan the reap uses, so a
|
|
24
|
+
background agent job is counted as well as a pane. A session whose directory is gone is
|
|
25
|
+
listed and marked `(missing)` rather than crashing the command, and no workspaces prints
|
|
26
|
+
`no termwire workspaces` and exits 0. `--json` prints the same rows for machines, with
|
|
27
|
+
absolute directories.
|
|
28
|
+
|
|
29
|
+
A session counts as a workspace when its tmux session environment carries
|
|
30
|
+
`TERMWIRE_SESSION`, never because its name looks like `<project>-<name>`: you pick the
|
|
31
|
+
name and `up` sets the label, so a session of your own is never listed by its name alone.
|
|
32
|
+
Nothing is read from disk — the list is derived from tmux and Git, so identity stays
|
|
33
|
+
stateless and there is no file to go stale.
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
termwire down dev # kill the workspace session
|
|
37
|
+
termwire down # kill the workspace this shell is in
|
|
38
|
+
termwire down dev -w # and remove the worktree it sits in
|
|
39
|
+
termwire down dev -w --force # even with uncommitted changes
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`down` resolves `[name]` exactly as `up` does, so `up dev` and `down dev` always mean one
|
|
43
|
+
session, and it hunts no processes: the `session-closed` hook already reaps that session.
|
|
44
|
+
|
|
45
|
+
Without a name the target is the workspace the command runs in, read from the inherited
|
|
46
|
+
`TERMWIRE_SESSION` — the same environment-based identity `open` uses. Inside a worktree
|
|
47
|
+
workspace that bare form is the only one that works, because there the Git root is the
|
|
48
|
+
worktree, so `down feat` would look for `<worktree>-feat` and find nothing. Outside a
|
|
49
|
+
workspace a bare `down` fails with `not inside a termwire workspace`.
|
|
50
|
+
|
|
51
|
+
`-w` removes the worktree the session was created in, and refuses the main checkout, the
|
|
52
|
+
directory the command is running in, and a worktree holding uncommitted changes unless
|
|
53
|
+
`--force` is given. A refusal removes nothing at all, the session included. The branch is
|
|
54
|
+
never deleted: a branch outlives its workspace. Ignored files are not uncommitted
|
|
55
|
+
changes, so a worktree carrying only `.env` or `node_modules` counts as clean and is
|
|
56
|
+
removed with them.
|
|
57
|
+
|
|
58
|
+
Tearing down your _own_ workspace with `-w` inverts the order: the worktree is removed
|
|
59
|
+
first and the session killed last, because the kill ends the process that would otherwise
|
|
60
|
+
do the removal — and the command steps out of the worktree before removing it, since a
|
|
61
|
+
spawn from a deleted working directory fails with ENOENT. The refusal to remove the
|
|
62
|
+
directory it runs in does not apply there: the shell standing in it dies with the session
|
|
63
|
+
a moment later.
|
|
64
|
+
|
|
65
|
+
The tmux adapter gained `listSessions` and `showEnvironment` on `createTmux`, and the
|
|
66
|
+
process scan now reports resident memory, so `ProcessEntry` carries `rss` in KiB and one
|
|
67
|
+
walk over the process table answers for every workspace at once.
|
|
68
|
+
|
|
69
|
+
Process scanning also became platform-agnostic above the seam. `process-scan.ts` keeps
|
|
70
|
+
only the `SessionScanner` type and the contract a platform has to honour, while
|
|
71
|
+
`process-scan-darwin.ts` and `process-scan-linux.ts` each take their own dependencies;
|
|
72
|
+
`runtime.ts` picks one. Supporting another platform is a new module plus a branch there,
|
|
73
|
+
and `reap` and `ls` do not change, because they depend on the type.
|
|
74
|
+
|
|
75
|
+
Moving the scanner reshapes `CliRuntime`: it gained `createScanner`, a lazy factory so an
|
|
76
|
+
unsupported platform fails the commands that scan instead of every command, and lost
|
|
77
|
+
`exec`, `host.platform`, `host.uid` and `fs.readdir`, which existed only to feed it. It also
|
|
78
|
+
gained `host.chdir`, and `ProgramDependencies` gained `ls`, `down` and `homedir` — so
|
|
79
|
+
anything that builds a runtime or the command set by hand has to follow.
|
|
80
|
+
|
|
81
|
+
### Patch Changes
|
|
82
|
+
|
|
83
|
+
- Updated dependencies [cfdcc19]
|
|
84
|
+
- @termwire/tmux@0.6.0
|
|
85
|
+
- @termwire/nvim@0.6.0
|
|
86
|
+
|
|
3
87
|
## 0.5.0
|
|
4
88
|
|
|
5
89
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -11,6 +11,8 @@ termwire --help
|
|
|
11
11
|
termwire --version
|
|
12
12
|
termwire up dev
|
|
13
13
|
termwire open src/app.ts:42
|
|
14
|
+
termwire ls
|
|
15
|
+
termwire down dev
|
|
14
16
|
```
|
|
15
17
|
|
|
16
18
|
Workspace identity is stateless. It lives in the environment variables that
|
|
@@ -99,6 +101,70 @@ Git branch names and replaced only in filesystem-safe worktree directory names.
|
|
|
99
101
|
is changed only when `--branch` is present. Existing tmux sessions attach without Git mutations or
|
|
100
102
|
rereading/reconciling configuration.
|
|
101
103
|
|
|
104
|
+
## `ls`
|
|
105
|
+
|
|
106
|
+
```
|
|
107
|
+
SESSION A BRANCH DIRECTORY PROCS RSS
|
|
108
|
+
termwire-dev * master ~/projects/termwire 7 1.2G
|
|
109
|
+
termwire-demo demo ~/projects/termwire-demo 4 780M
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
One row per workspace on this machine, printed once: `ls` is not a monitor. `A`
|
|
113
|
+
marks an attached session. `DIRECTORY` is where the session was created, with
|
|
114
|
+
`$HOME` shortened to `~`; a directory that is gone is marked `(missing)` rather
|
|
115
|
+
than fatal. `BRANCH` is the Git branch there, a short sha on a detached `HEAD`,
|
|
116
|
+
or `-` outside a repository. `PROCS` and `RSS` count the processes still carrying
|
|
117
|
+
`TERMWIRE_SESSION=<session>` and their resident memory, from the same scan the
|
|
118
|
+
reap uses, so they cover background jobs and not just panes.
|
|
119
|
+
|
|
120
|
+
A session counts as a workspace when its tmux session environment carries
|
|
121
|
+
`TERMWIRE_SESSION`, never because its name looks like `<project>-<name>`. The
|
|
122
|
+
user picks the name and `up` sets the label, so a session of your own is never
|
|
123
|
+
listed by its name alone. Nothing is read from disk: the list comes from tmux and
|
|
124
|
+
Git, so there is no state file to go stale.
|
|
125
|
+
|
|
126
|
+
No workspaces prints `no termwire workspaces` and exits 0. `--json` prints the
|
|
127
|
+
same rows for machines, with absolute directories and `rssKib` in KiB.
|
|
128
|
+
|
|
129
|
+
## `down`
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
termwire down dev # kill the workspace session
|
|
133
|
+
termwire down # kill the workspace this shell is in
|
|
134
|
+
termwire down dev -w # and remove the worktree it sits in
|
|
135
|
+
termwire down dev -w --force # even with uncommitted changes
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
`[name]` resolves exactly as it does for `up`, so `up dev` and `down dev` always
|
|
139
|
+
mean one session. `down` kills it and hunts no processes: the `session-closed`
|
|
140
|
+
hook already runs the reap for exactly that session.
|
|
141
|
+
|
|
142
|
+
Without a name the target is the workspace the command runs in, read from the
|
|
143
|
+
inherited `TERMWIRE_SESSION`; outside a workspace it fails with `not inside a
|
|
144
|
+
termwire workspace`. Inside a **worktree** workspace this bare form is the only
|
|
145
|
+
one that works: there the Git root is the worktree itself, so `down <name>` would
|
|
146
|
+
build `<worktree>-<name>` and find no such session.
|
|
147
|
+
|
|
148
|
+
`-w` removes the worktree the session was created in, as tmux reports it, and
|
|
149
|
+
refuses the main checkout, the directory you are standing in, and a worktree
|
|
150
|
+
holding uncommitted changes unless `--force` is given. A refusal removes nothing
|
|
151
|
+
at all, the session included. The branch is never deleted: a branch outlives its
|
|
152
|
+
workspace.
|
|
153
|
+
|
|
154
|
+
Ignored files are not uncommitted changes, so a worktree carrying only `.env` or
|
|
155
|
+
`node_modules` counts as clean and `git worktree remove` deletes them with it. A
|
|
156
|
+
symlinked `.env` is unlinked, leaving the file it points at alone; a real copy is
|
|
157
|
+
gone for good, because Git never had it.
|
|
158
|
+
|
|
159
|
+
Tearing down **your own** workspace with `-w` inverts the order: the worktree is
|
|
160
|
+
removed first and the session killed last. The kill takes this process with it,
|
|
161
|
+
so a removal after it would never run, and a spawn from a deleted working
|
|
162
|
+
directory fails — the command steps out of the worktree before removing it. The
|
|
163
|
+
usual refusal to remove the directory it runs in does not apply here, because the
|
|
164
|
+
shell standing there dies with the session a moment later.
|
|
165
|
+
|
|
166
|
+
An unknown session fails with `no workspace session named <project>-<name>`.
|
|
167
|
+
|
|
102
168
|
## Session cleanup
|
|
103
169
|
|
|
104
170
|
`up` installs one global tmux hook, `session-closed`, that runs a hidden
|
package/dist/down.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { WorktreeState } from "./worktree.js";
|
|
2
|
+
export interface DownRequest {
|
|
3
|
+
/** Omitted inside a workspace, where the inherited label names the session. */
|
|
4
|
+
name?: string;
|
|
5
|
+
worktree?: true;
|
|
6
|
+
force?: true;
|
|
7
|
+
}
|
|
8
|
+
export interface DownResult {
|
|
9
|
+
session: string;
|
|
10
|
+
/** Present only when a worktree was removed. */
|
|
11
|
+
worktree?: string;
|
|
12
|
+
}
|
|
13
|
+
/** The fields of a tmux session this command reads, as the adapter reports them. */
|
|
14
|
+
export interface DownSession {
|
|
15
|
+
name: string;
|
|
16
|
+
path: string;
|
|
17
|
+
}
|
|
18
|
+
export interface DownDependencies {
|
|
19
|
+
cwd: () => string;
|
|
20
|
+
/** Called before this command's own directory is removed from under it. */
|
|
21
|
+
chdir: (path: string) => void;
|
|
22
|
+
env: Record<string, string | undefined>;
|
|
23
|
+
findGitRoot: (cwd: string) => Promise<string | undefined>;
|
|
24
|
+
listSessions: () => Promise<DownSession[]>;
|
|
25
|
+
killSession: (session: string) => Promise<void>;
|
|
26
|
+
inspectWorktree: (path: string) => Promise<WorktreeState>;
|
|
27
|
+
removeWorktree: (path: string, options: {
|
|
28
|
+
force: boolean;
|
|
29
|
+
}) => Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Teardown. A name goes through `createIdentity`, so `up foo` and `down foo` always
|
|
33
|
+
* mean one session; without a name the inherited `TERMWIRE_SESSION` names it, which is
|
|
34
|
+
* how a workspace tears itself down from the inside. The tmux listing knows where it
|
|
35
|
+
* lives.
|
|
36
|
+
*
|
|
37
|
+
* Processes are not hunted here: the global `session-closed` hook `up` installs runs
|
|
38
|
+
* `_reap` for exactly that.
|
|
39
|
+
*/
|
|
40
|
+
export declare function down(request: DownRequest, { cwd, chdir, env, findGitRoot, listSessions, killSession, inspectWorktree, removeWorktree, }: DownDependencies): Promise<DownResult>;
|
package/dist/down.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { dirname, resolve, sep } from "node:path";
|
|
2
|
+
import { createIdentity } from "./identity.js";
|
|
3
|
+
import { sessionVariable } from "./process-scan.js";
|
|
4
|
+
/**
|
|
5
|
+
* Teardown. A name goes through `createIdentity`, so `up foo` and `down foo` always
|
|
6
|
+
* mean one session; without a name the inherited `TERMWIRE_SESSION` names it, which is
|
|
7
|
+
* how a workspace tears itself down from the inside. The tmux listing knows where it
|
|
8
|
+
* lives.
|
|
9
|
+
*
|
|
10
|
+
* Processes are not hunted here: the global `session-closed` hook `up` installs runs
|
|
11
|
+
* `_reap` for exactly that.
|
|
12
|
+
*/
|
|
13
|
+
export async function down(request, { cwd, chdir, env, findGitRoot, listSessions, killSession, inspectWorktree, removeWorktree, }) {
|
|
14
|
+
const directory = cwd();
|
|
15
|
+
const target = await resolveSession(request, { cwd: directory, env, findGitRoot });
|
|
16
|
+
const sessions = await listSessions();
|
|
17
|
+
const session = sessions.find((entry) => entry.name === target);
|
|
18
|
+
if (session === undefined) {
|
|
19
|
+
throw new Error(`no workspace session named ${target}`);
|
|
20
|
+
}
|
|
21
|
+
if (request.worktree !== true) {
|
|
22
|
+
await killSession(target);
|
|
23
|
+
return { session: target };
|
|
24
|
+
}
|
|
25
|
+
/** Whether the session being torn down is the one this command is running in. */
|
|
26
|
+
const ownSession = env[sessionVariable]?.trim() === target;
|
|
27
|
+
const force = request.force === true;
|
|
28
|
+
// Everything is refused before anything is destroyed, so a refusal leaves the
|
|
29
|
+
// session running and the worktree untouched.
|
|
30
|
+
await assertRemovable({ path: session.path, cwd: directory, force, ownSession, inspectWorktree });
|
|
31
|
+
if (ownSession) {
|
|
32
|
+
// The kill ends this process with its pane, so it goes last. And the kill is a
|
|
33
|
+
// spawn, which fails with ENOENT from a deleted working directory, so step out of
|
|
34
|
+
// the worktree first; the parent of a worktree always outlives it.
|
|
35
|
+
if (contains(session.path, directory))
|
|
36
|
+
chdir(dirname(session.path));
|
|
37
|
+
await removeWorktree(session.path, { force });
|
|
38
|
+
await killSession(target);
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
// Nothing of ours dies here, so the processes go first and their files after them.
|
|
42
|
+
await killSession(target);
|
|
43
|
+
await removeKilledWorktree({ session: target, path: session.path, force, removeWorktree });
|
|
44
|
+
}
|
|
45
|
+
return { session: target, worktree: session.path };
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A name is resolved from the current directory, exactly as `up` resolves it. Without
|
|
49
|
+
* one, the session is the workspace this command is running in, which is the only way
|
|
50
|
+
* to name a worktree session from inside it: there the Git root is the worktree, so
|
|
51
|
+
* `createIdentity` would build `<worktree>-<name>` and find nothing.
|
|
52
|
+
*/
|
|
53
|
+
async function resolveSession(request, { cwd, env, findGitRoot }) {
|
|
54
|
+
if (request.name === undefined) {
|
|
55
|
+
const session = env[sessionVariable]?.trim();
|
|
56
|
+
if (!session) {
|
|
57
|
+
throw new Error("not inside a termwire workspace");
|
|
58
|
+
}
|
|
59
|
+
return session;
|
|
60
|
+
}
|
|
61
|
+
const gitRoot = await findGitRoot(cwd);
|
|
62
|
+
return createIdentity({ cwd, gitRoot, name: request.name }).session;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The session is already gone by the time the worktree is removed, so a failure here
|
|
66
|
+
* says so: `down` cannot be retried for a session that no longer exists, and the user
|
|
67
|
+
* needs to know that `git worktree remove` is what is left to do.
|
|
68
|
+
*/
|
|
69
|
+
async function removeKilledWorktree({ session, path, force, removeWorktree, }) {
|
|
70
|
+
try {
|
|
71
|
+
await removeWorktree(path, { force });
|
|
72
|
+
}
|
|
73
|
+
catch (cause) {
|
|
74
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
75
|
+
throw new Error(`session ${session} was killed, but its worktree was not removed: ${message}`, {
|
|
76
|
+
cause,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
async function assertRemovable({ path, cwd, force, ownSession, inspectWorktree, }) {
|
|
81
|
+
// Sawing off the branch you stand on, unless the shell standing there is itself part
|
|
82
|
+
// of what is being torn down: it dies with the session a moment later.
|
|
83
|
+
if (!ownSession && contains(path, cwd)) {
|
|
84
|
+
throw new Error(`refusing to remove the directory this command runs in: ${path}`);
|
|
85
|
+
}
|
|
86
|
+
const state = await inspectWorktree(path);
|
|
87
|
+
if (state.main) {
|
|
88
|
+
throw new Error(`refusing to remove the main checkout: ${path}`);
|
|
89
|
+
}
|
|
90
|
+
if (state.dirty && !force) {
|
|
91
|
+
throw new Error(`${path} has uncommitted changes: pass --force to remove it anyway`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** Whether `inner` is `outer` itself or lies below it. */
|
|
95
|
+
function contains(outer, inner) {
|
|
96
|
+
const base = resolve(outer);
|
|
97
|
+
const nested = resolve(inner);
|
|
98
|
+
return nested === base || nested.startsWith(`${base}${sep}`);
|
|
99
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Exec } from "./exec.js";
|
|
2
|
+
import { type ProcessEntry, type SessionScanner } from "./process-scan.js";
|
|
3
|
+
export interface DarwinScanDependencies {
|
|
4
|
+
exec: Exec;
|
|
5
|
+
uid: number;
|
|
6
|
+
}
|
|
7
|
+
export interface DarwinProcessRow extends ProcessEntry {
|
|
8
|
+
/** The command line, followed by the environment when `ps -E` could read it. */
|
|
9
|
+
details: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function parseDarwinProcesses(stdout: string): DarwinProcessRow[];
|
|
12
|
+
export declare function parseDarwinArguments(stdout: string): Map<number, string>;
|
|
13
|
+
/**
|
|
14
|
+
* True when `text` assigns `needle`, meaning the match is a whole space-separated
|
|
15
|
+
* token. A command line that merely mentions the variable never qualifies.
|
|
16
|
+
*/
|
|
17
|
+
export declare function containsAssignment(text: string, needle: string): boolean;
|
|
18
|
+
/**
|
|
19
|
+
* macOS has no `/proc`, so the environment comes from `ps -E`, which appends it to
|
|
20
|
+
* the command column. A process that only mentions the label on its command line
|
|
21
|
+
* would look identical, so every candidate is re-read without `-E` and the command
|
|
22
|
+
* line is stripped off before the label is looked up in what remains.
|
|
23
|
+
*/
|
|
24
|
+
export declare function createDarwinScanner(dependencies: DarwinScanDependencies): SessionScanner;
|
|
@@ -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
|
+
}
|
package/dist/process-scan.d.ts
CHANGED
|
@@ -1,8 +1,31 @@
|
|
|
1
|
-
|
|
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
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
|
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
|
-
*
|
|
35
|
-
*
|
|
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
|
|
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;
|