@neuralnomads/codenomad 0.14.0 → 0.16.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/dist/cli-upgrade.js +53 -0
- package/dist/cli-upgrade.test.js +31 -0
- package/dist/filesystem/__tests__/browser.test.js +65 -0
- package/dist/filesystem/__tests__/search-cache.test.js +2 -2
- package/dist/filesystem/browser.js +40 -5
- package/dist/index.js +27 -6
- package/dist/opencode-plugin/codenomad-opencode-plugin.tgz +0 -0
- package/dist/opencode-plugin.js +146 -0
- package/dist/opencode-plugin.test.js +28 -0
- package/dist/previews/manager.js +63 -0
- package/dist/server/__tests__/remote-proxy.test.js +204 -0
- package/dist/server/http-server.js +380 -46
- package/dist/server/remote-proxy.js +466 -0
- package/dist/server/routes/filesystem.js +13 -0
- package/dist/server/routes/previews.js +25 -0
- package/dist/server/routes/remote-proxy.js +42 -0
- package/dist/server/routes/settings.js +1 -1
- package/dist/server/routes/workspaces.js +141 -1
- package/dist/workspaces/__tests__/git-clone.test.js +141 -0
- package/dist/workspaces/__tests__/git-worktrees.test.js +43 -0
- package/dist/workspaces/__tests__/spawn.test.js +158 -0
- package/dist/workspaces/git-clone.js +148 -0
- package/dist/workspaces/git-mutations.js +98 -0
- package/dist/workspaces/git-status.js +323 -0
- package/dist/workspaces/git-worktrees.js +18 -1
- package/dist/workspaces/manager.js +17 -9
- package/dist/workspaces/opencode-auth.js +18 -0
- package/dist/workspaces/opencode-auth.test.js +34 -0
- package/dist/workspaces/runtime.js +54 -77
- package/dist/workspaces/spawn.js +245 -0
- package/dist/workspaces/worktree-directory.js +74 -0
- package/package.json +3 -3
- package/public/assets/ChangesTab-CxrJwz2Z.js +2 -0
- package/public/assets/DiffToolbar-CqJttTgx.js +1 -0
- package/public/assets/FilesTab-tBrdrLID.js +2 -0
- package/public/assets/GitChangesTab-DUUJn4Va.js +2 -0
- package/public/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- package/public/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
- package/public/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
- package/public/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
- package/public/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
- package/public/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- package/public/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
- package/public/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- package/public/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
- package/public/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
- package/public/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
- package/public/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- package/public/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
- package/public/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- package/public/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
- package/public/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- package/public/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
- package/public/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
- package/public/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- package/public/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
- package/public/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
- package/public/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
- package/public/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
- package/public/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- package/public/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- package/public/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
- package/public/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
- package/public/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
- package/public/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- package/public/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
- package/public/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
- package/public/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
- package/public/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- package/public/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
- package/public/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- package/public/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
- package/public/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- package/public/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
- package/public/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
- package/public/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
- package/public/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
- package/public/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- package/public/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
- package/public/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- package/public/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
- package/public/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
- package/public/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
- package/public/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- package/public/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
- package/public/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- package/public/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
- package/public/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
- package/public/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
- package/public/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
- package/public/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
- package/public/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- package/public/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
- package/public/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- package/public/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
- package/public/assets/{SplitFilePanel-CupweEA5.js → SplitFilePanel-CiZrHI3o.js} +1 -1
- package/public/assets/StatusTab-DN31GijL.js +1 -0
- package/public/assets/align-justify-CKbOni6U.js +1 -0
- package/public/assets/{bundle-full-B-5u6Iv3.js → bundle-full-B_MbXXHv.js} +1 -1
- package/public/assets/{diff-viewer-_ehhYA-Z.js → diff-viewer-CersJruo.js} +1 -1
- package/public/assets/index-BTenW4sL.js +1 -0
- package/public/assets/index-BsYORY4z.js +1 -0
- package/public/assets/index-BvfQjuig.js +1 -0
- package/public/assets/{index-BqiNjV6R.js → index-CK51N0B7.js} +1 -1
- package/public/assets/index-Chghci_R.js +1 -0
- package/public/assets/{index-CxQr-wOF.js → index-DYa3o0_M.js} +1 -1
- package/public/assets/index-DskBWxXS.js +2 -0
- package/public/assets/index-DslkXxdb.js +1 -0
- package/public/assets/index-UCZ7MxNK.js +1 -0
- package/public/assets/index-i5UooSrU.css +1 -0
- package/public/assets/{loading-Dck2H3XH.js → loading-hkCubi3k.js} +1 -1
- package/public/assets/main-CXJTHRp1.js +62 -0
- package/public/assets/markdown-Cy9tCAXp.js +315 -0
- package/public/assets/monaco-viewer-B3iAKbO0.js +26 -0
- package/public/assets/tool-call-DhWimeRu.js +59 -0
- package/public/assets/{unified-picker-Dw0kTXoT.js → unified-picker-C47f5lFi.js} +1 -1
- package/public/assets/wrap-text-hwXbREuU.js +1 -0
- package/public/index.html +4 -4
- package/public/loading.html +4 -4
- package/public/sw.js +1 -1
- package/public/ui-version.json +1 -1
- package/dist/opencode-config/README.md +0 -32
- package/dist/opencode-config/opencode.jsonc +0 -3
- package/dist/opencode-config/package.json +0 -9
- package/dist/opencode-config/plugin/codenomad.ts +0 -62
- package/dist/opencode-config/plugin/lib/background-process.ts +0 -265
- package/dist/opencode-config/plugin/lib/client.ts +0 -133
- package/dist/opencode-config/plugin/lib/request.ts +0 -214
- package/dist/opencode-config.js +0 -26
- package/public/assets/ChangesTab-CFkk3tAp.js +0 -2
- package/public/assets/DiffToolbar-CQQLR1mp.js +0 -1
- package/public/assets/FilesTab-CXgucPtN.js +0 -2
- package/public/assets/GitChangesTab-BidSb28_.js +0 -2
- package/public/assets/StatusTab-C2Pl_Vce.js +0 -1
- package/public/assets/index-BnfDkr8C.js +0 -1
- package/public/assets/index-BntAaLZs.js +0 -1
- package/public/assets/index-BwCEJ4BE.css +0 -1
- package/public/assets/index-DXaitXVC.js +0 -1
- package/public/assets/index-DzRzoTK8.js +0 -2
- package/public/assets/index-ShHad48G.js +0 -1
- package/public/assets/index-_EaXFUIj.js +0 -1
- package/public/assets/index-mMh5TJvW.js +0 -1
- package/public/assets/main-BsIf5lOY.js +0 -50
- package/public/assets/markdown-CFV9kR80.js +0 -58
- package/public/assets/monaco-viewer-CMM6n0T3.js +0 -25
- package/public/assets/todo-Ghwirj-b.js +0 -1
- package/public/assets/tool-call-BC2Pv3uG.js +0 -60
- package/public/assets/wrap-text-D2MJk2ad.js +0 -1
|
@@ -1,17 +1,39 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { getWorktreeGitDiff, getWorktreeGitStatus } from "../../workspaces/git-status";
|
|
3
|
+
import { commitWorktreeChanges, isGitMutationError, stageWorktreePaths, unstageWorktreePaths } from "../../workspaces/git-mutations";
|
|
4
|
+
import { cloneGitRepository, isGitCloneError } from "../../workspaces/git-clone";
|
|
5
|
+
import { isGitAvailable, resolveRepoRoot } from "../../workspaces/git-worktrees";
|
|
6
|
+
import { resolveWorktreeDirectory } from "../../workspaces/worktree-directory";
|
|
2
7
|
const WorkspaceCreateSchema = z.object({
|
|
3
8
|
path: z.string(),
|
|
4
9
|
name: z.string().optional(),
|
|
5
10
|
});
|
|
11
|
+
const WorkspaceCloneSchema = z.object({
|
|
12
|
+
repositoryUrl: z.string().trim().min(1, "Repository URL is required"),
|
|
13
|
+
destinationPath: z.string().trim().min(1, "Destination path is required"),
|
|
14
|
+
cleanup: z.boolean().optional(),
|
|
15
|
+
});
|
|
6
16
|
const WorkspaceFilesQuerySchema = z.object({
|
|
7
17
|
path: z.string().optional(),
|
|
8
18
|
});
|
|
9
19
|
const WorkspaceFileContentQuerySchema = z.object({
|
|
10
20
|
path: z.string(),
|
|
21
|
+
encoding: z.enum(["utf-8", "base64"]).optional(),
|
|
11
22
|
});
|
|
12
23
|
const WorkspaceFileContentBodySchema = z.object({
|
|
13
24
|
contents: z.string(),
|
|
14
25
|
});
|
|
26
|
+
const WorktreeGitDiffQuerySchema = z.object({
|
|
27
|
+
path: z.string().trim().min(1, "Path is required"),
|
|
28
|
+
originalPath: z.string().trim().optional(),
|
|
29
|
+
scope: z.enum(["staged", "unstaged"]),
|
|
30
|
+
});
|
|
31
|
+
const WorktreeGitPathsBodySchema = z.object({
|
|
32
|
+
paths: z.array(z.string().trim().min(1, "Path is required")).min(1, "At least one path is required"),
|
|
33
|
+
});
|
|
34
|
+
const WorktreeGitCommitBodySchema = z.object({
|
|
35
|
+
message: z.string().trim().min(1, "Commit message is required"),
|
|
36
|
+
});
|
|
15
37
|
const WorkspaceFileSearchQuerySchema = z.object({
|
|
16
38
|
q: z.string().trim().min(1, "Query is required"),
|
|
17
39
|
limit: z.coerce.number().int().positive().max(200).optional(),
|
|
@@ -38,6 +60,17 @@ export function registerWorkspaceRoutes(app, deps) {
|
|
|
38
60
|
reply.code(400).type("text/plain").send(message);
|
|
39
61
|
}
|
|
40
62
|
});
|
|
63
|
+
app.post("/api/workspaces/clone", async (request, reply) => {
|
|
64
|
+
try {
|
|
65
|
+
const body = WorkspaceCloneSchema.parse(request.body ?? {});
|
|
66
|
+
const result = await cloneGitRepository(body);
|
|
67
|
+
reply.code(201);
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
return handleWorkspaceError(error, reply);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
41
74
|
app.get("/api/workspaces/:id", async (request, reply) => {
|
|
42
75
|
const workspace = deps.workspaceManager.get(request.params.id);
|
|
43
76
|
if (!workspace) {
|
|
@@ -75,7 +108,7 @@ export function registerWorkspaceRoutes(app, deps) {
|
|
|
75
108
|
app.get("/api/workspaces/:id/files/content", async (request, reply) => {
|
|
76
109
|
try {
|
|
77
110
|
const query = WorkspaceFileContentQuerySchema.parse(request.query ?? {});
|
|
78
|
-
return deps.workspaceManager.readFile(request.params.id, query.path);
|
|
111
|
+
return deps.workspaceManager.readFile(request.params.id, query.path, { encoding: query.encoding });
|
|
79
112
|
}
|
|
80
113
|
catch (error) {
|
|
81
114
|
return handleWorkspaceError(error, reply);
|
|
@@ -92,8 +125,115 @@ export function registerWorkspaceRoutes(app, deps) {
|
|
|
92
125
|
return handleWorkspaceError(error, reply);
|
|
93
126
|
}
|
|
94
127
|
});
|
|
128
|
+
app.get("/api/workspaces/:id/worktrees/:slug/git-status", async (request, reply) => {
|
|
129
|
+
try {
|
|
130
|
+
const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
|
|
131
|
+
if (!directory)
|
|
132
|
+
return;
|
|
133
|
+
return await getWorktreeGitStatus({ workspaceFolder: directory, logger: request.log });
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
return handleWorkspaceError(error, reply);
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
app.get("/api/workspaces/:id/worktrees/:slug/git-diff", async (request, reply) => {
|
|
140
|
+
try {
|
|
141
|
+
const query = WorktreeGitDiffQuerySchema.parse(request.query ?? {});
|
|
142
|
+
const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
|
|
143
|
+
if (!directory)
|
|
144
|
+
return;
|
|
145
|
+
return await getWorktreeGitDiff({
|
|
146
|
+
workspaceFolder: directory,
|
|
147
|
+
path: query.path,
|
|
148
|
+
originalPath: query.originalPath,
|
|
149
|
+
scope: query.scope,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
return handleWorkspaceError(error, reply);
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
app.post("/api/workspaces/:id/worktrees/:slug/git-stage", async (request, reply) => {
|
|
157
|
+
try {
|
|
158
|
+
const body = WorktreeGitPathsBodySchema.parse(request.body ?? {});
|
|
159
|
+
const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
|
|
160
|
+
if (!directory)
|
|
161
|
+
return;
|
|
162
|
+
await stageWorktreePaths({ workspaceFolder: directory, paths: body.paths });
|
|
163
|
+
return { ok: true };
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
return handleWorkspaceError(error, reply);
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
app.post("/api/workspaces/:id/worktrees/:slug/git-unstage", async (request, reply) => {
|
|
170
|
+
try {
|
|
171
|
+
const body = WorktreeGitPathsBodySchema.parse(request.body ?? {});
|
|
172
|
+
const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
|
|
173
|
+
if (!directory)
|
|
174
|
+
return;
|
|
175
|
+
await unstageWorktreePaths({ workspaceFolder: directory, paths: body.paths });
|
|
176
|
+
return { ok: true };
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
return handleWorkspaceError(error, reply);
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
app.post("/api/workspaces/:id/worktrees/:slug/git-commit", async (request, reply) => {
|
|
183
|
+
try {
|
|
184
|
+
const body = WorktreeGitCommitBodySchema.parse(request.body ?? {});
|
|
185
|
+
const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
|
|
186
|
+
if (!directory)
|
|
187
|
+
return;
|
|
188
|
+
const result = await commitWorktreeChanges({ workspaceFolder: directory, message: body.message });
|
|
189
|
+
return { ok: true, ...result };
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
return handleWorkspaceError(error, reply);
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
async function resolveGitWorktreeDirectory(workspaceManager, workspaceId, worktreeSlug, logger, reply) {
|
|
197
|
+
const workspace = workspaceManager.get(workspaceId);
|
|
198
|
+
if (!workspace) {
|
|
199
|
+
reply.code(404);
|
|
200
|
+
reply.send({ error: "Workspace not found" });
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
const gitAvailable = await isGitAvailable(workspace.path);
|
|
204
|
+
if (!gitAvailable) {
|
|
205
|
+
reply.code(503);
|
|
206
|
+
reply.send({ error: "Git is not installed or not available in PATH" });
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
const { isGitRepo } = await resolveRepoRoot(workspace.path, logger);
|
|
210
|
+
if (!isGitRepo) {
|
|
211
|
+
reply.code(400);
|
|
212
|
+
reply.send({ error: "Workspace is not a Git repository" });
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
const directory = await resolveWorktreeDirectory({
|
|
216
|
+
workspaceId: workspace.id,
|
|
217
|
+
workspacePath: workspace.path,
|
|
218
|
+
worktreeSlug,
|
|
219
|
+
logger,
|
|
220
|
+
});
|
|
221
|
+
if (!directory) {
|
|
222
|
+
reply.code(404);
|
|
223
|
+
reply.send({ error: "Worktree not found" });
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
return directory;
|
|
95
227
|
}
|
|
96
228
|
function handleWorkspaceError(error, reply) {
|
|
229
|
+
if (isGitCloneError(error)) {
|
|
230
|
+
reply.code(error.statusCode);
|
|
231
|
+
return { error: error.message };
|
|
232
|
+
}
|
|
233
|
+
if (isGitMutationError(error)) {
|
|
234
|
+
reply.code(error.statusCode);
|
|
235
|
+
return { error: error.message };
|
|
236
|
+
}
|
|
97
237
|
if (error instanceof Error && error.message === "Workspace not found") {
|
|
98
238
|
reply.code(404);
|
|
99
239
|
return { error: "Workspace not found" };
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir, tmpdir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { describe, it } from "node:test";
|
|
7
|
+
import { cloneGitRepository } from "../git-clone";
|
|
8
|
+
function createBareRepository(repoPath) {
|
|
9
|
+
execFileSync("git", ["init", "--bare", repoPath], { stdio: "ignore" });
|
|
10
|
+
}
|
|
11
|
+
async function expectCloneError(callback, expectedStatusCode, messagePattern) {
|
|
12
|
+
await assert.rejects(callback, (error) => {
|
|
13
|
+
assert.equal(typeof error, "object");
|
|
14
|
+
assert.equal(error.statusCode, expectedStatusCode);
|
|
15
|
+
assert.match(String(error.message ?? ""), messagePattern);
|
|
16
|
+
return true;
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
describe("cloneGitRepository", () => {
|
|
20
|
+
it("clones into a missing destination", async () => {
|
|
21
|
+
const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
|
|
22
|
+
const sourceRepo = path.join(temp, "source.git");
|
|
23
|
+
const destinationPath = path.join(temp, "cloned-repo");
|
|
24
|
+
try {
|
|
25
|
+
createBareRepository(sourceRepo);
|
|
26
|
+
const result = await cloneGitRepository({
|
|
27
|
+
repositoryUrl: sourceRepo,
|
|
28
|
+
destinationPath,
|
|
29
|
+
});
|
|
30
|
+
assert.equal(result.path, destinationPath);
|
|
31
|
+
assert.equal(existsSync(path.join(destinationPath, ".git")), true);
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
rmSync(temp, { recursive: true, force: true });
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
it("rejects non-empty destinations when cleanup is not enabled", async () => {
|
|
38
|
+
const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
|
|
39
|
+
const sourceRepo = path.join(temp, "source.git");
|
|
40
|
+
const destinationPath = path.join(temp, "existing-destination");
|
|
41
|
+
const sentinelPath = path.join(destinationPath, "keep.txt");
|
|
42
|
+
try {
|
|
43
|
+
createBareRepository(sourceRepo);
|
|
44
|
+
mkdirSync(destinationPath, { recursive: true });
|
|
45
|
+
writeFileSync(sentinelPath, "keep");
|
|
46
|
+
await expectCloneError(() => cloneGitRepository({ repositoryUrl: sourceRepo, destinationPath }), 409, /Destination folder is not empty/);
|
|
47
|
+
assert.equal(readFileSync(sentinelPath, "utf8"), "keep");
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
rmSync(temp, { recursive: true, force: true });
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
it("preserves the existing destination when cleanup is enabled but clone fails", async () => {
|
|
54
|
+
const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
|
|
55
|
+
const missingRepo = path.join(temp, "missing.git");
|
|
56
|
+
const destinationPath = path.join(temp, "existing-destination");
|
|
57
|
+
const sentinelPath = path.join(destinationPath, "keep.txt");
|
|
58
|
+
try {
|
|
59
|
+
mkdirSync(destinationPath, { recursive: true });
|
|
60
|
+
writeFileSync(sentinelPath, "keep");
|
|
61
|
+
await expectCloneError(() => cloneGitRepository({ repositoryUrl: missingRepo, destinationPath, cleanup: true }), 409, /does not appear to be a git repository|does not exist|not found/i);
|
|
62
|
+
assert.equal(readFileSync(sentinelPath, "utf8"), "keep");
|
|
63
|
+
assert.equal(existsSync(destinationPath), true);
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
rmSync(temp, { recursive: true, force: true });
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
it("replaces the existing destination only after a successful cleanup clone", async () => {
|
|
70
|
+
const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
|
|
71
|
+
const sourceRepo = path.join(temp, "source.git");
|
|
72
|
+
const destinationPath = path.join(temp, "existing-destination");
|
|
73
|
+
const sentinelPath = path.join(destinationPath, "keep.txt");
|
|
74
|
+
try {
|
|
75
|
+
createBareRepository(sourceRepo);
|
|
76
|
+
mkdirSync(destinationPath, { recursive: true });
|
|
77
|
+
writeFileSync(sentinelPath, "keep");
|
|
78
|
+
const result = await cloneGitRepository({
|
|
79
|
+
repositoryUrl: sourceRepo,
|
|
80
|
+
destinationPath,
|
|
81
|
+
cleanup: true,
|
|
82
|
+
});
|
|
83
|
+
assert.equal(result.path, destinationPath);
|
|
84
|
+
assert.equal(existsSync(path.join(destinationPath, ".git")), true);
|
|
85
|
+
assert.equal(existsSync(sentinelPath), false);
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
rmSync(temp, { recursive: true, force: true });
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
it("rejects filesystem root destinations", async () => {
|
|
92
|
+
const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
|
|
93
|
+
const sourceRepo = path.join(temp, "source.git");
|
|
94
|
+
try {
|
|
95
|
+
createBareRepository(sourceRepo);
|
|
96
|
+
await expectCloneError(() => cloneGitRepository({
|
|
97
|
+
repositoryUrl: sourceRepo,
|
|
98
|
+
destinationPath: path.parse(process.cwd()).root,
|
|
99
|
+
cleanup: true,
|
|
100
|
+
}), 400, /filesystem root/);
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
rmSync(temp, { recursive: true, force: true });
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
it("rejects home directory destinations", async () => {
|
|
107
|
+
const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
|
|
108
|
+
const sourceRepo = path.join(temp, "source.git");
|
|
109
|
+
try {
|
|
110
|
+
createBareRepository(sourceRepo);
|
|
111
|
+
await expectCloneError(() => cloneGitRepository({
|
|
112
|
+
repositoryUrl: sourceRepo,
|
|
113
|
+
destinationPath: homedir(),
|
|
114
|
+
cleanup: true,
|
|
115
|
+
}), 400, /home folder/);
|
|
116
|
+
}
|
|
117
|
+
finally {
|
|
118
|
+
rmSync(temp, { recursive: true, force: true });
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
it("supports destinations directly under a Windows drive root", { skip: process.platform !== "win32" }, async () => {
|
|
122
|
+
const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
|
|
123
|
+
const sourceRepo = path.join(temp, "source.git");
|
|
124
|
+
const root = path.parse(process.cwd()).root;
|
|
125
|
+
const destinationPath = path.join(root, `codenomad-git-clone-root-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
|
126
|
+
try {
|
|
127
|
+
createBareRepository(sourceRepo);
|
|
128
|
+
rmSync(destinationPath, { recursive: true, force: true });
|
|
129
|
+
const result = await cloneGitRepository({
|
|
130
|
+
repositoryUrl: sourceRepo,
|
|
131
|
+
destinationPath,
|
|
132
|
+
});
|
|
133
|
+
assert.equal(result.path, destinationPath);
|
|
134
|
+
assert.equal(existsSync(destinationPath), true);
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
rmSync(destinationPath, { recursive: true, force: true });
|
|
138
|
+
rmSync(temp, { recursive: true, force: true });
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
});
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { describe, it } from "node:test";
|
|
6
|
+
import { listWorktrees } from "../git-worktrees";
|
|
7
|
+
describe("listWorktrees", () => {
|
|
8
|
+
it("uses the selected workspace folder for the root worktree directory", async () => {
|
|
9
|
+
const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-worktrees-"));
|
|
10
|
+
const binDir = path.join(temp, "bin");
|
|
11
|
+
const repoRoot = path.join(temp, "repo");
|
|
12
|
+
const workspaceFolder = path.join(repoRoot, "proj-1");
|
|
13
|
+
const originalPath = process.env.PATH;
|
|
14
|
+
try {
|
|
15
|
+
mkdirSync(binDir, { recursive: true });
|
|
16
|
+
mkdirSync(workspaceFolder, { recursive: true });
|
|
17
|
+
const gitPath = path.join(binDir, process.platform === "win32" ? "git.cmd" : "git");
|
|
18
|
+
const porcelain = [
|
|
19
|
+
`worktree ${repoRoot}`,
|
|
20
|
+
"HEAD 1111111",
|
|
21
|
+
"branch refs/heads/main",
|
|
22
|
+
"",
|
|
23
|
+
].join("\n");
|
|
24
|
+
if (process.platform === "win32") {
|
|
25
|
+
writeFileSync(gitPath, `@echo off\r\nif "%1"=="worktree" if "%2"=="list" if "%3"=="--porcelain" (\r\necho ${porcelain.replace(/\n/g, "\r\necho ")}\r\nexit /b 0\r\n)\r\nexit /b 1\r\n`);
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
writeFileSync(gitPath, `#!/bin/sh\nif [ "$1" = "worktree" ] && [ "$2" = "list" ] && [ "$3" = "--porcelain" ]; then\nprintf '%s\n' '${porcelain.replace(/'/g, "'\\''")}'\nexit 0\nfi\nexit 1\n`, { mode: 0o755 });
|
|
29
|
+
}
|
|
30
|
+
process.env.PATH = `${binDir}${path.delimiter}${originalPath ?? ""}`;
|
|
31
|
+
const worktrees = await listWorktrees({ repoRoot, workspaceFolder });
|
|
32
|
+
assert.equal(worktrees[0]?.slug, "root");
|
|
33
|
+
assert.equal(worktrees[0]?.directory, workspaceFolder);
|
|
34
|
+
assert.equal(worktrees[0]?.kind, "root");
|
|
35
|
+
assert.equal(worktrees[0]?.branch, "main");
|
|
36
|
+
assert.notEqual(worktrees[0]?.directory, repoRoot);
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
process.env.PATH = originalPath;
|
|
40
|
+
rmSync(temp, { recursive: true, force: true });
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
});
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { describe, it } from "node:test";
|
|
3
|
+
import { buildWindowsSpawnSpec, buildWslSignalSpec, parseWslUncPath, resolveWslWorkingDirectory } from "../spawn";
|
|
4
|
+
describe("parseWslUncPath", () => {
|
|
5
|
+
it("parses WSL UNC paths into distro and linux path", () => {
|
|
6
|
+
assert.deepEqual(parseWslUncPath(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`), {
|
|
7
|
+
distro: "Ubuntu",
|
|
8
|
+
linuxPath: "/home/dev/.opencode/bin/opencode",
|
|
9
|
+
});
|
|
10
|
+
});
|
|
11
|
+
it("supports the legacy wsl$ UNC prefix", () => {
|
|
12
|
+
assert.deepEqual(parseWslUncPath(String.raw `\\wsl$\Ubuntu\home\dev`), {
|
|
13
|
+
distro: "Ubuntu",
|
|
14
|
+
linuxPath: "/home/dev",
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
describe("resolveWslWorkingDirectory", () => {
|
|
19
|
+
it("keeps WSL workspace folders in the same distro", () => {
|
|
20
|
+
assert.equal(JSON.stringify(resolveWslWorkingDirectory(String.raw `\\wsl.localhost\Ubuntu\home\dev\workspace`, "Ubuntu")), JSON.stringify({ kind: "linux", path: "/home/dev/workspace" }));
|
|
21
|
+
});
|
|
22
|
+
it("keeps Windows drive paths so WSL can resolve them with wslpath", () => {
|
|
23
|
+
assert.equal(JSON.stringify(resolveWslWorkingDirectory(String.raw `C:\Users\dev\workspace`, "Ubuntu")), JSON.stringify({ kind: "windows", path: String.raw `C:\Users\dev\workspace` }));
|
|
24
|
+
});
|
|
25
|
+
it("keeps UNC network paths so WSL can resolve them with wslpath", () => {
|
|
26
|
+
assert.equal(JSON.stringify(resolveWslWorkingDirectory(String.raw `\\server\share\workspace`, "Ubuntu")), JSON.stringify({ kind: "windows", path: String.raw `\\server\share\workspace` }));
|
|
27
|
+
});
|
|
28
|
+
it("rejects WSL workspace folders from a different distro", () => {
|
|
29
|
+
assert.equal(resolveWslWorkingDirectory(String.raw `\\wsl.localhost\Debian\home\dev\workspace`, "Ubuntu"), null);
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
describe("buildWindowsSpawnSpec", () => {
|
|
33
|
+
it("wraps WSL binaries with wsl.exe and propagates required env vars", () => {
|
|
34
|
+
const spec = buildWindowsSpawnSpec(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`, ["serve", "--port", "0"], {
|
|
35
|
+
cwd: String.raw `\\wsl.localhost\Ubuntu\home\dev\workspace`,
|
|
36
|
+
env: {
|
|
37
|
+
OPENCODE_CONFIG_CONTENT: JSON.stringify({ plugin: ["file:///C:/Users/dev/AppData/Roaming/CodeNomad/plugin.tgz"] }),
|
|
38
|
+
CODENOMAD_INSTANCE_ID: "workspace-123",
|
|
39
|
+
OPENCODE_SERVER_BASE_URL: "https://127.0.0.1:4321/workspaces/workspace-123/worktrees/root/instance",
|
|
40
|
+
OPENCODE_SERVER_PASSWORD: "secret",
|
|
41
|
+
},
|
|
42
|
+
propagateEnvKeys: ["OPENCODE_CONFIG_CONTENT", "CODENOMAD_INSTANCE_ID", "OPENCODE_SERVER_BASE_URL", "OPENCODE_SERVER_PASSWORD"],
|
|
43
|
+
});
|
|
44
|
+
assert.equal(spec.command, "wsl.exe");
|
|
45
|
+
assert.deepEqual(spec.args, [
|
|
46
|
+
"--distribution",
|
|
47
|
+
"Ubuntu",
|
|
48
|
+
"--cd",
|
|
49
|
+
"/home/dev/workspace",
|
|
50
|
+
"--exec",
|
|
51
|
+
"/home/dev/.opencode/bin/opencode",
|
|
52
|
+
"serve",
|
|
53
|
+
"--port",
|
|
54
|
+
"0",
|
|
55
|
+
]);
|
|
56
|
+
assert.equal(spec.cwd, undefined);
|
|
57
|
+
assert.equal(spec.env?.WSLENV, "OPENCODE_CONFIG_CONTENT:CODENOMAD_INSTANCE_ID:OPENCODE_SERVER_BASE_URL:OPENCODE_SERVER_PASSWORD");
|
|
58
|
+
});
|
|
59
|
+
it("preserves non-path OPENCODE_CONFIG_CONTENT WSLENV entries", () => {
|
|
60
|
+
const spec = buildWindowsSpawnSpec(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`, ["serve"], {
|
|
61
|
+
env: {
|
|
62
|
+
OPENCODE_CONFIG_CONTENT: JSON.stringify({ plugin: ["file:///C:/Users/dev/AppData/Roaming/CodeNomad/plugin.tgz"] }),
|
|
63
|
+
WSLENV: "OPENCODE_CONFIG_CONTENT:CODENOMAD_INSTANCE_ID/u",
|
|
64
|
+
},
|
|
65
|
+
propagateEnvKeys: ["OPENCODE_CONFIG_CONTENT", "CODENOMAD_INSTANCE_ID"],
|
|
66
|
+
});
|
|
67
|
+
assert.equal(spec.env?.WSLENV, "OPENCODE_CONFIG_CONTENT:CODENOMAD_INSTANCE_ID/u");
|
|
68
|
+
});
|
|
69
|
+
it("rewrites packaged plugin paths for WSL before launching", () => {
|
|
70
|
+
const spec = buildWindowsSpawnSpec(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`, ["serve"], {
|
|
71
|
+
env: {
|
|
72
|
+
OPENCODE_CONFIG_CONTENT: JSON.stringify({
|
|
73
|
+
plugin: [
|
|
74
|
+
"@codenomad/codenomad-opencode-plugin@file:C:/Users/dev/AppData/Roaming/CodeNomad/codenomad-opencode-plugin.tgz",
|
|
75
|
+
],
|
|
76
|
+
}),
|
|
77
|
+
},
|
|
78
|
+
propagateEnvKeys: ["OPENCODE_CONFIG_CONTENT"],
|
|
79
|
+
});
|
|
80
|
+
assert.equal(spec.command, "wsl.exe");
|
|
81
|
+
assert.equal(spec.env?.CODENOMAD_OPENCODE_PLUGIN_WSL_PATH, String.raw `C:\Users\dev\AppData\Roaming\CodeNomad\codenomad-opencode-plugin.tgz`);
|
|
82
|
+
assert.match(spec.env?.OPENCODE_CONFIG_CONTENT ?? "", /__CODENOMAD_OPENCODE_PLUGIN_WSL_PATH__/);
|
|
83
|
+
assert.equal(spec.env?.WSLENV, "OPENCODE_CONFIG_CONTENT:CODENOMAD_OPENCODE_PLUGIN_WSL_PATH/p");
|
|
84
|
+
assert.deepEqual(spec.args.slice(0, 4), ["--distribution", "Ubuntu", "--exec", "sh"]);
|
|
85
|
+
assert.match(spec.args[5] ?? "", /CODENOMAD_OPENCODE_PLUGIN_WSL_PATH/);
|
|
86
|
+
});
|
|
87
|
+
it("propagates inherited known path variables even when they are not explicitly requested", () => {
|
|
88
|
+
const spec = buildWindowsSpawnSpec(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`, ["serve"], {
|
|
89
|
+
env: {
|
|
90
|
+
NODE_EXTRA_CA_CERTS: String.raw `C:\certs\root.pem`,
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
assert.equal(spec.env?.WSLENV, "NODE_EXTRA_CA_CERTS/p");
|
|
94
|
+
});
|
|
95
|
+
it("uses wslpath for Windows workspace folders instead of assuming /mnt", () => {
|
|
96
|
+
const spec = buildWindowsSpawnSpec(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`, ["serve", "--port", "0"], {
|
|
97
|
+
cwd: String.raw `C:\Users\dev\workspace`,
|
|
98
|
+
});
|
|
99
|
+
assert.equal(spec.command, "wsl.exe");
|
|
100
|
+
assert.deepEqual(spec.args, [
|
|
101
|
+
"--distribution",
|
|
102
|
+
"Ubuntu",
|
|
103
|
+
"--exec",
|
|
104
|
+
"sh",
|
|
105
|
+
"-lc",
|
|
106
|
+
'cd "$(wslpath -au "$1")" && shift && exec "$@"',
|
|
107
|
+
"codenomad-wsl-launch",
|
|
108
|
+
String.raw `C:\Users\dev\workspace`,
|
|
109
|
+
"/home/dev/.opencode/bin/opencode",
|
|
110
|
+
"serve",
|
|
111
|
+
"--port",
|
|
112
|
+
"0",
|
|
113
|
+
]);
|
|
114
|
+
});
|
|
115
|
+
it("uses wslpath for UNC network workspace folders", () => {
|
|
116
|
+
const spec = buildWindowsSpawnSpec(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`, ["serve"], {
|
|
117
|
+
cwd: String.raw `\\server\share\workspace`,
|
|
118
|
+
});
|
|
119
|
+
assert.equal(spec.command, "wsl.exe");
|
|
120
|
+
assert.deepEqual(spec.args, [
|
|
121
|
+
"--distribution",
|
|
122
|
+
"Ubuntu",
|
|
123
|
+
"--exec",
|
|
124
|
+
"sh",
|
|
125
|
+
"-lc",
|
|
126
|
+
'cd "$(wslpath -au "$1")" && shift && exec "$@"',
|
|
127
|
+
"codenomad-wsl-launch",
|
|
128
|
+
String.raw `\\server\share\workspace`,
|
|
129
|
+
"/home/dev/.opencode/bin/opencode",
|
|
130
|
+
"serve",
|
|
131
|
+
]);
|
|
132
|
+
});
|
|
133
|
+
it("can wrap WSL launches to emit the Linux PID marker", () => {
|
|
134
|
+
const spec = buildWindowsSpawnSpec(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`, ["serve"], {
|
|
135
|
+
cwd: String.raw `\\wsl.localhost\Ubuntu\home\dev\workspace`,
|
|
136
|
+
wslPidMarker: "__CODENOMAD_WSL_PID__:",
|
|
137
|
+
});
|
|
138
|
+
assert.equal(spec.command, "wsl.exe");
|
|
139
|
+
assert.deepEqual(spec.args, [
|
|
140
|
+
"--distribution",
|
|
141
|
+
"Ubuntu",
|
|
142
|
+
"--exec",
|
|
143
|
+
"sh",
|
|
144
|
+
"-lc",
|
|
145
|
+
`printf '%s%s\\n' '__CODENOMAD_WSL_PID__:' "$$" && cd "$1" && shift && exec "$@"`,
|
|
146
|
+
"codenomad-wsl-launch",
|
|
147
|
+
"/home/dev/workspace",
|
|
148
|
+
"/home/dev/.opencode/bin/opencode",
|
|
149
|
+
"serve",
|
|
150
|
+
]);
|
|
151
|
+
assert.equal(spec.wsl?.pidMarker, "__CODENOMAD_WSL_PID__:");
|
|
152
|
+
});
|
|
153
|
+
it("builds the WSL kill command for tracked Linux PIDs", () => {
|
|
154
|
+
const spec = buildWslSignalSpec("Ubuntu", 4321, "SIGTERM");
|
|
155
|
+
assert.equal(spec.command, "wsl.exe");
|
|
156
|
+
assert.deepEqual(spec.args, ["--distribution", "Ubuntu", "--exec", "kill", "-TERM", "4321"]);
|
|
157
|
+
});
|
|
158
|
+
});
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { spawn } from "child_process";
|
|
4
|
+
import { homedir } from "os";
|
|
5
|
+
class GitCloneError extends Error {
|
|
6
|
+
constructor(message, statusCode = 400) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "GitCloneError";
|
|
9
|
+
this.statusCode = statusCode;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function formatErrorMessage(error, fallback) {
|
|
13
|
+
if (error instanceof Error && error.message.trim().length > 0) {
|
|
14
|
+
return error.message;
|
|
15
|
+
}
|
|
16
|
+
return fallback;
|
|
17
|
+
}
|
|
18
|
+
function normalizePathForComparison(filePath) {
|
|
19
|
+
const resolvedPath = path.resolve(filePath);
|
|
20
|
+
const rootPath = path.parse(resolvedPath).root;
|
|
21
|
+
const trimmedPath = resolvedPath === rootPath ? rootPath : resolvedPath.replace(/[\\/]+$/, "");
|
|
22
|
+
return process.platform === "win32" ? trimmedPath.toLowerCase() : trimmedPath;
|
|
23
|
+
}
|
|
24
|
+
function assertDestinationPathIsSafe(destinationPath) {
|
|
25
|
+
const normalizedDestinationPath = normalizePathForComparison(destinationPath);
|
|
26
|
+
const normalizedRootPath = normalizePathForComparison(path.parse(destinationPath).root);
|
|
27
|
+
if (normalizedDestinationPath === normalizedRootPath) {
|
|
28
|
+
throw new GitCloneError("Destination path cannot be a filesystem root", 400);
|
|
29
|
+
}
|
|
30
|
+
const normalizedHomePath = normalizePathForComparison(homedir());
|
|
31
|
+
if (normalizedDestinationPath === normalizedHomePath) {
|
|
32
|
+
throw new GitCloneError("Destination path cannot be the home folder", 400);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function createSiblingUniquePath(destinationPath, label) {
|
|
36
|
+
const parentPath = path.dirname(destinationPath);
|
|
37
|
+
const baseName = path.basename(destinationPath);
|
|
38
|
+
return path.join(parentPath, `${baseName}.${label}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
|
39
|
+
}
|
|
40
|
+
function runGitClone(repositoryUrl, destinationPath) {
|
|
41
|
+
return new Promise((resolve, reject) => {
|
|
42
|
+
const parentPath = path.dirname(destinationPath);
|
|
43
|
+
const child = spawn("git", ["clone", "--", repositoryUrl, destinationPath], {
|
|
44
|
+
cwd: parentPath,
|
|
45
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
46
|
+
});
|
|
47
|
+
let stderr = "";
|
|
48
|
+
child.stderr?.on("data", (chunk) => {
|
|
49
|
+
stderr += chunk.toString();
|
|
50
|
+
});
|
|
51
|
+
child.once("error", (error) => {
|
|
52
|
+
reject(new GitCloneError(error.message || "Failed to start git clone", 500));
|
|
53
|
+
});
|
|
54
|
+
child.once("close", (code) => {
|
|
55
|
+
if (code === 0) {
|
|
56
|
+
resolve();
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
reject(new GitCloneError(stderr.trim() || `git clone failed with code ${code}`, 409));
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
function assertDestinationIsUsable(destinationPath, cleanup) {
|
|
64
|
+
if (!fs.existsSync(destinationPath))
|
|
65
|
+
return;
|
|
66
|
+
const stat = fs.statSync(destinationPath);
|
|
67
|
+
if (!stat.isDirectory()) {
|
|
68
|
+
throw new GitCloneError("Destination path exists and is not a folder", 409);
|
|
69
|
+
}
|
|
70
|
+
if (cleanup) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const entries = fs.readdirSync(destinationPath);
|
|
74
|
+
if (entries.length > 0) {
|
|
75
|
+
throw new GitCloneError("Destination folder is not empty", 409);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function ensureDestinationParentExists(destinationPath) {
|
|
79
|
+
const parentPath = path.dirname(destinationPath);
|
|
80
|
+
if (fs.existsSync(parentPath))
|
|
81
|
+
return;
|
|
82
|
+
fs.mkdirSync(parentPath, { recursive: true });
|
|
83
|
+
}
|
|
84
|
+
async function replaceDestinationAfterSuccessfulClone(repositoryUrl, destinationPath) {
|
|
85
|
+
const tempClonePath = createSiblingUniquePath(destinationPath, "clone");
|
|
86
|
+
let backupPath = null;
|
|
87
|
+
let preserveBackup = false;
|
|
88
|
+
try {
|
|
89
|
+
await runGitClone(repositoryUrl, tempClonePath);
|
|
90
|
+
backupPath = createSiblingUniquePath(destinationPath, "backup");
|
|
91
|
+
fs.renameSync(destinationPath, backupPath);
|
|
92
|
+
try {
|
|
93
|
+
fs.renameSync(tempClonePath, destinationPath);
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
try {
|
|
97
|
+
fs.renameSync(backupPath, destinationPath);
|
|
98
|
+
backupPath = null;
|
|
99
|
+
}
|
|
100
|
+
catch (restoreError) {
|
|
101
|
+
preserveBackup = true;
|
|
102
|
+
throw new GitCloneError(`Failed to replace clone destination and restore previous contents: ${formatErrorMessage(restoreError, "restore failed")}`, 500);
|
|
103
|
+
}
|
|
104
|
+
throw new GitCloneError(`Failed to replace clone destination: ${formatErrorMessage(error, "rename failed")}`, 500);
|
|
105
|
+
}
|
|
106
|
+
fs.rmSync(backupPath, { recursive: true, force: true });
|
|
107
|
+
backupPath = null;
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (error instanceof GitCloneError) {
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
throw new GitCloneError(`Failed to prepare clone destination: ${formatErrorMessage(error, "unknown error")}`, 500);
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
if (backupPath && !preserveBackup && fs.existsSync(backupPath)) {
|
|
117
|
+
fs.rmSync(backupPath, { recursive: true, force: true });
|
|
118
|
+
}
|
|
119
|
+
if (fs.existsSync(tempClonePath)) {
|
|
120
|
+
fs.rmSync(tempClonePath, { recursive: true, force: true });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
export function isGitCloneError(error) {
|
|
125
|
+
return error instanceof GitCloneError;
|
|
126
|
+
}
|
|
127
|
+
export async function cloneGitRepository(params) {
|
|
128
|
+
const repositoryUrl = params.repositoryUrl.trim();
|
|
129
|
+
const requestedDestinationPath = params.destinationPath.trim();
|
|
130
|
+
if (!repositoryUrl) {
|
|
131
|
+
throw new GitCloneError("Repository URL is required", 400);
|
|
132
|
+
}
|
|
133
|
+
if (!path.isAbsolute(requestedDestinationPath)) {
|
|
134
|
+
throw new GitCloneError("Destination path must be absolute", 400);
|
|
135
|
+
}
|
|
136
|
+
const destinationPath = path.resolve(requestedDestinationPath);
|
|
137
|
+
assertDestinationPathIsSafe(destinationPath);
|
|
138
|
+
ensureDestinationParentExists(destinationPath);
|
|
139
|
+
const destinationExists = fs.existsSync(destinationPath);
|
|
140
|
+
assertDestinationIsUsable(destinationPath, Boolean(params.cleanup));
|
|
141
|
+
if (destinationExists && params.cleanup) {
|
|
142
|
+
await replaceDestinationAfterSuccessfulClone(repositoryUrl, destinationPath);
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
await runGitClone(repositoryUrl, destinationPath);
|
|
146
|
+
}
|
|
147
|
+
return { path: destinationPath };
|
|
148
|
+
}
|