forked from anomalyco/opencode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworktree.ts
More file actions
76 lines (68 loc) · 1.96 KB
/
Copy pathworktree.ts
File metadata and controls
76 lines (68 loc) · 1.96 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
import { ScopedKey, type ServerScope } from "@/utils/server-scope"
const normalize = (directory: string) => directory.replace(/[\\/]+$/, "")
const key = (scope: ServerScope, directory: string) => ScopedKey.from(scope, normalize(directory))
type State =
| {
status: "pending"
}
| {
status: "ready"
}
| {
status: "failed"
message: string
}
const state = new Map<string, State>()
const waiters = new Map<
string,
{
promise: Promise<State>
resolve: (state: State) => void
}
>()
function deferred() {
const box = { resolve: (_: State) => {} }
const promise = new Promise<State>((resolve) => {
box.resolve = resolve
})
return { promise, resolve: box.resolve }
}
export const Worktree = {
get(scope: ServerScope, directory: string) {
return state.get(key(scope, directory))
},
pending(scope: ServerScope, directory: string) {
const id = key(scope, directory)
const current = state.get(id)
if (current && current.status !== "pending") return
state.set(id, { status: "pending" })
},
ready(scope: ServerScope, directory: string) {
const id = key(scope, directory)
const next = { status: "ready" } as const
state.set(id, next)
const waiter = waiters.get(id)
if (!waiter) return
waiters.delete(id)
waiter.resolve(next)
},
failed(scope: ServerScope, directory: string, message: string) {
const id = key(scope, directory)
const next = { status: "failed", message } as const
state.set(id, next)
const waiter = waiters.get(id)
if (!waiter) return
waiters.delete(id)
waiter.resolve(next)
},
wait(scope: ServerScope, directory: string) {
const id = key(scope, directory)
const current = state.get(id)
if (current && current.status !== "pending") return Promise.resolve(current)
const existing = waiters.get(id)
if (existing) return existing.promise
const waiter = deferred()
waiters.set(id, waiter)
return waiter.promise
},
}