@termwire/cli 0.1.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 +13 -0
- package/LICENSE +21 -0
- package/README.md +47 -0
- package/dist/bin/termwire.d.ts +2 -0
- package/dist/bin/termwire.js +3 -0
- package/dist/identity.d.ts +11 -0
- package/dist/identity.js +22 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +3 -0
- package/dist/program.d.ts +24 -0
- package/dist/program.js +101 -0
- package/dist/up.d.ts +18 -0
- package/dist/up.js +83 -0
- package/dist/worktree.d.ts +25 -0
- package/dist/worktree.js +165 -0
- package/package.json +44 -0
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Termwire contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# @termwire/cli
|
|
2
|
+
|
|
3
|
+
Requires Bun >=1.3.14, tmux >=3.2, and Neovim >=0.9.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
bun add --global @termwire/cli
|
|
7
|
+
termwire --help
|
|
8
|
+
termwire up dev
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The project's main entry point — the `termwire` command. Orchestrates the
|
|
12
|
+
other packages. Fully **stateless**: no config files, no state files —
|
|
13
|
+
workspace identity lives in environment variables set by `termwire up <name>`.
|
|
14
|
+
|
|
15
|
+
## Why it exists
|
|
16
|
+
|
|
17
|
+
This is the tool that removes manual tmux/editor setup: bring up a stateless
|
|
18
|
+
workspace with a single command. The CLI owns `up <name>` only; file opening is
|
|
19
|
+
the explicit `termwire_open({ path, line? })` OpenCode plugin tool.
|
|
20
|
+
|
|
21
|
+
## Commands
|
|
22
|
+
|
|
23
|
+
| Command | What it does |
|
|
24
|
+
| -------------------------------------------- | ------------ |
|
|
25
|
+
| `termwire up <name>` | create or attach to `<project>-<name>` in the current directory |
|
|
26
|
+
| `termwire up <name> -w` | create or reuse sibling worktree `<project>-<name>` on branch `<name>` |
|
|
27
|
+
| `termwire up <name> --worktree <wt-name>` | create or reuse the explicit sibling worktree while retaining session `<project>-<name>` |
|
|
28
|
+
|
|
29
|
+
## How it works
|
|
30
|
+
|
|
31
|
+
- `up <name>` creates `editor` (`nvim --listen <socket>`) and free `shell`
|
|
32
|
+
windows. Final processes receive `TERMWIRE_SESSION`, `TERMWIRE_SOCKET`,
|
|
33
|
+
and `TERMWIRE_EDITOR_PANE`.
|
|
34
|
+
- OpenCode is not started automatically. Users may start it in the shell and
|
|
35
|
+
reshape the workspace with tmux.
|
|
36
|
+
- Existing sessions attach immediately without worktree mutation. Bare
|
|
37
|
+
`-w` uses the workspace name; an explicit worktree value selects its branch
|
|
38
|
+
and sibling directory while the session name stays `<project>-<name>`.
|
|
39
|
+
- There are no config files or persistent state.
|
|
40
|
+
- The CLI has no shell-facing `open` command and does not need to be in `PATH`
|
|
41
|
+
for the plugin: the plugin composes the nvim and tmux adapters directly.
|
|
42
|
+
|
|
43
|
+
## Dependencies
|
|
44
|
+
|
|
45
|
+
Commander 15 is the CLI runtime dependency for parsing `up`. `@termwire/tmux`
|
|
46
|
+
and `@termwire/nvim` are thin adapters over their binaries; the CLI owns
|
|
47
|
+
workspace policy and orchestration.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface WorkspaceIdentity {
|
|
2
|
+
project: string;
|
|
3
|
+
session: string;
|
|
4
|
+
socket: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function sanitizeComponent(value: string, label: string): string;
|
|
7
|
+
export declare function createIdentity(options: {
|
|
8
|
+
cwd: string;
|
|
9
|
+
gitRoot?: string;
|
|
10
|
+
name: string;
|
|
11
|
+
}): WorkspaceIdentity;
|
package/dist/identity.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { basename } from "node:path";
|
|
2
|
+
export function sanitizeComponent(value, label) {
|
|
3
|
+
const sanitized = value.replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
4
|
+
if (sanitized.length === 0) {
|
|
5
|
+
throw new Error(`${label} must contain a letter, number, _ or -`);
|
|
6
|
+
}
|
|
7
|
+
return sanitized;
|
|
8
|
+
}
|
|
9
|
+
export function createIdentity(options) {
|
|
10
|
+
const project = sanitizeComponent(basename(options.gitRoot ?? options.cwd), "project");
|
|
11
|
+
const name = sanitizeComponent(options.name, "name");
|
|
12
|
+
const session = `${project}-${name}`;
|
|
13
|
+
const socket = `/tmp/termwire/${session}.sock`;
|
|
14
|
+
if (Buffer.byteLength(socket) > 103) {
|
|
15
|
+
throw new Error("socket path exceeds macOS Unix socket limit of 103 bytes");
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
project,
|
|
19
|
+
session,
|
|
20
|
+
socket,
|
|
21
|
+
};
|
|
22
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type { ProgramDependencies, RuntimeDependencies } from "./program";
|
|
2
|
+
export { createProgram, createRuntimeUp, executeGit, removeStaleSocket, run } from "./program";
|
|
3
|
+
export type { UpDependencies, UpRequest } from "./up";
|
|
4
|
+
export { up } from "./up";
|
|
5
|
+
export type { GitExec, WorktreeEntry } from "./worktree";
|
|
6
|
+
export { findGitRoot, parseWorktreeList, prepareWorktree } from "./worktree";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { createTmux } from "@termwire/tmux";
|
|
2
|
+
import { Command } from "commander";
|
|
3
|
+
import { type UpRequest } from "./up";
|
|
4
|
+
import { type GitExec } from "./worktree";
|
|
5
|
+
export interface ProgramDependencies {
|
|
6
|
+
up: (request: UpRequest) => Promise<void>;
|
|
7
|
+
writeError: (message: string) => void;
|
|
8
|
+
writeOutput: (message: string) => void;
|
|
9
|
+
}
|
|
10
|
+
export interface RuntimeDependencies {
|
|
11
|
+
createTmux: () => ReturnType<typeof createTmux>;
|
|
12
|
+
cwd: () => string;
|
|
13
|
+
gitExec: GitExec;
|
|
14
|
+
mkdir: (path: string, options: {
|
|
15
|
+
recursive: true;
|
|
16
|
+
}) => Promise<unknown>;
|
|
17
|
+
pathExists: (path: string) => Promise<boolean>;
|
|
18
|
+
unlink: (path: string) => Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
export declare const executeGit: GitExec;
|
|
21
|
+
export declare function removeStaleSocket(path: string, unlink: (path: string) => Promise<void>): Promise<void>;
|
|
22
|
+
export declare function createRuntimeUp(dependencies?: Partial<RuntimeDependencies>): (request: UpRequest) => Promise<void>;
|
|
23
|
+
export declare function createProgram(dependencies: ProgramDependencies): Command;
|
|
24
|
+
export declare function run(argv: readonly string[], dependencies?: Partial<ProgramDependencies>): Promise<number>;
|
package/dist/program.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { mkdir as mkdirDirectory, stat, unlink as unlinkFile } from "node:fs/promises";
|
|
2
|
+
import { createTmux } from "@termwire/tmux";
|
|
3
|
+
import { Command, CommanderError } from "commander";
|
|
4
|
+
import { up } from "./up";
|
|
5
|
+
import { findGitRoot, prepareWorktree } from "./worktree";
|
|
6
|
+
export const executeGit = async (argv, options) => {
|
|
7
|
+
const spawn = () => Bun.spawn([...argv], { cwd: options?.cwd, stdout: "pipe", stderr: "pipe" });
|
|
8
|
+
let child;
|
|
9
|
+
try {
|
|
10
|
+
child = spawn();
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
throw new Error(`git execution failed: ${argv.join(" ")}`, { cause: error });
|
|
14
|
+
}
|
|
15
|
+
const [stdout, stderr, exitCode] = await Promise.all([
|
|
16
|
+
new Response(child.stdout).text(),
|
|
17
|
+
new Response(child.stderr).text(),
|
|
18
|
+
child.exited,
|
|
19
|
+
]);
|
|
20
|
+
return { exitCode, stdout, stderr };
|
|
21
|
+
};
|
|
22
|
+
export async function removeStaleSocket(path, unlink) {
|
|
23
|
+
try {
|
|
24
|
+
await unlink(path);
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (error.code !== "ENOENT") {
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function createRuntimeUp(dependencies = {}) {
|
|
33
|
+
const tmux = (dependencies.createTmux ?? (() => createTmux()))();
|
|
34
|
+
const cwd = dependencies.cwd ?? (() => process.cwd());
|
|
35
|
+
const gitExec = dependencies.gitExec ?? executeGit;
|
|
36
|
+
const mkdir = dependencies.mkdir ?? mkdirDirectory;
|
|
37
|
+
const pathExists = dependencies.pathExists ??
|
|
38
|
+
(async (path) => {
|
|
39
|
+
try {
|
|
40
|
+
await stat(path);
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
if (error.code === "ENOENT")
|
|
45
|
+
return false;
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
const unlink = dependencies.unlink ?? unlinkFile;
|
|
50
|
+
return (request) => up(request, {
|
|
51
|
+
cwd,
|
|
52
|
+
findGitRoot: (directory) => findGitRoot(gitExec, directory),
|
|
53
|
+
prepareWorktree: (options) => prepareWorktree({ ...options, exec: gitExec, pathExists }),
|
|
54
|
+
mkdir: async (path) => {
|
|
55
|
+
await mkdir(path, { recursive: true });
|
|
56
|
+
},
|
|
57
|
+
removeFile: (path) => removeStaleSocket(path, unlink),
|
|
58
|
+
tmux,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
export function createProgram(dependencies) {
|
|
62
|
+
const program = new Command().name("termwire").configureOutput({
|
|
63
|
+
writeErr: dependencies.writeError,
|
|
64
|
+
writeOut: dependencies.writeOutput,
|
|
65
|
+
});
|
|
66
|
+
program.exitOverride();
|
|
67
|
+
program.showHelpAfterError();
|
|
68
|
+
program
|
|
69
|
+
.command("up <name>")
|
|
70
|
+
.option("-w, --worktree [wt-name]", "create or reuse a Git worktree")
|
|
71
|
+
.action(async (name, options) => {
|
|
72
|
+
if (options.worktree === "") {
|
|
73
|
+
throw new Error("worktree name must not be empty");
|
|
74
|
+
}
|
|
75
|
+
await dependencies.up({
|
|
76
|
+
name,
|
|
77
|
+
...(options.worktree === undefined ? {} : { worktree: options.worktree }),
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
return program;
|
|
81
|
+
}
|
|
82
|
+
export async function run(argv, dependencies = {}) {
|
|
83
|
+
const writeError = dependencies.writeError ?? ((message) => process.stderr.write(message));
|
|
84
|
+
const program = createProgram({
|
|
85
|
+
up: dependencies.up ?? createRuntimeUp(),
|
|
86
|
+
writeError,
|
|
87
|
+
writeOutput: dependencies.writeOutput ?? ((message) => process.stdout.write(message)),
|
|
88
|
+
});
|
|
89
|
+
try {
|
|
90
|
+
await program.parseAsync(argv, { from: "user" });
|
|
91
|
+
return 0;
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
if (error instanceof CommanderError) {
|
|
95
|
+
return error.exitCode;
|
|
96
|
+
}
|
|
97
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
98
|
+
writeError(`termwire: ${message}\n`);
|
|
99
|
+
return 1;
|
|
100
|
+
}
|
|
101
|
+
}
|
package/dist/up.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { createTmux } from "@termwire/tmux";
|
|
2
|
+
export interface UpRequest {
|
|
3
|
+
name: string;
|
|
4
|
+
worktree?: true | string;
|
|
5
|
+
}
|
|
6
|
+
export interface UpDependencies {
|
|
7
|
+
cwd: () => string;
|
|
8
|
+
findGitRoot: (cwd: string) => Promise<string | undefined>;
|
|
9
|
+
prepareWorktree: (options: {
|
|
10
|
+
gitRoot: string;
|
|
11
|
+
project: string;
|
|
12
|
+
name: string;
|
|
13
|
+
}) => Promise<string>;
|
|
14
|
+
mkdir: (path: string) => Promise<void>;
|
|
15
|
+
removeFile: (path: string) => Promise<void>;
|
|
16
|
+
tmux: ReturnType<typeof createTmux>;
|
|
17
|
+
}
|
|
18
|
+
export declare function up(request: UpRequest, dependencies: UpDependencies): Promise<void>;
|
package/dist/up.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { createIdentity } from "./identity";
|
|
2
|
+
export async function up(request, dependencies) {
|
|
3
|
+
if (request.worktree === "") {
|
|
4
|
+
throw new Error("worktree name must not be empty");
|
|
5
|
+
}
|
|
6
|
+
const cwd = dependencies.cwd();
|
|
7
|
+
const gitRoot = await dependencies.findGitRoot(cwd);
|
|
8
|
+
const identity = createIdentity({ cwd, gitRoot, name: request.name });
|
|
9
|
+
if (await dependencies.tmux.hasSession(identity.session)) {
|
|
10
|
+
await dependencies.tmux.attach(identity.session);
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
const workspace = await resolveWorkspace(request, dependencies, identity, gitRoot, cwd);
|
|
14
|
+
await dependencies.mkdir("/tmp/termwire");
|
|
15
|
+
await dependencies.removeFile(identity.socket);
|
|
16
|
+
const editor = await dependencies.tmux.newSession({
|
|
17
|
+
session: identity.session,
|
|
18
|
+
name: "editor",
|
|
19
|
+
cwd: workspace,
|
|
20
|
+
});
|
|
21
|
+
const environment = createWorkspaceEnvironment(identity, editor.paneId);
|
|
22
|
+
try {
|
|
23
|
+
await configureWorkspaceSession({
|
|
24
|
+
tmux: dependencies.tmux,
|
|
25
|
+
identity,
|
|
26
|
+
workspace,
|
|
27
|
+
editor,
|
|
28
|
+
environment,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
await bestEffortKillSession(dependencies.tmux, identity.session);
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
await dependencies.tmux.attach(identity.session);
|
|
36
|
+
}
|
|
37
|
+
async function resolveWorkspace(request, dependencies, identity, gitRoot, cwd) {
|
|
38
|
+
if (request.worktree === undefined) {
|
|
39
|
+
return cwd;
|
|
40
|
+
}
|
|
41
|
+
if (!gitRoot) {
|
|
42
|
+
throw new Error("worktree requires a Git repository");
|
|
43
|
+
}
|
|
44
|
+
return dependencies.prepareWorktree({
|
|
45
|
+
gitRoot,
|
|
46
|
+
project: identity.project,
|
|
47
|
+
name: request.worktree === true ? request.name : request.worktree,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function createWorkspaceEnvironment(identity, editorPane) {
|
|
51
|
+
return {
|
|
52
|
+
TERMWIRE_SESSION: identity.session,
|
|
53
|
+
TERMWIRE_SOCKET: identity.socket,
|
|
54
|
+
TERMWIRE_EDITOR_PANE: editorPane,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
async function configureWorkspaceSession(options) {
|
|
58
|
+
for (const [key, value] of Object.entries(options.environment)) {
|
|
59
|
+
await options.tmux.setEnvironment(options.identity.session, key, value);
|
|
60
|
+
}
|
|
61
|
+
await options.tmux.respawnPane({
|
|
62
|
+
target: options.editor.paneId,
|
|
63
|
+
cwd: options.workspace,
|
|
64
|
+
command: ["nvim", "--listen", options.identity.socket],
|
|
65
|
+
environment: options.environment,
|
|
66
|
+
});
|
|
67
|
+
await options.tmux.newWindow({
|
|
68
|
+
target: options.identity.session,
|
|
69
|
+
name: "shell",
|
|
70
|
+
cwd: options.workspace,
|
|
71
|
+
environment: options.environment,
|
|
72
|
+
});
|
|
73
|
+
await options.tmux.selectWindow(options.editor.windowId);
|
|
74
|
+
await options.tmux.selectPane(options.editor.paneId);
|
|
75
|
+
}
|
|
76
|
+
async function bestEffortKillSession(tmux, session) {
|
|
77
|
+
try {
|
|
78
|
+
await tmux.killSession(session);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// Preserve the workspace setup failure when best-effort cleanup fails.
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export type GitExec = (argv: readonly string[], options?: {
|
|
2
|
+
cwd?: string;
|
|
3
|
+
}) => Promise<{
|
|
4
|
+
exitCode: number;
|
|
5
|
+
stdout: string;
|
|
6
|
+
stderr: string;
|
|
7
|
+
}>;
|
|
8
|
+
export interface WorktreeEntry {
|
|
9
|
+
path: string;
|
|
10
|
+
branch?: string;
|
|
11
|
+
bare?: true;
|
|
12
|
+
detached?: true;
|
|
13
|
+
locked?: true | string;
|
|
14
|
+
prunable?: true | string;
|
|
15
|
+
}
|
|
16
|
+
export declare function findGitRoot(exec: GitExec, cwd: string): Promise<string | undefined>;
|
|
17
|
+
export declare function parseWorktreeList(output: string): WorktreeEntry[];
|
|
18
|
+
export declare function prepareWorktree(options: {
|
|
19
|
+
exec: GitExec;
|
|
20
|
+
pathExists: (path: string) => Promise<boolean>;
|
|
21
|
+
realpath?: (path: string) => Promise<string>;
|
|
22
|
+
gitRoot: string;
|
|
23
|
+
project: string;
|
|
24
|
+
name: string;
|
|
25
|
+
}): Promise<string>;
|
package/dist/worktree.js
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { realpath as resolveRealpath } from "node:fs/promises";
|
|
2
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
3
|
+
import { sanitizeComponent } from "./identity";
|
|
4
|
+
export async function findGitRoot(exec, cwd) {
|
|
5
|
+
const result = await exec(["git", "rev-parse", "--show-toplevel"], { cwd });
|
|
6
|
+
if (result.exitCode === 128 && /not a git repository/i.test(result.stderr)) {
|
|
7
|
+
return undefined;
|
|
8
|
+
}
|
|
9
|
+
if (result.exitCode !== 0) {
|
|
10
|
+
throw new Error(`git rev-parse failed: ${result.stderr}`);
|
|
11
|
+
}
|
|
12
|
+
return result.stdout.trim();
|
|
13
|
+
}
|
|
14
|
+
export function parseWorktreeList(output) {
|
|
15
|
+
const trimmed = output.trim();
|
|
16
|
+
if (trimmed === "") {
|
|
17
|
+
return [];
|
|
18
|
+
}
|
|
19
|
+
return trimmed.split(/\n\s*\n/).map((record) => {
|
|
20
|
+
const path = record.match(/^worktree (.+)$/m)?.[1];
|
|
21
|
+
if (!path) {
|
|
22
|
+
throw new Error("Git worktree record is missing a path");
|
|
23
|
+
}
|
|
24
|
+
const entry = { path };
|
|
25
|
+
const branch = record.match(/^branch refs\/heads\/(.+)$/m)?.[1];
|
|
26
|
+
if (branch)
|
|
27
|
+
entry.branch = branch;
|
|
28
|
+
if (/^bare$/m.test(record))
|
|
29
|
+
entry.bare = true;
|
|
30
|
+
if (/^detached$/m.test(record))
|
|
31
|
+
entry.detached = true;
|
|
32
|
+
for (const field of ["locked", "prunable"]) {
|
|
33
|
+
const match = record.match(new RegExp(`^${field}(?: (.*))?$`, "m"));
|
|
34
|
+
if (match)
|
|
35
|
+
entry[field] = match[1] || true;
|
|
36
|
+
}
|
|
37
|
+
return entry;
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
export async function prepareWorktree(options) {
|
|
41
|
+
const name = sanitizeComponent(options.name, "name");
|
|
42
|
+
const target = join(dirname(options.gitRoot), `${options.project}-${name}`);
|
|
43
|
+
const entries = await listWorktrees(options.exec, options.gitRoot);
|
|
44
|
+
const registered = findWorktreeAt(entries, target);
|
|
45
|
+
if (registered) {
|
|
46
|
+
return reuseRegisteredWorktree({
|
|
47
|
+
entry: registered,
|
|
48
|
+
name,
|
|
49
|
+
target,
|
|
50
|
+
gitRoot: options.gitRoot,
|
|
51
|
+
exec: options.exec,
|
|
52
|
+
pathExists: options.pathExists,
|
|
53
|
+
realpath: options.realpath ?? resolveRealpath,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
if (await options.pathExists(target)) {
|
|
57
|
+
throw new Error(`Worktree conflict: target path is occupied: ${target}`);
|
|
58
|
+
}
|
|
59
|
+
const branchAt = findBranchCheckout(entries, name);
|
|
60
|
+
if (branchAt) {
|
|
61
|
+
throw new Error(`Worktree conflict: branch ${name} is already checked out at ${branchAt.path}`);
|
|
62
|
+
}
|
|
63
|
+
await addWorktree(options.exec, options.gitRoot, target, name);
|
|
64
|
+
return target;
|
|
65
|
+
}
|
|
66
|
+
async function listWorktrees(exec, gitRoot) {
|
|
67
|
+
const list = await exec(["git", "worktree", "list", "--porcelain"], {
|
|
68
|
+
cwd: gitRoot,
|
|
69
|
+
});
|
|
70
|
+
if (list.exitCode !== 0) {
|
|
71
|
+
throw new Error(`git worktree list failed: ${list.stderr}`);
|
|
72
|
+
}
|
|
73
|
+
return parseWorktreeList(list.stdout);
|
|
74
|
+
}
|
|
75
|
+
function findWorktreeAt(entries, target) {
|
|
76
|
+
return entries.find((entry) => resolve(entry.path) === resolve(target));
|
|
77
|
+
}
|
|
78
|
+
function validateRegistrationMetadata(entry, name) {
|
|
79
|
+
if (entry.prunable) {
|
|
80
|
+
throw new Error(`Worktree conflict: registered target is prunable${typeof entry.prunable === "string" ? `: ${entry.prunable}` : ""}`);
|
|
81
|
+
}
|
|
82
|
+
if (entry.bare) {
|
|
83
|
+
throw new Error("Worktree conflict: registered target is bare");
|
|
84
|
+
}
|
|
85
|
+
if (entry.detached) {
|
|
86
|
+
throw new Error("Worktree conflict: registered target is detached");
|
|
87
|
+
}
|
|
88
|
+
if (entry.branch !== name) {
|
|
89
|
+
throw new Error(`Worktree conflict: expected ${name}, found ${entry.branch ?? "detached HEAD"}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
async function reuseRegisteredWorktree(options) {
|
|
93
|
+
validateRegistrationMetadata(options.entry, options.name);
|
|
94
|
+
if (!(await options.pathExists(options.target))) {
|
|
95
|
+
throw new Error(`Worktree conflict: registered target path is missing: ${options.target}`);
|
|
96
|
+
}
|
|
97
|
+
await validateRegisteredWorktree({
|
|
98
|
+
exec: options.exec,
|
|
99
|
+
realpath: options.realpath,
|
|
100
|
+
target: options.target,
|
|
101
|
+
gitRoot: options.gitRoot,
|
|
102
|
+
name: options.name,
|
|
103
|
+
});
|
|
104
|
+
return options.target;
|
|
105
|
+
}
|
|
106
|
+
function findBranchCheckout(entries, name) {
|
|
107
|
+
return entries.find((entry) => entry.branch === name);
|
|
108
|
+
}
|
|
109
|
+
async function addWorktree(exec, gitRoot, target, name) {
|
|
110
|
+
const branch = await exec(["git", "show-ref", "--verify", "--quiet", `refs/heads/${name}`], {
|
|
111
|
+
cwd: gitRoot,
|
|
112
|
+
});
|
|
113
|
+
if (branch.exitCode !== 0 && branch.exitCode !== 1) {
|
|
114
|
+
throw new Error(`git show-ref failed: ${branch.stderr}`);
|
|
115
|
+
}
|
|
116
|
+
const command = branch.exitCode === 0
|
|
117
|
+
? ["git", "worktree", "add", target, name]
|
|
118
|
+
: ["git", "worktree", "add", "-b", name, target];
|
|
119
|
+
const added = await exec(command, { cwd: gitRoot });
|
|
120
|
+
if (added.exitCode !== 0) {
|
|
121
|
+
throw new Error(`git worktree add failed: ${added.stderr}`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
async function validateRegisteredWorktree(options) {
|
|
125
|
+
const targetDetails = await options.exec(["git", "rev-parse", "--show-toplevel", "--git-common-dir"], { cwd: options.target });
|
|
126
|
+
if (targetDetails.exitCode !== 0) {
|
|
127
|
+
throw new Error(`Worktree conflict: registered target is not a usable Git worktree: ${targetDetails.stderr}`);
|
|
128
|
+
}
|
|
129
|
+
const [targetTopLevel, targetCommonDir] = targetDetails.stdout.trim().split(/\r?\n/);
|
|
130
|
+
if (!targetTopLevel || !targetCommonDir) {
|
|
131
|
+
throw new Error("Worktree conflict: registered target is not a usable Git worktree");
|
|
132
|
+
}
|
|
133
|
+
const [canonicalTarget, canonicalTopLevel] = await Promise.all([
|
|
134
|
+
options.realpath(options.target),
|
|
135
|
+
options.realpath(targetTopLevel),
|
|
136
|
+
]);
|
|
137
|
+
if (canonicalTarget !== canonicalTopLevel) {
|
|
138
|
+
throw new Error(`Worktree conflict: registered target canonical path does not match: ${targetTopLevel}`);
|
|
139
|
+
}
|
|
140
|
+
const sourceCommonDir = await options.exec(["git", "rev-parse", "--git-common-dir"], {
|
|
141
|
+
cwd: options.gitRoot,
|
|
142
|
+
});
|
|
143
|
+
if (sourceCommonDir.exitCode !== 0) {
|
|
144
|
+
throw new Error(`git rev-parse --git-common-dir failed: ${sourceCommonDir.stderr}`);
|
|
145
|
+
}
|
|
146
|
+
const [canonicalTargetCommonDir, canonicalSourceCommonDir] = await Promise.all([
|
|
147
|
+
options.realpath(resolveGitPath(targetCommonDir, options.target)),
|
|
148
|
+
options.realpath(resolveGitPath(sourceCommonDir.stdout.trim(), options.gitRoot)),
|
|
149
|
+
]);
|
|
150
|
+
if (canonicalTargetCommonDir !== canonicalSourceCommonDir) {
|
|
151
|
+
throw new Error("Worktree conflict: registered target has a different Git common directory");
|
|
152
|
+
}
|
|
153
|
+
const liveBranch = await options.exec(["git", "symbolic-ref", "--quiet", "HEAD"], {
|
|
154
|
+
cwd: options.target,
|
|
155
|
+
});
|
|
156
|
+
if (liveBranch.exitCode !== 0) {
|
|
157
|
+
throw new Error(`Worktree conflict: registered target has no symbolic HEAD: ${liveBranch.stderr}`);
|
|
158
|
+
}
|
|
159
|
+
if (liveBranch.stdout.trim() !== `refs/heads/${options.name}`) {
|
|
160
|
+
throw new Error(`Worktree conflict: registered target live branch is ${liveBranch.stdout.trim()}, expected refs/heads/${options.name}`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function resolveGitPath(path, cwd) {
|
|
164
|
+
return isAbsolute(path) ? path : resolve(cwd, path);
|
|
165
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@termwire/cli",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"types": "./dist/index.d.ts",
|
|
7
|
+
"bin": {
|
|
8
|
+
"termwire": "./dist/bin/termwire.js"
|
|
9
|
+
},
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.js",
|
|
14
|
+
"default": "./dist/index.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE",
|
|
21
|
+
"CHANGELOG.md"
|
|
22
|
+
],
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"license": "MIT",
|
|
27
|
+
"engines": {
|
|
28
|
+
"bun": ">=1.3.14"
|
|
29
|
+
},
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "git+https://github.com/max-konin/termwire.git",
|
|
33
|
+
"directory": "packages/cli"
|
|
34
|
+
},
|
|
35
|
+
"homepage": "https://github.com/max-konin/termwire#readme",
|
|
36
|
+
"bugs": {
|
|
37
|
+
"url": "https://github.com/max-konin/termwire/issues"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@termwire/nvim": "workspace:*",
|
|
41
|
+
"@termwire/tmux": "workspace:*",
|
|
42
|
+
"commander": "^15.0.0"
|
|
43
|
+
}
|
|
44
|
+
}
|