@termwire/cli 0.2.2 → 0.4.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 +72 -0
- package/README.md +105 -15
- package/dist/bin/termwire.d.ts +1 -1
- package/dist/bin/termwire.js +3 -3
- package/dist/branch.d.ts +1 -1
- package/dist/config-loader.d.ts +1 -1
- package/dist/config-validation.d.ts +2 -2
- package/dist/config-validation.js +1 -1
- package/dist/exec.d.ts +7 -0
- package/dist/exec.js +22 -0
- package/dist/index.d.ts +17 -7
- package/dist/index.js +9 -4
- package/dist/layout.d.ts +1 -1
- package/dist/open.d.ts +27 -0
- package/dist/open.js +45 -0
- package/dist/process-scan.d.ts +37 -0
- package/dist/process-scan.js +138 -0
- package/dist/program.d.ts +37 -2
- package/dist/program.js +161 -20
- package/dist/reap-hook.d.ts +41 -0
- package/dist/reap-hook.js +76 -0
- package/dist/reap.d.ts +47 -0
- package/dist/reap.js +117 -0
- package/dist/up.d.ts +5 -3
- package/dist/up.js +12 -1
- package/dist/worktree.js +1 -1
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,77 @@
|
|
|
1
1
|
# @termwire/cli
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 7e73a29: Closing a workspace session now kills the processes started in it.
|
|
8
|
+
|
|
9
|
+
`tmux kill-session` only sends `SIGHUP` to the foreground process group of each
|
|
10
|
+
pane, so background agent jobs detached from the terminal survived it and were
|
|
11
|
+
adopted by `init`. They accumulated for weeks, in one case 158 processes across
|
|
12
|
+
nine abandoned sessions, five of whose worktrees no longer existed on disk.
|
|
13
|
+
|
|
14
|
+
`up` now installs one global tmux `session-closed` hook that runs a hidden
|
|
15
|
+
`termwire _reap <session>` subcommand. The reap collects the processes of the
|
|
16
|
+
current user whose environment still carries `TERMWIRE_SESSION=<session>`, sends
|
|
17
|
+
`SIGTERM`, then confirms the survivors still carry the label before escalating
|
|
18
|
+
them to `SIGKILL`. It signals exactly that list of pids and never a pattern
|
|
19
|
+
match, and never the tmux server or anything it descends from. Each run appends
|
|
20
|
+
one line to `$XDG_STATE_HOME/termwire/reap.log`, because a tmux hook's output is
|
|
21
|
+
shown nowhere.
|
|
22
|
+
|
|
23
|
+
Installing the hook is idempotent. A repeated `up` updates our entry when the
|
|
24
|
+
interpreter or script path changed, drops duplicates of ours, and leaves a
|
|
25
|
+
`session-closed` hook of your own untouched. A tmux server that refuses the hook
|
|
26
|
+
only produces a warning; the workspace still comes up.
|
|
27
|
+
|
|
28
|
+
`@termwire/tmux` gains `showHooks`, `setHook`, and `unsetHook`. It keeps no
|
|
29
|
+
knowledge of what the hooks are for.
|
|
30
|
+
|
|
31
|
+
### Patch Changes
|
|
32
|
+
|
|
33
|
+
- Updated dependencies [7e73a29]
|
|
34
|
+
- @termwire/tmux@0.4.0
|
|
35
|
+
- @termwire/nvim@0.4.0
|
|
36
|
+
|
|
37
|
+
## 0.3.0
|
|
38
|
+
|
|
39
|
+
### Minor Changes
|
|
40
|
+
|
|
41
|
+
- f57c480: Run on Node instead of requiring Bun. Every package now spawns through
|
|
42
|
+
`node:child_process`, emits explicit `.js` extensions on relative imports, and
|
|
43
|
+
ships a `#!/usr/bin/env node` entry point. `engines` declares `node >=22.12.0`,
|
|
44
|
+
the floor set by Commander 15.
|
|
45
|
+
|
|
46
|
+
The published CLI and MCP server previously failed under Node with
|
|
47
|
+
`ERR_MODULE_NOT_FOUND` and had no test covering it. `bun run verify:node`
|
|
48
|
+
executes both built artifacts under Node, and CI runs it on every push.
|
|
49
|
+
|
|
50
|
+
This makes `npx -y @termwire/mcp` the recommended MCP registration. Unlike
|
|
51
|
+
`bunx`, the `npx` cache lives under `~/.npm` and is not swept by the nightly
|
|
52
|
+
macOS temporary-directory cleanup that silently broke the server.
|
|
53
|
+
|
|
54
|
+
Emitted type declarations are now typed against `@types/node` alone and no
|
|
55
|
+
longer reference Bun types.
|
|
56
|
+
|
|
57
|
+
The repository is still developed with Bun. Only the published output changed.
|
|
58
|
+
|
|
59
|
+
- f57c480: Add the `termwire open <target>` command, which opens a file in the workspace
|
|
60
|
+
Neovim and focuses the editor pane. A trailing `:<line>` selects a line, and
|
|
61
|
+
`--line` keeps the target verbatim for filenames that end in a colon and
|
|
62
|
+
digits. This gives any agent that can run a shell command the same capability
|
|
63
|
+
as the MCP server and the OpenCode plugin, with nothing to configure.
|
|
64
|
+
|
|
65
|
+
Correct the OpenCode plugin's out-of-workspace error to `not inside a termwire
|
|
66
|
+
workspace`, matching the CLI and the MCP server.
|
|
67
|
+
|
|
68
|
+
### Patch Changes
|
|
69
|
+
|
|
70
|
+
- Updated dependencies [f57c480]
|
|
71
|
+
- Updated dependencies [f57c480]
|
|
72
|
+
- @termwire/nvim@0.3.0
|
|
73
|
+
- @termwire/tmux@0.3.0
|
|
74
|
+
|
|
3
75
|
## 0.2.2
|
|
4
76
|
|
|
5
77
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -1,25 +1,23 @@
|
|
|
1
1
|
# @termwire/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The `termwire` command. It creates tmux workspaces with a Neovim RPC socket and
|
|
4
|
+
opens files in the workspace editor.
|
|
5
|
+
|
|
6
|
+
Requires Node >=22.12, tmux >=3.2, and Neovim >=0.9. It runs on Bun as well.
|
|
4
7
|
|
|
5
8
|
```bash
|
|
6
|
-
|
|
9
|
+
npm install -g @termwire/cli
|
|
7
10
|
termwire --help
|
|
8
11
|
termwire up dev
|
|
12
|
+
termwire open src/app.ts:42
|
|
9
13
|
```
|
|
10
14
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
## Why it exists
|
|
17
|
-
|
|
18
|
-
This is the tool that removes manual tmux/editor setup: bring up a stateless
|
|
19
|
-
workspace with a single command. The CLI owns `up <name>` only; file opening is
|
|
20
|
-
the explicit `termwire_open({ path, line? })` OpenCode plugin tool.
|
|
15
|
+
Workspace identity is stateless. It lives in the environment variables that
|
|
16
|
+
`termwire up <name>` exports into every pane, never in a file on disk. Layout
|
|
17
|
+
configuration is optional JSONC read when a session is created; it is not
|
|
18
|
+
workspace state.
|
|
21
19
|
|
|
22
|
-
##
|
|
20
|
+
## `up`
|
|
23
21
|
|
|
24
22
|
| Command | Workspace | Branch |
|
|
25
23
|
| --- | --- | --- |
|
|
@@ -37,6 +35,88 @@ Git branch names and replaced only in filesystem-safe worktree directory names.
|
|
|
37
35
|
is changed only when `--branch` is present. Existing tmux sessions attach without Git mutations or
|
|
38
36
|
rereading/reconciling configuration.
|
|
39
37
|
|
|
38
|
+
## Session cleanup
|
|
39
|
+
|
|
40
|
+
`up` installs one global tmux hook, `session-closed`, that runs a hidden
|
|
41
|
+
`termwire _reap <session>` for the session that just closed. Without it,
|
|
42
|
+
processes started in a workspace outlive `tmux kill-session`: tmux only sends
|
|
43
|
+
`SIGHUP` to the foreground process group of each pane, so a background agent job
|
|
44
|
+
detached from the terminal is adopted by `init` and keeps running for weeks.
|
|
45
|
+
|
|
46
|
+
The reap finds every process of the current user whose environment still carries
|
|
47
|
+
`TERMWIRE_SESSION=<session>` (from `ps -E` on macOS, from `/proc` on Linux),
|
|
48
|
+
sends `SIGTERM`, waits two seconds, confirms the survivors still carry the label,
|
|
49
|
+
then escalates them to `SIGKILL`. It signals that list of pids and nothing else,
|
|
50
|
+
never a pattern match. The tmux server and everything it descends from are never
|
|
51
|
+
signalled, even when the server's own environment carries the label.
|
|
52
|
+
|
|
53
|
+
Each run appends one line to `$XDG_STATE_HOME/termwire/reap.log`, defaulting to
|
|
54
|
+
`~/.local/state/termwire/reap.log`, because a tmux hook's output is not shown
|
|
55
|
+
anywhere. The reap inherits the tmux server's environment, so `XDG_STATE_HOME`
|
|
56
|
+
is read as the server saw it when it started, not as your current shell exports
|
|
57
|
+
it. The log is never rotated; it gains one line per session close.
|
|
58
|
+
|
|
59
|
+
Installing the hook is idempotent: a repeated `up` updates our entry when the
|
|
60
|
+
interpreter or script path changed, drops duplicates of ours, and leaves any
|
|
61
|
+
`session-closed` hook you configured yourself in place. When the tmux server
|
|
62
|
+
refuses the hook, `up` warns and still brings the workspace up.
|
|
63
|
+
|
|
64
|
+
Two things escape the reap. A process that clears or rewrites its own
|
|
65
|
+
environment no longer carries the label, and on macOS the kernel hides the
|
|
66
|
+
environment of Apple's own signed binaries, so a bare `sleep` started in a pane
|
|
67
|
+
is invisible to `ps -E` while a `node` or `pnpm` process is not. Everything that
|
|
68
|
+
does carry the label is killed, including processes you started in the session
|
|
69
|
+
yourself; for a session you are closing, that is the point.
|
|
70
|
+
|
|
71
|
+
One false positive is possible on macOS, where `ps -E` flattens the environment
|
|
72
|
+
into a single line: a process holding `TERMWIRE_SESSION=<session>` inside the
|
|
73
|
+
*value* of another variable, a captured command line for instance, is
|
|
74
|
+
indistinguishable from one that carries the label itself. Linux reads `/proc`
|
|
75
|
+
and matches exactly.
|
|
76
|
+
|
|
77
|
+
The hook records the absolute path of the interpreter and script that installed
|
|
78
|
+
it, and the next `up` rewrites it when either moved. A path that disappears
|
|
79
|
+
without a further `up`, after `npx` prunes its cache for example, leaves a hook
|
|
80
|
+
that silently does nothing. Remove it by index:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
tmux show-hooks -g | grep TERMWIRE_REAP_HOOK # e.g. session-closed[1]
|
|
84
|
+
tmux set-hook -gu 'session-closed[1]'
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## `open`
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
termwire open <target>
|
|
91
|
+
termwire open <target> --line <number>
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Opens a file in the Neovim of the current workspace and focuses the editor
|
|
95
|
+
pane. A trailing `:<line>` in the target selects a line, so `src/app.ts:42`
|
|
96
|
+
opens line 42. With `--line`, the target is used verbatim, which is the way to
|
|
97
|
+
open a file whose name ends in a colon and digits. Relative paths resolve from
|
|
98
|
+
the current directory. On success the command prints the absolute path it
|
|
99
|
+
opened.
|
|
100
|
+
|
|
101
|
+
| Invocation | Opens |
|
|
102
|
+
| --- | --- |
|
|
103
|
+
| `termwire open src/app.ts` | `src/app.ts`, no line jump |
|
|
104
|
+
| `termwire open src/app.ts:42` | `src/app.ts` at line 42 |
|
|
105
|
+
| `termwire open src/app.ts -l 42` | `src/app.ts` at line 42 |
|
|
106
|
+
| `termwire open weird:42 -l 7` | the file named `weird:42`, at line 7 |
|
|
107
|
+
|
|
108
|
+
The command reads `TERMWIRE_SOCKET` and `TERMWIRE_EDITOR_PANE` from its
|
|
109
|
+
environment, so it works only in a shell created by `termwire up`. Errors are
|
|
110
|
+
reported without a stack trace:
|
|
111
|
+
|
|
112
|
+
- `not inside a termwire workspace`: `TERMWIRE_SOCKET` is missing.
|
|
113
|
+
- `nvim is not responding on socket ...`: the workspace Neovim is gone.
|
|
114
|
+
- `line must be a positive integer`, `path must not be empty`: bad target.
|
|
115
|
+
|
|
116
|
+
Pane focus is skipped when `TERMWIRE_EDITOR_PANE` is absent; opening still
|
|
117
|
+
succeeds. This is what makes the command useful to a coding agent: it needs no
|
|
118
|
+
integration beyond permission to run a shell command.
|
|
119
|
+
|
|
40
120
|
## Layout configuration
|
|
41
121
|
|
|
42
122
|
TermWire discovers optional JSONC files in this order:
|
|
@@ -308,8 +388,12 @@ while preserving the original failure.
|
|
|
308
388
|
- The default layout does not start OpenCode automatically. Users may start it manually in an
|
|
309
389
|
ordinary shell pane, or configure `["opencode"]` as a pane command. They may also reshape the
|
|
310
390
|
workspace with tmux after creation.
|
|
311
|
-
-
|
|
312
|
-
|
|
391
|
+
- Closing a workspace session kills the processes it started, through the global
|
|
392
|
+
tmux `session-closed` hook that `up` installs.
|
|
393
|
+
- `open <target>` resolves the path, checks that Neovim answers on the socket,
|
|
394
|
+
opens the file, then focuses the editor pane when one is known.
|
|
395
|
+
- The CLI does not need to be in `PATH` for the MCP server or the OpenCode
|
|
396
|
+
plugin. Both compose the nvim and tmux adapters directly.
|
|
313
397
|
|
|
314
398
|
## Dependencies
|
|
315
399
|
|
|
@@ -318,3 +402,9 @@ Zod 4 provides strict structural config validation. All three are direct runtime
|
|
|
318
402
|
dependencies.
|
|
319
403
|
`@termwire/tmux` and `@termwire/nvim` are thin adapters over their binaries;
|
|
320
404
|
the CLI owns workspace policy and orchestration.
|
|
405
|
+
|
|
406
|
+
## Alternatives for opening files
|
|
407
|
+
|
|
408
|
+
`@termwire/mcp` exposes the same open operation as an MCP tool and
|
|
409
|
+
`@termwire/opencode-plugin` as a native OpenCode tool. They exist for agents
|
|
410
|
+
that should not run shell commands. Configure one of the three, not several.
|
package/dist/bin/termwire.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
#!/usr/bin/env
|
|
1
|
+
#!/usr/bin/env node
|
|
2
2
|
export {};
|
package/dist/bin/termwire.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
#!/usr/bin/env
|
|
2
|
-
import { run } from "../index";
|
|
3
|
-
process.exitCode = await run(
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { run } from "../index.js";
|
|
3
|
+
process.exitCode = await run(process.argv.slice(2));
|
package/dist/branch.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import type { GitExec } from "./worktree";
|
|
1
|
+
import type { GitExec } from "./worktree.js";
|
|
2
2
|
export declare function prepareBranch(exec: GitExec, cwd: string, name: string): Promise<void>;
|
package/dist/config-loader.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { type LayoutConfig } from "./config-schema";
|
|
2
|
-
import type { LoadedConfig } from "./config-types";
|
|
1
|
+
import { type LayoutConfig } from "./config-schema.js";
|
|
2
|
+
import type { LoadedConfig } from "./config-types.js";
|
|
3
3
|
export declare function resolveLayout(globalConfig?: LoadedConfig, projectConfig?: LoadedConfig): LayoutConfig;
|
package/dist/exec.d.ts
ADDED
package/dist/exec.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
export async function spawnCapture(argv) {
|
|
3
|
+
const [command, ...args] = argv;
|
|
4
|
+
if (command === undefined) {
|
|
5
|
+
throw new Error("command must not be empty");
|
|
6
|
+
}
|
|
7
|
+
return await new Promise((resolve, reject) => {
|
|
8
|
+
const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
9
|
+
let stdout = "";
|
|
10
|
+
let stderr = "";
|
|
11
|
+
child.stdout.setEncoding("utf8").on("data", (chunk) => {
|
|
12
|
+
stdout += chunk;
|
|
13
|
+
});
|
|
14
|
+
child.stderr.setEncoding("utf8").on("data", (chunk) => {
|
|
15
|
+
stderr += chunk;
|
|
16
|
+
});
|
|
17
|
+
child.once("error", reject);
|
|
18
|
+
child.once("close", (code) => {
|
|
19
|
+
resolve({ exitCode: code ?? 1, stdout, stderr });
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,17 @@
|
|
|
1
|
-
export { prepareBranch } from "./branch";
|
|
2
|
-
export type {
|
|
3
|
-
export {
|
|
4
|
-
export type {
|
|
5
|
-
export {
|
|
6
|
-
export type {
|
|
7
|
-
export {
|
|
1
|
+
export { prepareBranch } from "./branch.js";
|
|
2
|
+
export type { Exec, ExecResult } from "./exec.js";
|
|
3
|
+
export { spawnCapture } from "./exec.js";
|
|
4
|
+
export type { NvimClient, OpenDependencies, OpenRequest, OpenResult, TmuxClient, } from "./open.js";
|
|
5
|
+
export { open, parseTarget } from "./open.js";
|
|
6
|
+
export type { DarwinProcessRow, DarwinScanDependencies, LinuxScanDependencies, ProcessEntry, ProcessScan, ProcessScanner, ProcessScannerDependencies, } from "./process-scan.js";
|
|
7
|
+
export { containsAssignment, createProcessScanner, parseDarwinArguments, parseDarwinProcesses, parseLinuxPpid, sessionVariable, } from "./process-scan.js";
|
|
8
|
+
export type { ProgramDependencies, RuntimeDependencies, RuntimeOpenDependencies, RuntimeReapDependencies, } from "./program.js";
|
|
9
|
+
export { createProgram, createRuntimeOpen, createRuntimeReap, createRuntimeUp, executeGit, killProcess, removeStaleSocket, run, } from "./program.js";
|
|
10
|
+
export type { KillOutcome, ReapDependencies, ReapReport, ReapSignal } from "./reap.js";
|
|
11
|
+
export { formatReapFailure, formatReapReport, protectedPids, reapLogPath, reapSession, selectTargets, } from "./reap.js";
|
|
12
|
+
export type { ReapHookOutcome, ReapHookPaths, ReapHookTmux } from "./reap-hook.js";
|
|
13
|
+
export { createReapHookCommand, ensureReapHook, reapCommandName, reapHookMarker, reapHookName, } from "./reap-hook.js";
|
|
14
|
+
export type { UpDependencies, UpRequest } from "./up.js";
|
|
15
|
+
export { up } from "./up.js";
|
|
16
|
+
export type { GitExec, WorktreeEntry } from "./worktree.js";
|
|
17
|
+
export { findGitRoot, parseWorktreeList, prepareWorktree } from "./worktree.js";
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
export { prepareBranch } from "./branch";
|
|
2
|
-
export {
|
|
3
|
-
export {
|
|
4
|
-
export {
|
|
1
|
+
export { prepareBranch } from "./branch.js";
|
|
2
|
+
export { spawnCapture } from "./exec.js";
|
|
3
|
+
export { open, parseTarget } from "./open.js";
|
|
4
|
+
export { containsAssignment, createProcessScanner, parseDarwinArguments, parseDarwinProcesses, parseLinuxPpid, sessionVariable, } from "./process-scan.js";
|
|
5
|
+
export { createProgram, createRuntimeOpen, createRuntimeReap, createRuntimeUp, executeGit, killProcess, removeStaleSocket, run, } from "./program.js";
|
|
6
|
+
export { formatReapFailure, formatReapReport, protectedPids, reapLogPath, reapSession, selectTargets, } from "./reap.js";
|
|
7
|
+
export { createReapHookCommand, ensureReapHook, reapCommandName, reapHookMarker, reapHookName, } from "./reap-hook.js";
|
|
8
|
+
export { up } from "./up.js";
|
|
9
|
+
export { findGitRoot, parseWorktreeList, prepareWorktree } from "./worktree.js";
|
package/dist/layout.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { createTmux } from "@termwire/tmux";
|
|
2
|
-
import type { LayoutConfig } from "./config-schema";
|
|
2
|
+
import type { LayoutConfig } from "./config-schema.js";
|
|
3
3
|
export declare function createLayout(options: {
|
|
4
4
|
tmux: ReturnType<typeof createTmux>;
|
|
5
5
|
session: string;
|
package/dist/open.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export interface OpenRequest {
|
|
2
|
+
target: string;
|
|
3
|
+
line?: string;
|
|
4
|
+
}
|
|
5
|
+
export interface OpenResult {
|
|
6
|
+
path: string;
|
|
7
|
+
line?: number;
|
|
8
|
+
}
|
|
9
|
+
export interface NvimClient {
|
|
10
|
+
isRunning(socket: string): Promise<boolean>;
|
|
11
|
+
openFile(socket: string, path: string, line?: number): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
export interface TmuxClient {
|
|
14
|
+
selectWindow(target: string): Promise<void>;
|
|
15
|
+
selectPane(pane: string): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
export interface OpenDependencies {
|
|
18
|
+
cwd: () => string;
|
|
19
|
+
env: Record<string, string | undefined>;
|
|
20
|
+
nvim: NvimClient;
|
|
21
|
+
tmux: TmuxClient;
|
|
22
|
+
}
|
|
23
|
+
export declare function parseTarget(target: string, line?: string): {
|
|
24
|
+
path: string;
|
|
25
|
+
line?: number;
|
|
26
|
+
};
|
|
27
|
+
export declare function open(request: OpenRequest, dependencies: OpenDependencies): Promise<OpenResult>;
|
package/dist/open.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
const lineSuffix = /^(.+):(\d+)$/;
|
|
3
|
+
function parseLine(value) {
|
|
4
|
+
const trimmed = value.trim();
|
|
5
|
+
if (!/^\d+$/.test(trimmed) || Number(trimmed) < 1) {
|
|
6
|
+
throw new Error("line must be a positive integer");
|
|
7
|
+
}
|
|
8
|
+
return Number(trimmed);
|
|
9
|
+
}
|
|
10
|
+
export function parseTarget(target, line) {
|
|
11
|
+
const trimmed = target.trim();
|
|
12
|
+
if (trimmed === "") {
|
|
13
|
+
throw new Error("path must not be empty");
|
|
14
|
+
}
|
|
15
|
+
if (line !== undefined) {
|
|
16
|
+
return { path: trimmed, line: parseLine(line) };
|
|
17
|
+
}
|
|
18
|
+
const match = lineSuffix.exec(trimmed);
|
|
19
|
+
if (!match) {
|
|
20
|
+
return { path: trimmed };
|
|
21
|
+
}
|
|
22
|
+
const [, path, suffix] = match;
|
|
23
|
+
if (path === undefined || suffix === undefined) {
|
|
24
|
+
return { path: trimmed };
|
|
25
|
+
}
|
|
26
|
+
return { path, line: parseLine(suffix) };
|
|
27
|
+
}
|
|
28
|
+
export async function open(request, dependencies) {
|
|
29
|
+
const parsed = parseTarget(request.target, request.line);
|
|
30
|
+
const socket = dependencies.env.TERMWIRE_SOCKET?.trim();
|
|
31
|
+
const editorPane = dependencies.env.TERMWIRE_EDITOR_PANE?.trim();
|
|
32
|
+
if (!socket) {
|
|
33
|
+
throw new Error("not inside a termwire workspace");
|
|
34
|
+
}
|
|
35
|
+
const path = resolve(dependencies.cwd(), parsed.path);
|
|
36
|
+
if (!(await dependencies.nvim.isRunning(socket))) {
|
|
37
|
+
throw new Error(`nvim is not responding on socket ${socket}`);
|
|
38
|
+
}
|
|
39
|
+
await dependencies.nvim.openFile(socket, path, parsed.line);
|
|
40
|
+
if (editorPane) {
|
|
41
|
+
await dependencies.tmux.selectWindow(editorPane);
|
|
42
|
+
await dependencies.tmux.selectPane(editorPane);
|
|
43
|
+
}
|
|
44
|
+
return { path, ...(parsed.line === undefined ? {} : { line: parsed.line }) };
|
|
45
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Exec } from "./exec.js";
|
|
2
|
+
export declare const sessionVariable = "TERMWIRE_SESSION";
|
|
3
|
+
export interface ProcessEntry {
|
|
4
|
+
pid: number;
|
|
5
|
+
ppid: number;
|
|
6
|
+
}
|
|
7
|
+
export interface ProcessScan {
|
|
8
|
+
/** Every process visible to the current user, used to protect our own ancestors. */
|
|
9
|
+
processes: ProcessEntry[];
|
|
10
|
+
/** Processes whose environment carries the scanned session label. */
|
|
11
|
+
labeled: number[];
|
|
12
|
+
}
|
|
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;
|
|
28
|
+
}
|
|
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;
|
|
33
|
+
/**
|
|
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.
|
|
36
|
+
*/
|
|
37
|
+
export declare function containsAssignment(text: string, needle: string): boolean;
|
|
@@ -0,0 +1,138 @@
|
|
|
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
|
+
/**
|
|
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.
|
|
45
|
+
*/
|
|
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;
|
|
56
|
+
}
|
|
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
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function createLinuxScanner(dependencies) {
|
|
95
|
+
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 };
|
|
118
|
+
};
|
|
119
|
+
}
|
|
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,9 +1,15 @@
|
|
|
1
|
+
import { createNvim } from "@termwire/nvim";
|
|
1
2
|
import { createTmux } from "@termwire/tmux";
|
|
2
3
|
import { Command } from "commander";
|
|
3
|
-
import { type
|
|
4
|
-
import { type
|
|
4
|
+
import { type Exec } from "./exec.js";
|
|
5
|
+
import { type OpenRequest, type OpenResult } from "./open.js";
|
|
6
|
+
import { type KillOutcome, type ReapSignal } from "./reap.js";
|
|
7
|
+
import { type UpRequest } from "./up.js";
|
|
8
|
+
import { type GitExec } from "./worktree.js";
|
|
5
9
|
export interface ProgramDependencies {
|
|
6
10
|
up: (request: UpRequest) => Promise<void>;
|
|
11
|
+
open: (request: OpenRequest) => Promise<OpenResult>;
|
|
12
|
+
reap: (session: string) => Promise<void>;
|
|
7
13
|
writeError: (message: string) => void;
|
|
8
14
|
writeOutput: (message: string) => void;
|
|
9
15
|
}
|
|
@@ -12,6 +18,9 @@ export interface RuntimeDependencies {
|
|
|
12
18
|
cwd: () => string;
|
|
13
19
|
env: Record<string, string | undefined>;
|
|
14
20
|
homedir: () => string;
|
|
21
|
+
execPath: string;
|
|
22
|
+
scriptPath: string | undefined;
|
|
23
|
+
warn: (message: string) => void;
|
|
15
24
|
readFile: (path: string, encoding: "utf8") => Promise<string>;
|
|
16
25
|
gitExec: GitExec;
|
|
17
26
|
mkdir: (path: string, options: {
|
|
@@ -20,8 +29,34 @@ export interface RuntimeDependencies {
|
|
|
20
29
|
pathExists: (path: string) => Promise<boolean>;
|
|
21
30
|
unlink: (path: string) => Promise<void>;
|
|
22
31
|
}
|
|
32
|
+
export interface RuntimeReapDependencies {
|
|
33
|
+
env: Record<string, string | undefined>;
|
|
34
|
+
homedir: () => string;
|
|
35
|
+
platform: string;
|
|
36
|
+
uid: number;
|
|
37
|
+
pid: number;
|
|
38
|
+
exec: Exec;
|
|
39
|
+
readdir: (path: string) => Promise<string[]>;
|
|
40
|
+
readFile: (path: string) => Promise<string>;
|
|
41
|
+
kill: (pid: number, signal: ReapSignal) => KillOutcome;
|
|
42
|
+
wait: (milliseconds: number) => Promise<void>;
|
|
43
|
+
appendFile: (path: string, contents: string) => Promise<void>;
|
|
44
|
+
mkdir: (path: string, options: {
|
|
45
|
+
recursive: true;
|
|
46
|
+
}) => Promise<unknown>;
|
|
47
|
+
now: () => Date;
|
|
48
|
+
}
|
|
49
|
+
export interface RuntimeOpenDependencies {
|
|
50
|
+
createNvim: () => ReturnType<typeof createNvim>;
|
|
51
|
+
createTmux: () => ReturnType<typeof createTmux>;
|
|
52
|
+
cwd: () => string;
|
|
53
|
+
env: Record<string, string | undefined>;
|
|
54
|
+
}
|
|
23
55
|
export declare const executeGit: GitExec;
|
|
24
56
|
export declare function removeStaleSocket(path: string, unlink: (path: string) => Promise<void>): Promise<void>;
|
|
25
57
|
export declare function createRuntimeUp(dependencies?: Partial<RuntimeDependencies>): (request: UpRequest) => Promise<void>;
|
|
58
|
+
export declare function killProcess(pid: number, signal: ReapSignal): KillOutcome;
|
|
59
|
+
export declare function createRuntimeReap(dependencies?: Partial<RuntimeReapDependencies>): (session: string) => Promise<void>;
|
|
60
|
+
export declare function createRuntimeOpen(dependencies?: Partial<RuntimeOpenDependencies>): (request: OpenRequest) => Promise<OpenResult>;
|
|
26
61
|
export declare function createProgram(dependencies: ProgramDependencies): Command;
|
|
27
62
|
export declare function run(argv: readonly string[], dependencies?: Partial<ProgramDependencies>): Promise<number>;
|
package/dist/program.js
CHANGED
|
@@ -1,28 +1,46 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { appendFile as appendFileToDisk, mkdir as mkdirDirectory, readdir as readDirectory, readFile as readFileFromDisk, stat, unlink as unlinkFile, } from "node:fs/promises";
|
|
2
3
|
import { homedir as getHomeDirectory } from "node:os";
|
|
4
|
+
import { dirname, resolve as resolvePath } from "node:path";
|
|
5
|
+
import { createNvim } from "@termwire/nvim";
|
|
3
6
|
import { createTmux } from "@termwire/tmux";
|
|
4
7
|
import { Command, CommanderError } from "commander";
|
|
5
|
-
import { prepareBranch } from "./branch";
|
|
6
|
-
import { createConfigLoader } from "./config-loader";
|
|
7
|
-
import { resolveLayout } from "./config-validation";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
8
|
+
import { prepareBranch } from "./branch.js";
|
|
9
|
+
import { createConfigLoader } from "./config-loader.js";
|
|
10
|
+
import { resolveLayout } from "./config-validation.js";
|
|
11
|
+
import { spawnCapture } from "./exec.js";
|
|
12
|
+
import { createLayout } from "./layout.js";
|
|
13
|
+
import { open } from "./open.js";
|
|
14
|
+
import { createProcessScanner } from "./process-scan.js";
|
|
15
|
+
import { formatReapFailure, formatReapReport, parseTmuxServerPid, reapLogPath, reapSession, } from "./reap.js";
|
|
16
|
+
import { ensureReapHook, reapCommandName } from "./reap-hook.js";
|
|
17
|
+
import { up } from "./up.js";
|
|
18
|
+
import { findGitRoot, prepareWorktree } from "./worktree.js";
|
|
11
19
|
export const executeGit = async (argv, options) => {
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
child = spawn();
|
|
16
|
-
}
|
|
17
|
-
catch (error) {
|
|
18
|
-
throw new Error(`git execution failed: ${argv.join(" ")}`, { cause: error });
|
|
20
|
+
const [command, ...args] = argv;
|
|
21
|
+
if (command === undefined) {
|
|
22
|
+
throw new Error("git execution failed: empty command");
|
|
19
23
|
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
24
|
+
return await new Promise((resolve, reject) => {
|
|
25
|
+
const child = spawn(command, args, {
|
|
26
|
+
cwd: options?.cwd,
|
|
27
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
28
|
+
});
|
|
29
|
+
let stdout = "";
|
|
30
|
+
let stderr = "";
|
|
31
|
+
child.stdout.setEncoding("utf8").on("data", (chunk) => {
|
|
32
|
+
stdout += chunk;
|
|
33
|
+
});
|
|
34
|
+
child.stderr.setEncoding("utf8").on("data", (chunk) => {
|
|
35
|
+
stderr += chunk;
|
|
36
|
+
});
|
|
37
|
+
child.once("error", (cause) => {
|
|
38
|
+
reject(new Error(`git execution failed: ${argv.join(" ")}`, { cause }));
|
|
39
|
+
});
|
|
40
|
+
child.once("close", (code) => {
|
|
41
|
+
resolve({ exitCode: code ?? 1, stdout, stderr });
|
|
42
|
+
});
|
|
43
|
+
});
|
|
26
44
|
};
|
|
27
45
|
export async function removeStaleSocket(path, unlink) {
|
|
28
46
|
try {
|
|
@@ -55,6 +73,9 @@ export function createRuntimeUp(dependencies = {}) {
|
|
|
55
73
|
}
|
|
56
74
|
});
|
|
57
75
|
const unlink = dependencies.unlink ?? unlinkFile;
|
|
76
|
+
const execPath = dependencies.execPath ?? process.execPath;
|
|
77
|
+
const scriptPath = "scriptPath" in dependencies ? dependencies.scriptPath : process.argv[1];
|
|
78
|
+
const warn = dependencies.warn ?? ((message) => process.stderr.write(message));
|
|
58
79
|
const loader = createConfigLoader({ env, homedir, exists: pathExists, readFile });
|
|
59
80
|
const loadGlobalConfig = loader.loadGlobal;
|
|
60
81
|
const loadProjectConfig = loader.loadProject;
|
|
@@ -68,12 +89,102 @@ export function createRuntimeUp(dependencies = {}) {
|
|
|
68
89
|
},
|
|
69
90
|
removeFile: (path) => removeStaleSocket(path, unlink),
|
|
70
91
|
tmux,
|
|
92
|
+
installReapHook: () => installReapHook({ tmux, execPath, scriptPath, warn }),
|
|
71
93
|
loadGlobalConfig,
|
|
72
94
|
loadProjectConfig,
|
|
73
95
|
resolveLayout,
|
|
74
96
|
createLayout,
|
|
75
97
|
});
|
|
76
98
|
}
|
|
99
|
+
/**
|
|
100
|
+
* Installing the cleanup hook is best effort: a workspace is still usable when the
|
|
101
|
+
* tmux server refuses the hook, so `up` only warns.
|
|
102
|
+
*/
|
|
103
|
+
async function installReapHook(options) {
|
|
104
|
+
try {
|
|
105
|
+
if (options.scriptPath === undefined) {
|
|
106
|
+
throw new Error("the termwire script path is unknown");
|
|
107
|
+
}
|
|
108
|
+
await ensureReapHook({
|
|
109
|
+
tmux: options.tmux,
|
|
110
|
+
execPath: options.execPath,
|
|
111
|
+
scriptPath: resolvePath(options.scriptPath),
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
116
|
+
options.warn(`termwire: session cleanup hook not installed: ${message}\n`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
export function killProcess(pid, signal) {
|
|
120
|
+
try {
|
|
121
|
+
process.kill(pid, signal);
|
|
122
|
+
return "signalled";
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
const code = error.code;
|
|
126
|
+
if (code === "ESRCH")
|
|
127
|
+
return "gone";
|
|
128
|
+
if (code === "EPERM")
|
|
129
|
+
return "denied";
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
export function createRuntimeReap(dependencies = {}) {
|
|
134
|
+
const env = dependencies.env ?? process.env;
|
|
135
|
+
const homedir = dependencies.homedir ?? getHomeDirectory;
|
|
136
|
+
const platform = dependencies.platform ?? process.platform;
|
|
137
|
+
const uid = dependencies.uid ?? process.getuid?.() ?? 0;
|
|
138
|
+
const pid = dependencies.pid ?? process.pid;
|
|
139
|
+
const exec = dependencies.exec ?? spawnCapture;
|
|
140
|
+
const readdir = dependencies.readdir ?? ((path) => readDirectory(path));
|
|
141
|
+
const readFile = dependencies.readFile ?? ((path) => readFileFromDisk(path, "utf8"));
|
|
142
|
+
const kill = dependencies.kill ?? killProcess;
|
|
143
|
+
const wait = dependencies.wait ??
|
|
144
|
+
((milliseconds) => new Promise((resolveWait) => {
|
|
145
|
+
setTimeout(resolveWait, milliseconds);
|
|
146
|
+
}));
|
|
147
|
+
const appendFile = dependencies.appendFile ??
|
|
148
|
+
((path, contents) => appendFileToDisk(path, contents));
|
|
149
|
+
const mkdir = dependencies.mkdir ?? mkdirDirectory;
|
|
150
|
+
const now = dependencies.now ?? (() => new Date());
|
|
151
|
+
const record = async (line) => {
|
|
152
|
+
const path = reapLogPath({ env, homedir });
|
|
153
|
+
try {
|
|
154
|
+
await mkdir(dirname(path), { recursive: true });
|
|
155
|
+
await appendFile(path, line);
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
// A missing log must not hide the reap itself.
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
return async (session) => {
|
|
162
|
+
try {
|
|
163
|
+
const serverPid = parseTmuxServerPid(env.TMUX);
|
|
164
|
+
const report = await reapSession(session, {
|
|
165
|
+
scan: createProcessScanner({ platform, exec, uid, readdir, readFile }),
|
|
166
|
+
kill,
|
|
167
|
+
wait,
|
|
168
|
+
selfPid: pid,
|
|
169
|
+
// The reap inherits the tmux server's environment, TMUX included, which is
|
|
170
|
+
// the only way back to the server it must not kill.
|
|
171
|
+
...(serverPid === undefined ? {} : { serverPid }),
|
|
172
|
+
});
|
|
173
|
+
await record(formatReapReport(report, now().toISOString()));
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
await record(formatReapFailure(session, error, now().toISOString()));
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
export function createRuntimeOpen(dependencies = {}) {
|
|
182
|
+
const nvim = (dependencies.createNvim ?? (() => createNvim()))();
|
|
183
|
+
const tmux = (dependencies.createTmux ?? (() => createTmux()))();
|
|
184
|
+
const cwd = dependencies.cwd ?? (() => process.cwd());
|
|
185
|
+
const env = dependencies.env ?? process.env;
|
|
186
|
+
return (request) => open(request, { cwd, env, nvim, tmux });
|
|
187
|
+
}
|
|
77
188
|
export function createProgram(dependencies) {
|
|
78
189
|
const program = new Command().name("termwire").configureOutput({
|
|
79
190
|
writeErr: dependencies.writeError,
|
|
@@ -83,6 +194,7 @@ export function createProgram(dependencies) {
|
|
|
83
194
|
program.showHelpAfterError();
|
|
84
195
|
program
|
|
85
196
|
.command("up <name>")
|
|
197
|
+
.description("create or attach to the workspace tmux session <project>-<name>")
|
|
86
198
|
.option("-w, --worktree [wt-name]", "create or reuse a Git worktree")
|
|
87
199
|
.option("-b, --branch <name>", "select the exact Git branch")
|
|
88
200
|
.addHelpText("after", `
|
|
@@ -106,12 +218,41 @@ Branch and worktree selection:
|
|
|
106
218
|
...(options.branch === undefined ? {} : { branch: options.branch }),
|
|
107
219
|
});
|
|
108
220
|
});
|
|
221
|
+
program
|
|
222
|
+
.command("open <target>")
|
|
223
|
+
.description("open a file in this workspace's editor and focus it")
|
|
224
|
+
.option("-l, --line <number>", "line to jump to, instead of a path:line suffix")
|
|
225
|
+
.addHelpText("after", `
|
|
226
|
+
Target syntax:
|
|
227
|
+
A trailing :<line> selects the line, so src/app.ts:42 opens line 42.
|
|
228
|
+
With --line, the target is used verbatim, which keeps a literal colon in a name.
|
|
229
|
+
Relative paths resolve from the current directory.
|
|
230
|
+
Requires a shell created by termwire up, which exports TERMWIRE_SOCKET.
|
|
231
|
+
`)
|
|
232
|
+
.action(async (target, options) => {
|
|
233
|
+
const result = await dependencies.open({
|
|
234
|
+
target,
|
|
235
|
+
...(options.line === undefined ? {} : { line: options.line }),
|
|
236
|
+
});
|
|
237
|
+
const suffix = result.line === undefined ? "" : ` at line ${result.line}`;
|
|
238
|
+
dependencies.writeOutput(`Opened ${result.path}${suffix}\n`);
|
|
239
|
+
});
|
|
240
|
+
// Part of the `up` lifecycle, not a user-facing command: the global tmux
|
|
241
|
+
// `session-closed` hook installed by `up` invokes it with the closed session.
|
|
242
|
+
program
|
|
243
|
+
.command(`${reapCommandName} <session>`, { hidden: true })
|
|
244
|
+
.description("kill the processes a closed workspace session left behind")
|
|
245
|
+
.action(async (session) => {
|
|
246
|
+
await dependencies.reap(session);
|
|
247
|
+
});
|
|
109
248
|
return program;
|
|
110
249
|
}
|
|
111
250
|
export async function run(argv, dependencies = {}) {
|
|
112
251
|
const writeError = dependencies.writeError ?? ((message) => process.stderr.write(message));
|
|
113
252
|
const program = createProgram({
|
|
114
253
|
up: dependencies.up ?? createRuntimeUp(),
|
|
254
|
+
open: dependencies.open ?? createRuntimeOpen(),
|
|
255
|
+
reap: dependencies.reap ?? createRuntimeReap(),
|
|
115
256
|
writeError,
|
|
116
257
|
writeOutput: dependencies.writeOutput ?? ((message) => process.stdout.write(message)),
|
|
117
258
|
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { HookEntry, SetHookOptions, ShowHooksOptions, UnsetHookOptions } from "@termwire/tmux";
|
|
2
|
+
export declare const reapHookName = "session-closed";
|
|
3
|
+
/**
|
|
4
|
+
* Identifies our entry among the user's own `session-closed` hooks, and doubles as
|
|
5
|
+
* a harmless environment assignment in the shell command that carries it.
|
|
6
|
+
*/
|
|
7
|
+
export declare const reapHookMarker = "TERMWIRE_REAP_HOOK=1";
|
|
8
|
+
export declare const reapCommandName = "_reap";
|
|
9
|
+
export type ReapHookOutcome = "created" | "updated" | "unchanged";
|
|
10
|
+
export interface ReapHookTmux {
|
|
11
|
+
showHooks: (options?: ShowHooksOptions) => Promise<HookEntry[]>;
|
|
12
|
+
setHook: (options: SetHookOptions) => Promise<void>;
|
|
13
|
+
unsetHook: (options: UnsetHookOptions) => Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
export interface ReapHookPaths {
|
|
16
|
+
execPath: string;
|
|
17
|
+
scriptPath: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The tmux server has its own environment and no `PATH` we control, so the hook
|
|
21
|
+
* names the interpreter and the script by absolute path. `#{hook_session_name}` is
|
|
22
|
+
* expanded by tmux when the hook fires; only the global hook sees it, because a
|
|
23
|
+
* session is destroyed before its own hooks run.
|
|
24
|
+
*
|
|
25
|
+
* `run-shell -b` never runs when the session being closed is the last one, because
|
|
26
|
+
* the server shuts down first. A foreground `run-shell` does run, and the trailing
|
|
27
|
+
* `&` hands the reap to a detached child that outlives the server, so tmux waits
|
|
28
|
+
* only for the fork and the closing client never blocks on it.
|
|
29
|
+
*
|
|
30
|
+
* The hook is global and therefore fires for sessions Termwire never created,
|
|
31
|
+
* whose names it never sanitized. `#{q:...}` is what makes that safe: tmux escapes
|
|
32
|
+
* the sh(1) special characters in the name, so the name must stay unquoted here.
|
|
33
|
+
* Quoting it would disarm the escaping and turn a session named
|
|
34
|
+
* `evil'; rm -rf ~; '` into a command.
|
|
35
|
+
*/
|
|
36
|
+
export declare function createReapHookCommand(paths: ReapHookPaths): string;
|
|
37
|
+
export declare function ensureReapHook(options: {
|
|
38
|
+
tmux: ReapHookTmux;
|
|
39
|
+
execPath: string;
|
|
40
|
+
scriptPath: string;
|
|
41
|
+
}): Promise<ReapHookOutcome>;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { isAbsolute } from "node:path";
|
|
2
|
+
export const reapHookName = "session-closed";
|
|
3
|
+
/**
|
|
4
|
+
* Identifies our entry among the user's own `session-closed` hooks, and doubles as
|
|
5
|
+
* a harmless environment assignment in the shell command that carries it.
|
|
6
|
+
*/
|
|
7
|
+
export const reapHookMarker = "TERMWIRE_REAP_HOOK=1";
|
|
8
|
+
export const reapCommandName = "_reap";
|
|
9
|
+
/** tmux expands this when the hook fires; `#{q:...}` escapes it for sh(1). */
|
|
10
|
+
const sessionFormat = "hook_session_name";
|
|
11
|
+
/**
|
|
12
|
+
* The tmux server has its own environment and no `PATH` we control, so the hook
|
|
13
|
+
* names the interpreter and the script by absolute path. `#{hook_session_name}` is
|
|
14
|
+
* expanded by tmux when the hook fires; only the global hook sees it, because a
|
|
15
|
+
* session is destroyed before its own hooks run.
|
|
16
|
+
*
|
|
17
|
+
* `run-shell -b` never runs when the session being closed is the last one, because
|
|
18
|
+
* the server shuts down first. A foreground `run-shell` does run, and the trailing
|
|
19
|
+
* `&` hands the reap to a detached child that outlives the server, so tmux waits
|
|
20
|
+
* only for the fork and the closing client never blocks on it.
|
|
21
|
+
*
|
|
22
|
+
* The hook is global and therefore fires for sessions Termwire never created,
|
|
23
|
+
* whose names it never sanitized. `#{q:...}` is what makes that safe: tmux escapes
|
|
24
|
+
* the sh(1) special characters in the name, so the name must stay unquoted here.
|
|
25
|
+
* Quoting it would disarm the escaping and turn a session named
|
|
26
|
+
* `evil'; rm -rf ~; '` into a command.
|
|
27
|
+
*/
|
|
28
|
+
export function createReapHookCommand(paths) {
|
|
29
|
+
const execPath = shellQuote(paths.execPath, "interpreter path");
|
|
30
|
+
const scriptPath = shellQuote(paths.scriptPath, "script path");
|
|
31
|
+
const session = `#{q:${sessionFormat}}`;
|
|
32
|
+
const command = `${reapHookMarker} ${execPath} ${scriptPath} ${reapCommandName} ${session}`;
|
|
33
|
+
return `run-shell "${command} >/dev/null 2>&1 &"`;
|
|
34
|
+
}
|
|
35
|
+
export async function ensureReapHook(options) {
|
|
36
|
+
const command = createReapHookCommand(options);
|
|
37
|
+
const entries = await options.tmux.showHooks({ global: true });
|
|
38
|
+
const [existing, ...duplicates] = entries.filter((entry) => entry.name === reapHookName && entry.command.includes(reapHookMarker));
|
|
39
|
+
if (existing === undefined) {
|
|
40
|
+
// Appending keeps any `session-closed` hook the user configured themselves.
|
|
41
|
+
await options.tmux.setHook({ name: reapHookName, command, global: true, append: true });
|
|
42
|
+
return "created";
|
|
43
|
+
}
|
|
44
|
+
let outcome = "unchanged";
|
|
45
|
+
if (existing.command !== command) {
|
|
46
|
+
await options.tmux.setHook({ name: hookTarget(existing), command, global: true });
|
|
47
|
+
outcome = "updated";
|
|
48
|
+
}
|
|
49
|
+
// Earlier versions, or a hand-edited server, can leave more than one of ours.
|
|
50
|
+
for (const duplicate of [...duplicates].reverse()) {
|
|
51
|
+
await options.tmux.unsetHook({ name: hookTarget(duplicate), global: true });
|
|
52
|
+
outcome = "updated";
|
|
53
|
+
}
|
|
54
|
+
return outcome;
|
|
55
|
+
}
|
|
56
|
+
function hookTarget(entry) {
|
|
57
|
+
return entry.index === undefined ? entry.name : `${entry.name}[${entry.index}]`;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The path is read by two parsers: tmux, which expands `#{...}` and backslash
|
|
61
|
+
* escapes inside double quotes, and then `sh`. Quoting characters would have to
|
|
62
|
+
* survive both, so they are rejected instead of escaped twice.
|
|
63
|
+
*/
|
|
64
|
+
function shellQuote(value, label) {
|
|
65
|
+
if (value.trim().length === 0) {
|
|
66
|
+
throw new Error(`${label} must not be empty`);
|
|
67
|
+
}
|
|
68
|
+
if (!isAbsolute(value)) {
|
|
69
|
+
throw new Error(`${label} must be absolute: ${value}`);
|
|
70
|
+
}
|
|
71
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: control characters break both parsers
|
|
72
|
+
if (/['"\\#\n\r\t\u0000-\u001f]/.test(value)) {
|
|
73
|
+
throw new Error(`${label} contains characters a tmux hook cannot carry: ${value}`);
|
|
74
|
+
}
|
|
75
|
+
return `'${value}'`;
|
|
76
|
+
}
|
package/dist/reap.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { ProcessScan, ProcessScanner } from "./process-scan.js";
|
|
2
|
+
export type ReapSignal = "SIGTERM" | "SIGKILL" | 0;
|
|
3
|
+
export type KillOutcome = "signalled" | "gone" | "denied";
|
|
4
|
+
export interface ReapDependencies {
|
|
5
|
+
scan: ProcessScanner;
|
|
6
|
+
kill: (pid: number, signal: ReapSignal) => KillOutcome;
|
|
7
|
+
wait: (milliseconds: number) => Promise<void>;
|
|
8
|
+
selfPid: number;
|
|
9
|
+
/** The tmux server, which the hook detaches from and may itself carry the label. */
|
|
10
|
+
serverPid?: number;
|
|
11
|
+
graceMs?: number;
|
|
12
|
+
settleMs?: number;
|
|
13
|
+
}
|
|
14
|
+
export interface ReapReport {
|
|
15
|
+
session: string;
|
|
16
|
+
targets: number[];
|
|
17
|
+
terminated: number[];
|
|
18
|
+
killed: number[];
|
|
19
|
+
survived: number[];
|
|
20
|
+
denied: number[];
|
|
21
|
+
/** Still alive at escalation time, but no longer labeled: a recycled pid. */
|
|
22
|
+
unlabeled: number[];
|
|
23
|
+
}
|
|
24
|
+
export declare const defaultGraceMs = 2000;
|
|
25
|
+
export declare const defaultSettleMs = 250;
|
|
26
|
+
/**
|
|
27
|
+
* Processes never worth signalling: this process, the tmux server, whatever either
|
|
28
|
+
* of them descends from, and init.
|
|
29
|
+
*
|
|
30
|
+
* Walking up from this process alone is not enough. The hook detaches the reap with
|
|
31
|
+
* `&`, so the forking shell is gone and this process is already a child of init by
|
|
32
|
+
* the time it scans. The tmux server is therefore not an ancestor, and it does
|
|
33
|
+
* inherit the environment of whoever started it, label included: without naming it
|
|
34
|
+
* the reap would kill the server and every other session on it.
|
|
35
|
+
*/
|
|
36
|
+
export declare function protectedPids(scan: ProcessScan, selfPid: number, serverPid?: number): Set<number>;
|
|
37
|
+
export declare function selectTargets(scan: ProcessScan, selfPid: number, serverPid?: number): number[];
|
|
38
|
+
/** Parses the server pid out of `TMUX`, which tmux sets to `socket,pid,session`. */
|
|
39
|
+
export declare function parseTmuxServerPid(tmux: string | undefined): number | undefined;
|
|
40
|
+
export declare function reapSession(session: string, dependencies: ReapDependencies): Promise<ReapReport>;
|
|
41
|
+
export declare function formatReapReport(report: ReapReport, timestamp: string): string;
|
|
42
|
+
export declare function formatReapFailure(session: string, error: unknown, timestamp: string): string;
|
|
43
|
+
/** `run-shell` output goes nowhere, so every reap records what it did here. */
|
|
44
|
+
export declare function reapLogPath(dependencies: {
|
|
45
|
+
env: Record<string, string | undefined>;
|
|
46
|
+
homedir: () => string;
|
|
47
|
+
}): string;
|
package/dist/reap.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { isAbsolute, join } from "node:path";
|
|
2
|
+
export const defaultGraceMs = 2000;
|
|
3
|
+
export const defaultSettleMs = 250;
|
|
4
|
+
const killRounds = 2;
|
|
5
|
+
/**
|
|
6
|
+
* Processes never worth signalling: this process, the tmux server, whatever either
|
|
7
|
+
* of them descends from, and init.
|
|
8
|
+
*
|
|
9
|
+
* Walking up from this process alone is not enough. The hook detaches the reap with
|
|
10
|
+
* `&`, so the forking shell is gone and this process is already a child of init by
|
|
11
|
+
* the time it scans. The tmux server is therefore not an ancestor, and it does
|
|
12
|
+
* inherit the environment of whoever started it, label included: without naming it
|
|
13
|
+
* the reap would kill the server and every other session on it.
|
|
14
|
+
*/
|
|
15
|
+
export function protectedPids(scan, selfPid, serverPid) {
|
|
16
|
+
const parents = new Map(scan.processes.map((entry) => [entry.pid, entry.ppid]));
|
|
17
|
+
const protectedSet = new Set([0, 1, selfPid]);
|
|
18
|
+
if (serverPid !== undefined)
|
|
19
|
+
protectedSet.add(serverPid);
|
|
20
|
+
for (const start of [selfPid, serverPid]) {
|
|
21
|
+
if (start === undefined)
|
|
22
|
+
continue;
|
|
23
|
+
let current = parents.get(start);
|
|
24
|
+
while (current !== undefined && !protectedSet.has(current)) {
|
|
25
|
+
protectedSet.add(current);
|
|
26
|
+
current = parents.get(current);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return protectedSet;
|
|
30
|
+
}
|
|
31
|
+
export function selectTargets(scan, selfPid, serverPid) {
|
|
32
|
+
const excluded = protectedPids(scan, selfPid, serverPid);
|
|
33
|
+
return [...new Set(scan.labeled)].filter((pid) => !excluded.has(pid)).sort((a, b) => a - b);
|
|
34
|
+
}
|
|
35
|
+
/** Parses the server pid out of `TMUX`, which tmux sets to `socket,pid,session`. */
|
|
36
|
+
export function parseTmuxServerPid(tmux) {
|
|
37
|
+
const pid = Number(tmux?.split(",")[1]);
|
|
38
|
+
return Number.isInteger(pid) && pid > 0 ? pid : undefined;
|
|
39
|
+
}
|
|
40
|
+
export async function reapSession(session, dependencies) {
|
|
41
|
+
const scan = await dependencies.scan(session);
|
|
42
|
+
const targets = selectTargets(scan, dependencies.selfPid, dependencies.serverPid);
|
|
43
|
+
const denied = new Set();
|
|
44
|
+
if (targets.length === 0) {
|
|
45
|
+
return {
|
|
46
|
+
session,
|
|
47
|
+
targets,
|
|
48
|
+
terminated: [],
|
|
49
|
+
killed: [],
|
|
50
|
+
survived: [],
|
|
51
|
+
denied: [],
|
|
52
|
+
unlabeled: [],
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
for (const pid of targets) {
|
|
56
|
+
if (dependencies.kill(pid, "SIGTERM") === "denied")
|
|
57
|
+
denied.add(pid);
|
|
58
|
+
}
|
|
59
|
+
await dependencies.wait(dependencies.graceMs ?? defaultGraceMs);
|
|
60
|
+
const survivingPids = targets.filter((pid) => dependencies.kill(pid, 0) !== "gone");
|
|
61
|
+
const terminated = targets.filter((pid) => !survivingPids.includes(pid));
|
|
62
|
+
// The grace period is long enough for a pid to be freed and handed to something
|
|
63
|
+
// else, so survivors are confirmed against a fresh scan before SIGKILL. A scan
|
|
64
|
+
// that fails here aborts the escalation rather than risk an innocent pid.
|
|
65
|
+
const relabeled = survivingPids.length === 0
|
|
66
|
+
? new Set()
|
|
67
|
+
: new Set(selectTargets(await dependencies.scan(session), dependencies.selfPid, dependencies.serverPid));
|
|
68
|
+
let alive = survivingPids.filter((pid) => relabeled.has(pid));
|
|
69
|
+
const unlabeled = survivingPids.filter((pid) => !relabeled.has(pid));
|
|
70
|
+
const killed = [];
|
|
71
|
+
for (let round = 0; round < killRounds && alive.length > 0; round += 1) {
|
|
72
|
+
for (const pid of alive) {
|
|
73
|
+
if (dependencies.kill(pid, "SIGKILL") === "denied")
|
|
74
|
+
denied.add(pid);
|
|
75
|
+
}
|
|
76
|
+
await dependencies.wait(dependencies.settleMs ?? defaultSettleMs);
|
|
77
|
+
const survivors = alive.filter((pid) => dependencies.kill(pid, 0) !== "gone");
|
|
78
|
+
killed.push(...alive.filter((pid) => !survivors.includes(pid)));
|
|
79
|
+
alive = survivors;
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
session,
|
|
83
|
+
targets,
|
|
84
|
+
terminated,
|
|
85
|
+
killed: killed.sort((a, b) => a - b),
|
|
86
|
+
survived: alive,
|
|
87
|
+
denied: [...denied].sort((a, b) => a - b),
|
|
88
|
+
unlabeled,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
export function formatReapReport(report, timestamp) {
|
|
92
|
+
const fields = [
|
|
93
|
+
`session=${report.session}`,
|
|
94
|
+
`targets=${formatPids(report.targets)}`,
|
|
95
|
+
`terminated=${formatPids(report.terminated)}`,
|
|
96
|
+
`killed=${formatPids(report.killed)}`,
|
|
97
|
+
`survived=${formatPids(report.survived)}`,
|
|
98
|
+
`denied=${formatPids(report.denied)}`,
|
|
99
|
+
`unlabeled=${formatPids(report.unlabeled)}`,
|
|
100
|
+
];
|
|
101
|
+
return `${timestamp} ${fields.join(" ")}\n`;
|
|
102
|
+
}
|
|
103
|
+
export function formatReapFailure(session, error, timestamp) {
|
|
104
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
105
|
+
return `${timestamp} session=${session} error=${message.replace(/\s+/g, " ")}\n`;
|
|
106
|
+
}
|
|
107
|
+
/** `run-shell` output goes nowhere, so every reap records what it did here. */
|
|
108
|
+
export function reapLogPath(dependencies) {
|
|
109
|
+
const xdgStateHome = dependencies.env.XDG_STATE_HOME;
|
|
110
|
+
const stateHome = xdgStateHome && isAbsolute(xdgStateHome)
|
|
111
|
+
? xdgStateHome
|
|
112
|
+
: join(dependencies.homedir(), ".local", "state");
|
|
113
|
+
return join(stateHome, "termwire", "reap.log");
|
|
114
|
+
}
|
|
115
|
+
function formatPids(pids) {
|
|
116
|
+
return pids.length === 0 ? "-" : pids.join(",");
|
|
117
|
+
}
|
package/dist/up.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { createTmux } from "@termwire/tmux";
|
|
2
|
-
import type { LayoutConfig } from "./config-schema";
|
|
3
|
-
import type { LoadedConfig } from "./config-types";
|
|
4
|
-
import type { createLayout } from "./layout";
|
|
2
|
+
import type { LayoutConfig } from "./config-schema.js";
|
|
3
|
+
import type { LoadedConfig } from "./config-types.js";
|
|
4
|
+
import type { createLayout } from "./layout.js";
|
|
5
5
|
export interface UpRequest {
|
|
6
6
|
name: string;
|
|
7
7
|
worktree?: true | string;
|
|
@@ -23,6 +23,8 @@ export interface UpDependencies {
|
|
|
23
23
|
mkdir: (path: string) => Promise<void>;
|
|
24
24
|
removeFile: (path: string) => Promise<void>;
|
|
25
25
|
tmux: ReturnType<typeof createTmux>;
|
|
26
|
+
/** Best effort: a workspace is worth having even without the cleanup hook. */
|
|
27
|
+
installReapHook: () => Promise<void>;
|
|
26
28
|
loadGlobalConfig: () => Promise<LoadedConfig | undefined>;
|
|
27
29
|
loadProjectConfig: (gitRoot: string) => Promise<LoadedConfig | undefined>;
|
|
28
30
|
resolveLayout: (globalConfig: LoadedConfig | undefined, projectConfig: LoadedConfig | undefined) => LayoutConfig;
|
package/dist/up.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createIdentity } from "./identity";
|
|
1
|
+
import { createIdentity } from "./identity.js";
|
|
2
2
|
export async function up(request, dependencies) {
|
|
3
3
|
if (request.worktree === "") {
|
|
4
4
|
throw new Error("worktree name must not be empty");
|
|
@@ -10,6 +10,7 @@ export async function up(request, dependencies) {
|
|
|
10
10
|
const gitRoot = await dependencies.findGitRoot(cwd);
|
|
11
11
|
const identity = createIdentity({ cwd, gitRoot, name: request.name });
|
|
12
12
|
if (await dependencies.tmux.hasSession(identity.session)) {
|
|
13
|
+
await bestEffortInstallReapHook(dependencies);
|
|
13
14
|
await dependencies.tmux.attach(identity.session);
|
|
14
15
|
return;
|
|
15
16
|
}
|
|
@@ -23,6 +24,7 @@ export async function up(request, dependencies) {
|
|
|
23
24
|
cwd: workspace,
|
|
24
25
|
});
|
|
25
26
|
try {
|
|
27
|
+
await bestEffortInstallReapHook(dependencies);
|
|
26
28
|
await dependencies.tmux.setSessionTitle(identity.session);
|
|
27
29
|
await dependencies.createLayout({
|
|
28
30
|
tmux: dependencies.tmux,
|
|
@@ -66,6 +68,15 @@ async function resolveWorkspace(request, dependencies, identity, gitRoot, cwd) {
|
|
|
66
68
|
branch: request.branch ?? name,
|
|
67
69
|
});
|
|
68
70
|
}
|
|
71
|
+
async function bestEffortInstallReapHook(dependencies) {
|
|
72
|
+
try {
|
|
73
|
+
await dependencies.installReapHook();
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
// Never trade the workspace for the cleanup hook: an implementation that
|
|
77
|
+
// reports failures does so itself, before throwing.
|
|
78
|
+
}
|
|
79
|
+
}
|
|
69
80
|
async function bestEffortKillSession(tmux, session) {
|
|
70
81
|
try {
|
|
71
82
|
await tmux.killSession(session);
|
package/dist/worktree.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { realpath as resolveRealpath } from "node:fs/promises";
|
|
2
2
|
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
3
|
-
import { sanitizeComponent } from "./identity";
|
|
3
|
+
import { sanitizeComponent } from "./identity.js";
|
|
4
4
|
export async function findGitRoot(exec, cwd) {
|
|
5
5
|
const result = await exec(["git", "rev-parse", "--show-toplevel"], { cwd });
|
|
6
6
|
if (result.exitCode === 128 && /not a git repository/i.test(result.stderr)) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@termwire/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
},
|
|
26
26
|
"license": "MIT",
|
|
27
27
|
"engines": {
|
|
28
|
-
"
|
|
28
|
+
"node": ">=22.12.0"
|
|
29
29
|
},
|
|
30
30
|
"repository": {
|
|
31
31
|
"type": "git",
|
|
@@ -37,8 +37,8 @@
|
|
|
37
37
|
"url": "https://github.com/max-konin/termwire/issues"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"@termwire/nvim": "^0.
|
|
41
|
-
"@termwire/tmux": "^0.
|
|
40
|
+
"@termwire/nvim": "^0.4.0",
|
|
41
|
+
"@termwire/tmux": "^0.4.0",
|
|
42
42
|
"commander": "^15.0.0",
|
|
43
43
|
"jsonc-parser": "^3.3.1",
|
|
44
44
|
"zod": "^4.0.0"
|