opencode-worktree 0.1.3 → 0.2.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 arturosdg
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,67 @@
1
+ # opencode-worktree
2
+
3
+ Terminal UI for managing git worktrees and launching `opencode` in the selected worktree.
4
+
5
+ ## Features
6
+
7
+ - Lists all worktrees with branch, path, and short HEAD
8
+ - Create new worktrees directly from the TUI
9
+ - Unlink worktrees (remove directory, keep branch)
10
+ - Delete worktrees and local branches (never remote)
11
+ - Launches `opencode` in the selected worktree
12
+ - Refresh list on demand
13
+
14
+ ## Requirements
15
+
16
+ - Git
17
+ - `opencode` available on your PATH
18
+
19
+ ## Install (npm)
20
+
21
+ ```bash
22
+ npm i -g opencode-worktree
23
+ ```
24
+
25
+ ## Run
26
+
27
+ ```bash
28
+ opencode-worktree
29
+ ```
30
+
31
+ Or specify a repo path:
32
+
33
+ ```bash
34
+ opencode-worktree /path/to/your/repo
35
+ ```
36
+
37
+ ## Keybindings
38
+
39
+ - `Up`/`Down` or `j`/`k`: navigate
40
+ - `Enter`: open selected worktree
41
+ - `d`: unlink/delete menu
42
+ - `n`: create new worktree
43
+ - `r`: refresh list
44
+ - `q` or `Esc`: quit (or cancel dialogs)
45
+
46
+ ## Update notifications
47
+
48
+ When a new version is published to npm, the CLI will show a non-intrusive update message on the next run.
49
+
50
+ ## Development
51
+
52
+ ```bash
53
+ bun install
54
+ bun run dev
55
+ ```
56
+
57
+ ## Build (local)
58
+
59
+ ```bash
60
+ bun run build:single
61
+ ```
62
+
63
+ Build all platforms (release only):
64
+
65
+ ```bash
66
+ bun run build:all
67
+ ```
@@ -44,24 +44,17 @@ const detectPlatformAndArch = () => {
44
44
  };
45
45
 
46
46
  const resolveBinaryPath = () => {
47
- const { platform, arch } = detectPlatformAndArch();
48
- const packageName = `${pkg.name}-${platform}-${arch}`;
49
- const binaryName = platform === 'windows' ? 'opencode-worktree.exe' : 'opencode-worktree';
47
+ const { platform } = detectPlatformAndArch();
48
+ const binaryName = platform === 'windows' ? 'opencode-worktree.exe' : 'opencode-worktree-bin';
49
+ const binaryPath = path.join(__dirname, 'bin', binaryName);
50
50
 
51
- try {
52
- const packageJsonPath = require.resolve(`${packageName}/package.json`);
53
- const packageDir = path.dirname(packageJsonPath);
54
- const binaryPath = path.join(packageDir, 'bin', binaryName);
55
-
56
- if (!fs.existsSync(binaryPath)) {
57
- throw new Error(`Binary not found at ${binaryPath}`);
58
- }
59
-
60
- return binaryPath;
61
- } catch (error) {
62
- const message = error instanceof Error ? error.message : String(error);
63
- throw new Error(`Could not find ${packageName}: ${message}`);
51
+ if (!fs.existsSync(binaryPath)) {
52
+ throw new Error(
53
+ `Binary not found at ${binaryPath}. Run npm install -g ${pkg.name} again to re-download.`,
54
+ );
64
55
  }
56
+
57
+ return binaryPath;
65
58
  };
66
59
 
67
60
  const run = () => {
package/package.json CHANGED
@@ -1,9 +1,11 @@
1
1
  {
2
2
  "name": "opencode-worktree",
3
- "version": "0.1.3",
3
+ "version": "0.2.2",
4
+ "private": false,
5
+ "type": "module",
4
6
  "description": "TUI for managing git worktrees with opencode integration.",
5
- "license": "MIT",
6
7
  "author": "arturosdg",
8
+ "license": "MIT",
7
9
  "repository": {
8
10
  "type": "git",
9
11
  "url": "git+https://github.com/arturosdg/opencode-worktree.git"
@@ -12,27 +14,39 @@
12
14
  "url": "https://github.com/arturosdg/opencode-worktree/issues"
13
15
  },
14
16
  "homepage": "https://github.com/arturosdg/opencode-worktree#readme",
17
+ "keywords": [
18
+ "git",
19
+ "worktree",
20
+ "tui",
21
+ "opencode",
22
+ "cli"
23
+ ],
15
24
  "bin": {
16
- "opencode-worktree": "./bin/opencode-worktree"
25
+ "opencode-worktree": "bin/opencode-worktree"
17
26
  },
18
27
  "scripts": {
19
- "postinstall": "node ./postinstall.mjs"
20
- },
21
- "dependencies": {
22
- "update-notifier": "^7.3.1"
23
- },
24
- "optionalDependencies": {
25
- "opencode-worktree-darwin-arm64": "0.1.3",
26
- "opencode-worktree-darwin-x64": "0.1.3",
27
- "opencode-worktree-linux-x64": "0.1.3",
28
- "opencode-worktree-linux-arm64": "0.1.3",
29
- "opencode-worktree-windows-x64": "0.1.3"
28
+ "dev": "bun src/cli.ts",
29
+ "build:single": "bun run script/build.ts --single",
30
+ "build:all": "bun run script/build.ts",
31
+ "publish": "bun run script/publish.ts"
30
32
  },
31
33
  "files": [
32
34
  "bin",
33
- "postinstall.mjs"
35
+ "script",
36
+ "src",
37
+ "README.md",
38
+ "LICENSE"
34
39
  ],
35
40
  "engines": {
36
41
  "node": ">=18"
42
+ },
43
+ "dependencies": {
44
+ "@opentui/core": "^0.1.75",
45
+ "update-notifier": "^7.3.1"
46
+ },
47
+ "devDependencies": {
48
+ "@types/bun": "^1.2.0",
49
+ "@types/node": "^24.2.0",
50
+ "typescript": "^5.9.3"
37
51
  }
38
- }
52
+ }
@@ -0,0 +1,150 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import path from "node:path";
4
+ import fs from "node:fs";
5
+ import { fileURLToPath } from "node:url";
6
+ import { $ } from "bun";
7
+
8
+ type Target = {
9
+ os: "darwin" | "linux" | "win32";
10
+ arch: "arm64" | "x64";
11
+ bunTarget: string;
12
+ packagePlatform: "darwin" | "linux" | "windows";
13
+ binaryName: string;
14
+ };
15
+
16
+ const __filename = fileURLToPath(import.meta.url);
17
+ const __dirname = path.dirname(__filename);
18
+ const rootDir = path.resolve(__dirname, "..");
19
+ const distDir = path.join(rootDir, "dist");
20
+ const releaseDir = path.join(distDir, "release");
21
+
22
+ const pkg = JSON.parse(
23
+ await Bun.file(path.join(rootDir, "package.json")).text(),
24
+ );
25
+
26
+ const packageName = "opencode-worktree";
27
+ const version = pkg.version as string;
28
+
29
+ export const targets: Target[] = [
30
+ {
31
+ os: "darwin",
32
+ arch: "arm64",
33
+ bunTarget: "bun-darwin-arm64",
34
+ packagePlatform: "darwin",
35
+ binaryName: "opencode-worktree",
36
+ },
37
+ {
38
+ os: "darwin",
39
+ arch: "x64",
40
+ bunTarget: "bun-darwin-x64",
41
+ packagePlatform: "darwin",
42
+ binaryName: "opencode-worktree",
43
+ },
44
+ {
45
+ os: "linux",
46
+ arch: "x64",
47
+ bunTarget: "bun-linux-x64",
48
+ packagePlatform: "linux",
49
+ binaryName: "opencode-worktree",
50
+ },
51
+ {
52
+ os: "linux",
53
+ arch: "arm64",
54
+ bunTarget: "bun-linux-arm64",
55
+ packagePlatform: "linux",
56
+ binaryName: "opencode-worktree",
57
+ },
58
+ {
59
+ os: "win32",
60
+ arch: "x64",
61
+ bunTarget: "bun-windows-x64",
62
+ packagePlatform: "windows",
63
+ binaryName: "opencode-worktree.exe",
64
+ },
65
+ ];
66
+
67
+ const ensureCleanDist = () => {
68
+ fs.rmSync(distDir, { recursive: true, force: true });
69
+ fs.mkdirSync(distDir, { recursive: true });
70
+ fs.mkdirSync(releaseDir, { recursive: true });
71
+ };
72
+
73
+ const installPlatformDependencies = async () => {
74
+ const opentuiVersion = pkg.dependencies?.["@opentui/core"] ?? "^0.1.75";
75
+ await $`bun install --os="*" --cpu="*" @opentui/core@${opentuiVersion}`;
76
+ };
77
+
78
+ const buildBinary = async (target: Target) => {
79
+ const name = `${packageName}-${target.packagePlatform}-${target.arch}`;
80
+ const outDir = path.join(releaseDir);
81
+
82
+ const parserWorker = fs.realpathSync(
83
+ path.join(rootDir, "node_modules/@opentui/core/parser.worker.js"),
84
+ );
85
+ const bunfsRoot = target.os === "win32" ? "B:/~BUN/root/" : "/$bunfs/root/";
86
+ const workerRelativePath = path
87
+ .relative(rootDir, parserWorker)
88
+ .replace(/\\/g, "/");
89
+
90
+ let result: Bun.BuildOutput;
91
+ try {
92
+ result = await Bun.build({
93
+ entrypoints: [path.join(rootDir, "src/cli.ts"), parserWorker],
94
+ minify: true,
95
+ compile: {
96
+ target: target.bunTarget as Bun.Build.Target,
97
+ outfile: path.join(
98
+ outDir,
99
+ name + (target.os === "win32" ? ".exe" : ""),
100
+ ),
101
+ autoloadBunfig: false,
102
+ autoloadDotenv: false,
103
+ autoloadPackageJson: true,
104
+ autoloadTsconfig: true,
105
+ },
106
+ define: {
107
+ OTUI_TREE_SITTER_WORKER_PATH: JSON.stringify(
108
+ bunfsRoot + workerRelativePath,
109
+ ),
110
+ },
111
+ });
112
+ } catch (error) {
113
+ console.error(`Bundle threw for ${name}`);
114
+ if (error instanceof Error && error.stack) {
115
+ console.error(error.stack);
116
+ } else {
117
+ console.error(error);
118
+ }
119
+ throw error;
120
+ }
121
+
122
+ if (!result.success) {
123
+ const logs = result.logs
124
+ .map((log) => `${log.level}: ${log.message}`)
125
+ .join("\n");
126
+ throw new Error(`Bundle failed for ${name}:\n${logs}`);
127
+ }
128
+
129
+ return name;
130
+ };
131
+
132
+ export const buildAll = async ({ single = false } = {}) => {
133
+ await installPlatformDependencies();
134
+ ensureCleanDist();
135
+
136
+ const selectedTargets = single
137
+ ? targets.filter(
138
+ (item) => item.os === process.platform && item.arch === process.arch,
139
+ )
140
+ : targets;
141
+
142
+ for (const target of selectedTargets) {
143
+ await buildBinary(target);
144
+ }
145
+ };
146
+
147
+ if (import.meta.main) {
148
+ const single = process.argv.includes("--single");
149
+ await buildAll({ single });
150
+ }
@@ -0,0 +1,86 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import os from "node:os";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
9
+ const pkg = JSON.parse(
10
+ fs.readFileSync(path.join(__dirname, "..", "package.json"), "utf8"),
11
+ );
12
+
13
+ const detectPlatformAndArch = () => {
14
+ let platform;
15
+ switch (os.platform()) {
16
+ case "darwin":
17
+ platform = "darwin";
18
+ break;
19
+ case "linux":
20
+ platform = "linux";
21
+ break;
22
+ case "win32":
23
+ platform = "windows";
24
+ break;
25
+ default:
26
+ platform = os.platform();
27
+ break;
28
+ }
29
+
30
+ let arch;
31
+ switch (os.arch()) {
32
+ case "x64":
33
+ arch = "x64";
34
+ break;
35
+ case "arm64":
36
+ arch = "arm64";
37
+ break;
38
+ default:
39
+ arch = os.arch();
40
+ break;
41
+ }
42
+
43
+ return { platform, arch };
44
+ };
45
+
46
+ const downloadFile = async (url, targetPath) => {
47
+ const response = await fetch(url);
48
+ if (!response.ok) {
49
+ throw new Error(`Failed to download ${url} (${response.status})`);
50
+ }
51
+
52
+ const buffer = Buffer.from(await response.arrayBuffer());
53
+ fs.writeFileSync(targetPath, buffer);
54
+ };
55
+
56
+ const installBinary = async () => {
57
+ const { platform, arch } = detectPlatformAndArch();
58
+ const isWindows = platform === "windows";
59
+ const binaryName = isWindows
60
+ ? "opencode-worktree.exe"
61
+ : "opencode-worktree-bin";
62
+ const downloadName = `opencode-worktree-${platform}-${arch}${isWindows ? ".exe" : ""}`;
63
+ const version = pkg.version;
64
+ const downloadUrl = `https://github.com/arturosdg/opencode-worktree/releases/download/v${version}/${downloadName}`;
65
+
66
+ const binDir = path.join(__dirname, "..", "bin");
67
+ const binaryPath = path.join(binDir, binaryName);
68
+
69
+ fs.mkdirSync(binDir, { recursive: true });
70
+ await downloadFile(downloadUrl, binaryPath);
71
+
72
+ if (!isWindows) {
73
+ fs.chmodSync(binaryPath, 0o755);
74
+ }
75
+
76
+ return binaryPath;
77
+ };
78
+
79
+ try {
80
+ const binaryPath = await installBinary();
81
+ console.log(`opencode-worktree binary installed at: ${binaryPath}`);
82
+ } catch (error) {
83
+ console.error("Failed to install opencode-worktree binary.");
84
+ console.error(error instanceof Error ? error.message : String(error));
85
+ process.exit(1);
86
+ }
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { $ } from "bun";
4
+
5
+ try {
6
+ await $`npm publish --access public`;
7
+ } catch (error) {
8
+ console.error("Publish failed.");
9
+ console.error(error instanceof Error ? error.message : String(error));
10
+ process.exit(1);
11
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { runApp } from "./ui.js";
2
+
3
+ // Accept optional path argument: opencode-worktree [path]
4
+ const targetPath = process.argv[2] || process.cwd();
5
+
6
+ runApp(targetPath).catch((error: unknown) => {
7
+ console.error("Failed to start OpenTUI worktree selector.");
8
+ console.error(error);
9
+ process.exit(1);
10
+ });
package/src/git.ts ADDED
@@ -0,0 +1,209 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { WorktreeInfo } from "./types.js";
3
+
4
+ export const resolveRepoRoot = (cwd: string): string | null => {
5
+ try {
6
+ const output = execFileSync("git", ["rev-parse", "--show-toplevel"], {
7
+ cwd,
8
+ stdio: ["ignore", "pipe", "ignore"],
9
+ encoding: "utf8",
10
+ });
11
+ return output.trim() || null;
12
+ } catch {
13
+ return null;
14
+ }
15
+ };
16
+
17
+ export const parseWorktreeList = (output: string): WorktreeInfo[] => {
18
+ const lines = output.split(/\r?\n/);
19
+ const worktrees: WorktreeInfo[] = [];
20
+ let current: WorktreeInfo | null = null;
21
+
22
+ const pushCurrent = (): void => {
23
+ if (current?.path) {
24
+ worktrees.push(current);
25
+ }
26
+ };
27
+
28
+ for (const line of lines) {
29
+ if (line.startsWith("worktree ")) {
30
+ pushCurrent();
31
+ current = {
32
+ path: line.slice("worktree ".length).trim(),
33
+ head: "",
34
+ branch: null,
35
+ isDetached: false,
36
+ };
37
+ continue;
38
+ }
39
+
40
+ if (!current) continue;
41
+
42
+ if (line.startsWith("HEAD ")) {
43
+ current.head = line.slice("HEAD ".length).trim();
44
+ continue;
45
+ }
46
+
47
+ if (line.startsWith("branch ")) {
48
+ const ref = line.slice("branch ".length).trim();
49
+ if (ref.startsWith("refs/heads/")) {
50
+ current.branch = ref.replace("refs/heads/", "");
51
+ }
52
+ continue;
53
+ }
54
+
55
+ if (line.trim() === "detached") {
56
+ current.isDetached = true;
57
+ continue;
58
+ }
59
+ }
60
+
61
+ pushCurrent();
62
+ return worktrees;
63
+ };
64
+
65
+ export const listWorktrees = (cwd: string): WorktreeInfo[] => {
66
+ const repoRoot = resolveRepoRoot(cwd);
67
+ if (!repoRoot) return [];
68
+
69
+ const output = execFileSync("git", ["worktree", "list", "--porcelain"], {
70
+ cwd: repoRoot,
71
+ stdio: ["ignore", "pipe", "ignore"],
72
+ encoding: "utf8",
73
+ });
74
+ return parseWorktreeList(output);
75
+ };
76
+
77
+ export type CreateWorktreeResult =
78
+ | { success: true; path: string }
79
+ | { success: false; error: string };
80
+
81
+ export const createWorktree = (
82
+ repoRoot: string,
83
+ branchName: string,
84
+ worktreesDir: string,
85
+ ): CreateWorktreeResult => {
86
+ const worktreePath = `${worktreesDir}/${branchName}`;
87
+
88
+ try {
89
+ // Try to create worktree with new branch
90
+ execFileSync("git", ["worktree", "add", "-b", branchName, worktreePath], {
91
+ cwd: repoRoot,
92
+ stdio: ["ignore", "pipe", "pipe"],
93
+ encoding: "utf8",
94
+ });
95
+ return { success: true, path: worktreePath };
96
+ } catch {
97
+ // Branch might already exist, try without -b
98
+ try {
99
+ execFileSync("git", ["worktree", "add", worktreePath, branchName], {
100
+ cwd: repoRoot,
101
+ stdio: ["ignore", "pipe", "pipe"],
102
+ encoding: "utf8",
103
+ });
104
+ return { success: true, path: worktreePath };
105
+ } catch (e) {
106
+ const error = e instanceof Error ? e.message : String(e);
107
+ return { success: false, error };
108
+ }
109
+ }
110
+ };
111
+
112
+ export const getDefaultWorktreesDir = (repoRoot: string): string => {
113
+ // Place worktrees in a sibling 'worktrees' folder
114
+ const parentDir = repoRoot.replace(/\/[^/]+$/, "");
115
+ const repoName = repoRoot.split("/").pop() || "repo";
116
+ return `${parentDir}/${repoName}-worktrees`;
117
+ };
118
+
119
+ /**
120
+ * Check if a worktree has uncommitted changes (dirty state)
121
+ */
122
+ export const hasUncommittedChanges = (worktreePath: string): boolean => {
123
+ try {
124
+ const output = execFileSync("git", ["status", "--porcelain"], {
125
+ cwd: worktreePath,
126
+ stdio: ["ignore", "pipe", "ignore"],
127
+ encoding: "utf8",
128
+ });
129
+ return output.trim().length > 0;
130
+ } catch {
131
+ // If we can't check, assume it's clean to avoid blocking
132
+ return false;
133
+ }
134
+ };
135
+
136
+ /**
137
+ * Check if a worktree is the main worktree (the original repo clone)
138
+ */
139
+ export const isMainWorktree = (
140
+ repoRoot: string,
141
+ worktreePath: string,
142
+ ): boolean => {
143
+ // The main worktree path matches the repo root
144
+ return repoRoot === worktreePath;
145
+ };
146
+
147
+ export type UnlinkResult =
148
+ | { success: true }
149
+ | { success: false; error: string };
150
+
151
+ /**
152
+ * Unlink a worktree - removes the worktree directory but keeps the branch
153
+ */
154
+ export const unlinkWorktree = (
155
+ repoRoot: string,
156
+ worktreePath: string,
157
+ force: boolean = false,
158
+ ): UnlinkResult => {
159
+ try {
160
+ const args = ["worktree", "remove"];
161
+ if (force) {
162
+ args.push("--force");
163
+ }
164
+ args.push(worktreePath);
165
+
166
+ execFileSync("git", args, {
167
+ cwd: repoRoot,
168
+ stdio: ["ignore", "pipe", "pipe"],
169
+ encoding: "utf8",
170
+ });
171
+ return { success: true };
172
+ } catch (e) {
173
+ const error = e instanceof Error ? e.message : String(e);
174
+ return { success: false, error };
175
+ }
176
+ };
177
+
178
+ export type DeleteResult =
179
+ | { success: true }
180
+ | { success: false; error: string; step: "unlink" | "branch" };
181
+
182
+ /**
183
+ * Delete a worktree AND its local branch (never touches remote)
184
+ */
185
+ export const deleteWorktree = (
186
+ repoRoot: string,
187
+ worktreePath: string,
188
+ branchName: string,
189
+ force: boolean = false,
190
+ ): DeleteResult => {
191
+ // First unlink the worktree
192
+ const unlinkResult = unlinkWorktree(repoRoot, worktreePath, force);
193
+ if (!unlinkResult.success) {
194
+ return { success: false, error: unlinkResult.error, step: "unlink" };
195
+ }
196
+
197
+ // Then delete the local branch (never remote!)
198
+ try {
199
+ execFileSync("git", ["branch", "-D", branchName], {
200
+ cwd: repoRoot,
201
+ stdio: ["ignore", "pipe", "pipe"],
202
+ encoding: "utf8",
203
+ });
204
+ return { success: true };
205
+ } catch (e) {
206
+ const error = e instanceof Error ? e.message : String(e);
207
+ return { success: false, error, step: "branch" };
208
+ }
209
+ };
@@ -0,0 +1,20 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+
3
+ export const isOpenCodeAvailable = (): boolean => {
4
+ const result = spawnSync("opencode", ["--version"], {
5
+ stdio: "ignore",
6
+ });
7
+ return result.status === 0;
8
+ };
9
+
10
+ export const launchOpenCode = (cwd: string): void => {
11
+ const child = spawn("opencode", [], {
12
+ cwd,
13
+ stdio: "inherit",
14
+ });
15
+
16
+ child.on("exit", (code: number | null) => {
17
+ const exitCode = typeof code === "number" ? code : 0;
18
+ process.exit(exitCode);
19
+ });
20
+ };
package/src/types.ts ADDED
@@ -0,0 +1,6 @@
1
+ export type WorktreeInfo = {
2
+ path: string;
3
+ head: string;
4
+ branch: string | null;
5
+ isDetached: boolean;
6
+ };