forked from anomalyco/opencode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
623 lines (540 loc) · 22.6 KB
/
Copy pathindex.ts
File metadata and controls
623 lines (540 loc) · 22.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { path } from "@opencode-ai/core/effect/app-node-platform"
import { Global } from "@opencode-ai/core/global"
import { InstanceStore } from "@/project/instance-store"
import { Project } from "@/project/project"
import { Database } from "@opencode-ai/core/database/database"
import { eq } from "drizzle-orm"
import { ProjectTable } from "@opencode-ai/core/project/sql"
import type { ProjectV2 } from "@opencode-ai/core/project"
import { Slug } from "@opencode-ai/core/util/slug"
import { errorMessage } from "../util/error"
import { GlobalBus } from "@/bus/global"
import { Git } from "@/git"
import { Effect, Layer, Path, Schema, Scope, Context } from "effect"
import { ChildProcess } from "effect/unstable/process"
import { FSUtil } from "@opencode-ai/core/fs-util"
import { AppProcess } from "@opencode-ai/core/process"
import { InstanceState } from "@/effect/instance-state"
import { WorktreeEvent } from "@opencode-ai/schema/worktree-event"
export const Event = WorktreeEvent
export const Info = Schema.Struct({
name: Schema.String,
branch: Schema.optional(Schema.String),
directory: Schema.String,
}).annotate({ identifier: "Worktree" })
export type Info = Schema.Schema.Type<typeof Info>
export const CreateInput = Schema.Struct({
name: Schema.optional(Schema.String),
startCommand: Schema.optional(
Schema.String.annotate({ description: "Additional startup script to run after the project's start command" }),
),
}).annotate({ identifier: "WorktreeCreateInput" })
export type CreateInput = Schema.Schema.Type<typeof CreateInput>
export const RemoveInput = Schema.Struct({
directory: Schema.String,
}).annotate({ identifier: "WorktreeRemoveInput" })
export type RemoveInput = Schema.Schema.Type<typeof RemoveInput>
export const ResetInput = Schema.Struct({
directory: Schema.String,
}).annotate({ identifier: "WorktreeResetInput" })
export type ResetInput = Schema.Schema.Type<typeof ResetInput>
export class NotGitError extends Schema.TaggedErrorClass<NotGitError>()("WorktreeNotGitError", {
message: Schema.String,
}) {}
export class NameGenerationFailedError extends Schema.TaggedErrorClass<NameGenerationFailedError>()(
"WorktreeNameGenerationFailedError",
{
message: Schema.String,
},
) {}
export class CreateFailedError extends Schema.TaggedErrorClass<CreateFailedError>()("WorktreeCreateFailedError", {
message: Schema.String,
}) {}
export class StartCommandFailedError extends Schema.TaggedErrorClass<StartCommandFailedError>()(
"WorktreeStartCommandFailedError",
{
message: Schema.String,
},
) {}
export class RemoveFailedError extends Schema.TaggedErrorClass<RemoveFailedError>()("WorktreeRemoveFailedError", {
message: Schema.String,
}) {}
export class ResetFailedError extends Schema.TaggedErrorClass<ResetFailedError>()("WorktreeResetFailedError", {
message: Schema.String,
}) {}
export class ListFailedError extends Schema.TaggedErrorClass<ListFailedError>()("WorktreeListFailedError", {
message: Schema.String,
}) {}
export type Error =
| NotGitError
| NameGenerationFailedError
| CreateFailedError
| StartCommandFailedError
| RemoveFailedError
| ResetFailedError
| ListFailedError
function slugify(input: string) {
return input
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+/, "")
.replace(/-+$/, "")
}
function failedRemoves(...chunks: string[]) {
return chunks.filter(Boolean).flatMap((chunk) =>
chunk
.split("\n")
.map((line) => line.trim())
.flatMap((line) => {
const match = line.match(/^warning:\s+failed to remove\s+(.+):\s+/i)
if (!match) return []
const value = match[1]?.trim().replace(/^['"]|['"]$/g, "")
if (!value) return []
return [value]
}),
)
}
// ---------------------------------------------------------------------------
// Effect service
// ---------------------------------------------------------------------------
export interface Interface {
readonly makeWorktreeInfo: (options?: { name?: string; detached?: boolean }) => Effect.Effect<Info, Error>
readonly createFromInfo: (info: Info, startCommand?: string) => Effect.Effect<void, Error>
readonly create: (input?: CreateInput) => Effect.Effect<Info, Error>
readonly list: () => Effect.Effect<(Omit<Info, "branch"> & { branch?: string })[], Error>
readonly remove: (input: RemoveInput) => Effect.Effect<boolean, Error>
readonly reset: (input: ResetInput) => Effect.Effect<boolean, Error>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/Worktree") {}
type GitResult = { code: number; text: string; stderr: string }
const layer: Layer.Layer<
Service,
never,
| FSUtil.Service
| Path.Path
| AppProcess.Service
| Git.Service
| Project.Service
| InstanceStore.Service
| Database.Service
> = Layer.effect(
Service,
Effect.gen(function* () {
const scope = yield* Scope.Scope
const fs = yield* FSUtil.Service
const pathSvc = yield* Path.Path
const appProcess = yield* AppProcess.Service
const { db } = yield* Database.Service
const gitSvc = yield* Git.Service
const project = yield* Project.Service
const store = yield* InstanceStore.Service
const git = Effect.fnUntraced(
function* (args: string[], opts?: { cwd?: string }) {
const result = yield* appProcess.run(
ChildProcess.make("git", args, { cwd: opts?.cwd, extendEnv: true, stdin: "ignore" }),
)
return {
code: result.exitCode,
text: result.stdout.toString("utf8"),
stderr: result.stderr.toString("utf8"),
} satisfies GitResult
},
Effect.catch((e) =>
Effect.succeed({
code: 1,
text: "",
stderr: e instanceof Error ? e.message : String(e),
} satisfies GitResult),
),
)
const MAX_NAME_ATTEMPTS = 26
const candidate = Effect.fn("Worktree.candidate")(function* (input: {
root: string
name?: string
detached?: boolean
}) {
const ctx = yield* InstanceState.context
for (const attempt of Array.from({ length: MAX_NAME_ATTEMPTS }, (_, i) => i)) {
const name = input.name ? (attempt === 0 ? input.name : `${input.name}-${Slug.create()}`) : Slug.create()
const branch = input.detached ? undefined : `opencode/${name}`
const directory = pathSvc.join(input.root, name)
if (yield* fs.exists(directory).pipe(Effect.orDie)) continue
if (branch) {
const ref = `refs/heads/${branch}`
const branchCheck = yield* git(["show-ref", "--verify", "--quiet", ref], { cwd: ctx.worktree })
if (branchCheck.code === 0) continue
}
return { name, directory, ...(branch ? { branch } : {}) }
}
return yield* new NameGenerationFailedError({ message: "Failed to generate a unique worktree name" })
})
const makeWorktreeInfo = Effect.fn("Worktree.makeWorktreeInfo")(function* (input?: {
name?: string
detached?: boolean
}) {
const ctx = yield* InstanceState.context
if (ctx.project.vcs !== "git") {
return yield* new NotGitError({ message: "Worktrees are only supported for git projects" })
}
const root = pathSvc.join(Global.Path.data, "worktree", ctx.project.id)
yield* fs.makeDirectory(root, { recursive: true }).pipe(Effect.orDie)
return yield* candidate({ root, name: input?.name ? slugify(input.name) : "", detached: input?.detached })
})
const setup = Effect.fnUntraced(function* (info: Info) {
const ctx = yield* InstanceState.context
const created = yield* git(
info.branch
? ["worktree", "add", "--no-checkout", "-b", info.branch, info.directory]
: ["worktree", "add", "--no-checkout", "--detach", info.directory, "HEAD"],
{ cwd: ctx.worktree },
)
if (created.code !== 0) {
return yield* new CreateFailedError({
message: created.stderr || created.text || "Failed to create git worktree",
})
}
yield* project.addSandbox(ctx.project.id, info.directory).pipe(Effect.catch(() => Effect.void))
})
const boot = Effect.fnUntraced(function* (info: Info, startCommand?: string) {
const ctx = yield* InstanceState.context
const workspaceID = yield* InstanceState.workspaceID
const projectID = ctx.project.id
const extra = startCommand?.trim()
const populated = yield* git(["reset", "--hard"], { cwd: info.directory })
if (populated.code !== 0) {
const message = populated.stderr || populated.text || "Failed to populate worktree"
yield* Effect.logError("worktree checkout failed", { directory: info.directory, message })
GlobalBus.emit("event", {
directory: info.directory,
project: ctx.project.id,
workspace: workspaceID,
payload: { type: Event.Failed.type, properties: { message } },
})
return
}
const booted = yield* store.load({ directory: info.directory }).pipe(
Effect.as(true),
Effect.catch((error) =>
Effect.gen(function* () {
const message = errorMessage(error)
yield* Effect.logError("worktree bootstrap failed", { directory: info.directory, message })
GlobalBus.emit("event", {
directory: info.directory,
project: ctx.project.id,
workspace: workspaceID,
payload: { type: Event.Failed.type, properties: { message } },
})
return false
}),
),
)
if (!booted) return
GlobalBus.emit("event", {
directory: info.directory,
project: ctx.project.id,
workspace: workspaceID,
payload: {
type: Event.Ready.type,
properties: { name: info.name, ...(info.branch ? { branch: info.branch } : {}) },
},
})
yield* runStartScripts(info.directory, { projectID, extra })
})
const createFromInfo = Effect.fn("Worktree.createFromInfo")(function* (info: Info, startCommand?: string) {
yield* setup(info)
yield* boot(info, startCommand).pipe(
Effect.catchCause((cause) => Effect.logError("worktree bootstrap failed", { cause })),
Effect.forkIn(scope),
)
})
const create = Effect.fn("Worktree.create")(function* (input?: CreateInput) {
const info = yield* makeWorktreeInfo({ name: input?.name })
yield* createFromInfo(info, input?.startCommand)
return info
})
const canonical = Effect.fnUntraced(function* (input: string) {
const abs = pathSvc.resolve(input)
const real = yield* fs.realPath(abs).pipe(Effect.catch(() => Effect.succeed(abs)))
const normalized = pathSvc.normalize(real)
return process.platform === "win32" ? normalized.toLowerCase() : normalized
})
function parseWorktreeList(text: string) {
return text
.split("\n")
.map((line) => line.trim())
.reduce<{ path?: string; branch?: string }[]>((acc, line) => {
if (!line) return acc
if (line.startsWith("worktree ")) {
acc.push({ path: line.slice("worktree ".length).trim() })
return acc
}
const current = acc[acc.length - 1]
if (!current) return acc
if (line.startsWith("branch ")) {
current.branch = line.slice("branch ".length).trim()
}
return acc
}, [])
}
const locateWorktree = Effect.fnUntraced(function* (
entries: { path?: string; branch?: string }[],
directory: string,
) {
for (const item of entries) {
if (!item.path) continue
const key = yield* canonical(item.path)
if (key === directory) return item
}
return undefined
})
const list = Effect.fn("Worktree.list")(function* () {
const ctx = yield* InstanceState.context
if (ctx.project.vcs !== "git") {
return []
}
const result = yield* git(["worktree", "list", "--porcelain"], { cwd: ctx.worktree })
if (result.code !== 0) {
return yield* new ListFailedError({ message: result.stderr || result.text || "Failed to read git worktrees" })
}
const primary = yield* canonical(ctx.project.worktree)
const primaryName = pathSvc.basename(primary).toLowerCase()
return yield* Effect.forEach(parseWorktreeList(result.text), (entry) =>
Effect.gen(function* () {
if (!entry.path) return undefined
const directory = yield* canonical(entry.path)
if (directory === primary) return undefined
const name = pathSvc.basename(directory).toLowerCase()
return {
name: name === primaryName ? pathSvc.basename(pathSvc.dirname(directory)) : name,
directory,
...(entry.branch ? { branch: entry.branch.replace(/^refs\/heads\//, "") } : {}),
}
}),
).pipe(Effect.map((items) => items.filter((item) => item !== undefined)))
})
function stopFsmonitor(target: string) {
return fs.exists(target).pipe(
Effect.orDie,
Effect.flatMap((exists) => (exists ? git(["fsmonitor--daemon", "stop"], { cwd: target }) : Effect.void)),
)
}
function cleanDirectory(target: string) {
return Effect.tryPromise({
try: async () => {
const fsp = await import("fs/promises")
const attempts = process.platform === "win32" ? 50 : 5
for (const attempt of Array.from({ length: attempts }, (_, i) => i)) {
try {
await fsp.rm(target, { recursive: true, force: true })
return
} catch (error) {
if (attempt === attempts - 1) throw error
await new Promise((resolve) => setTimeout(resolve, 100))
}
}
},
catch: (error) =>
new RemoveFailedError({ message: errorMessage(error) || "Failed to remove git worktree directory" }),
})
}
const remove = Effect.fn("Worktree.remove")(function* (input: RemoveInput) {
const ctx = yield* InstanceState.context
if (ctx.project.vcs !== "git") {
return yield* new NotGitError({ message: "Worktrees are only supported for git projects" })
}
const directory = yield* canonical(input.directory)
// Preserve the loaded path casing for the store cache; `directory` is lowercased on Windows.
if (directory !== (yield* canonical(ctx.worktree))) yield* store.disposeDirectory(input.directory)
const list = yield* git(["worktree", "list", "--porcelain"], { cwd: ctx.worktree })
if (list.code !== 0) {
return yield* new RemoveFailedError({ message: list.stderr || list.text || "Failed to read git worktrees" })
}
const entries = parseWorktreeList(list.text)
const entry = yield* locateWorktree(entries, directory)
if (!entry?.path) {
const directoryExists = yield* fs.exists(directory).pipe(Effect.orDie)
if (directoryExists) {
yield* stopFsmonitor(directory)
yield* cleanDirectory(directory)
}
return true
}
// Git may return the original casing when a caller supplied a normalized Windows path.
yield* store.disposeDirectory(entry.path)
yield* stopFsmonitor(entry.path)
const removed = yield* git(["worktree", "remove", "--force", entry.path], { cwd: ctx.worktree })
if (removed.code !== 0) {
const next = yield* git(["worktree", "list", "--porcelain"], { cwd: ctx.worktree })
if (next.code !== 0) {
return yield* new RemoveFailedError({
message: removed.stderr || removed.text || next.stderr || next.text || "Failed to remove git worktree",
})
}
const stale = yield* locateWorktree(parseWorktreeList(next.text), directory)
if (stale?.path) {
return yield* new RemoveFailedError({
message: removed.stderr || removed.text || "Failed to remove git worktree",
})
}
}
yield* cleanDirectory(entry.path)
const branch = entry.branch?.replace(/^refs\/heads\//, "")
if (branch) {
const deleted = yield* git(["branch", "-D", branch], { cwd: ctx.worktree })
if (deleted.code !== 0) {
return yield* new RemoveFailedError({
message: deleted.stderr || deleted.text || "Failed to delete worktree branch",
})
}
}
return true
})
const gitExpect = Effect.fnUntraced(function* (
args: string[],
opts: { cwd: string },
error: (r: GitResult) => Error,
) {
const result = yield* git(args, opts)
if (result.code !== 0) return yield* error(result)
return result
})
const runStartCommand = Effect.fnUntraced(
function* (directory: string, cmd: string) {
const [shell, args] = process.platform === "win32" ? ["cmd", ["/c", cmd]] : ["bash", ["-lc", cmd]]
const result = yield* appProcess.run(
ChildProcess.make(shell, args as string[], { cwd: directory, extendEnv: true, stdin: "ignore" }),
)
return { code: result.exitCode, stderr: result.stderr.toString("utf8") }
},
Effect.catch(() => Effect.succeed({ code: 1, stderr: "" })),
)
const runStartScript = Effect.fnUntraced(function* (directory: string, cmd: string, kind: string) {
const text = cmd.trim()
if (!text) return true
const result = yield* runStartCommand(directory, text)
if (result.code === 0) return true
yield* Effect.logError("worktree start command failed", { kind, directory, message: result.stderr })
return false
})
const runStartScripts = Effect.fnUntraced(function* (
directory: string,
input: { projectID: ProjectV2.ID; extra?: string },
) {
const row = yield* db
.select()
.from(ProjectTable)
.where(eq(ProjectTable.id, input.projectID))
.get()
.pipe(Effect.orDie)
const project = row ? Project.fromRow(row) : undefined
const startup = project?.commands?.start?.trim() ?? ""
const ok = yield* runStartScript(directory, startup, "project")
if (!ok) return false
yield* runStartScript(directory, input.extra ?? "", "worktree")
return true
})
const prune = Effect.fnUntraced(function* (root: string, entries: string[]) {
const base = yield* canonical(root)
yield* Effect.forEach(
entries,
(entry) =>
Effect.gen(function* () {
const target = yield* canonical(pathSvc.resolve(root, entry))
if (target === base) return
if (!target.startsWith(`${base}${pathSvc.sep}`)) return
yield* fs.remove(target, { recursive: true }).pipe(Effect.ignore)
}),
{ concurrency: "unbounded" },
)
})
const sweep = Effect.fnUntraced(function* (root: string) {
const first = yield* git(["clean", "-ffdx"], { cwd: root })
if (first.code === 0) return first
const entries = failedRemoves(first.stderr, first.text)
if (!entries.length) return first
yield* prune(root, entries)
return yield* git(["clean", "-ffdx"], { cwd: root })
})
const reset = Effect.fn("Worktree.reset")(function* (input: ResetInput) {
const ctx = yield* InstanceState.context
if (ctx.project.vcs !== "git") {
return yield* new NotGitError({ message: "Worktrees are only supported for git projects" })
}
const directory = yield* canonical(input.directory)
const primary = yield* canonical(ctx.worktree)
if (directory === primary) {
return yield* new ResetFailedError({ message: "Cannot reset the primary workspace" })
}
const list = yield* git(["worktree", "list", "--porcelain"], { cwd: ctx.worktree })
if (list.code !== 0) {
return yield* new ResetFailedError({ message: list.stderr || list.text || "Failed to read git worktrees" })
}
const entry = yield* locateWorktree(parseWorktreeList(list.text), directory)
if (!entry?.path) {
return yield* new ResetFailedError({ message: "Worktree not found" })
}
const worktreePath = entry.path
const base = yield* gitSvc.defaultBranch(ctx.worktree)
if (!base) {
return yield* new ResetFailedError({ message: "Default branch not found" })
}
const sep = base.ref.indexOf("/")
if (base.ref !== base.name && sep > 0) {
const remote = base.ref.slice(0, sep)
const branch = base.ref.slice(sep + 1)
yield* gitExpect(
["fetch", remote, branch],
{ cwd: ctx.worktree },
(r) => new ResetFailedError({ message: r.stderr || r.text || `Failed to fetch ${base.ref}` }),
)
}
yield* gitExpect(
["reset", "--hard", base.ref],
{ cwd: worktreePath },
(r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to reset worktree to target" }),
)
const cleanResult = yield* sweep(worktreePath)
if (cleanResult.code !== 0) {
return yield* new ResetFailedError({
message: cleanResult.stderr || cleanResult.text || "Failed to clean worktree",
})
}
yield* gitExpect(
["submodule", "update", "--init", "--recursive", "--force"],
{ cwd: worktreePath },
(r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to update submodules" }),
)
yield* gitExpect(
["submodule", "foreach", "--recursive", "git", "reset", "--hard"],
{ cwd: worktreePath },
(r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to reset submodules" }),
)
yield* gitExpect(
["submodule", "foreach", "--recursive", "git", "clean", "-fdx"],
{ cwd: worktreePath },
(r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to clean submodules" }),
)
const status = yield* git(["-c", "core.fsmonitor=false", "status", "--porcelain=v1"], { cwd: worktreePath })
if (status.code !== 0) {
return yield* new ResetFailedError({ message: status.stderr || status.text || "Failed to read git status" })
}
if (status.text.trim()) {
return yield* new ResetFailedError({ message: `Worktree reset left local changes:\n${status.text.trim()}` })
}
yield* runStartScripts(worktreePath, { projectID: ctx.project.id }).pipe(
Effect.catchCause((cause) => Effect.logError("worktree start task failed", { cause })),
Effect.forkIn(scope),
)
return true
})
return Service.of({ makeWorktreeInfo, createFromInfo, create, list, remove, reset })
}),
)
export const node = LayerNode.make({
service: Service,
layer: layer,
deps: [FSUtil.node, path, AppProcess.node, Git.node, Project.node, InstanceStore.node, Database.node],
})
export * as Worktree from "."