summaryrefslogtreecommitdiffhomepage
path: root/packages/app/src/utils/worktree.ts
blob: 7c0055920b7c5da54542bfdd3cfffd4d3db4b34a (plain)
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
const normalize = (directory: string) => directory.replace(/[\\/]+$/, "")

type State =
  | {
      status: "pending"
    }
  | {
      status: "ready"
    }
  | {
      status: "failed"
      message: string
    }

const state = new Map<string, State>()
const waiters = new Map<string, Array<(state: State) => void>>()

export const Worktree = {
  get(directory: string) {
    return state.get(normalize(directory))
  },
  pending(directory: string) {
    const key = normalize(directory)
    const current = state.get(key)
    if (current && current.status !== "pending") return
    state.set(key, { status: "pending" })
  },
  ready(directory: string) {
    const key = normalize(directory)
    state.set(key, { status: "ready" })
    const list = waiters.get(key)
    if (!list) return
    waiters.delete(key)
    for (const fn of list) fn({ status: "ready" })
  },
  failed(directory: string, message: string) {
    const key = normalize(directory)
    state.set(key, { status: "failed", message })
    const list = waiters.get(key)
    if (!list) return
    waiters.delete(key)
    for (const fn of list) fn({ status: "failed", message })
  },
  wait(directory: string) {
    const key = normalize(directory)
    const current = state.get(key)
    if (current && current.status !== "pending") return Promise.resolve(current)

    return new Promise<State>((resolve) => {
      const list = waiters.get(key)
      if (!list) {
        waiters.set(key, [resolve])
        return
      }
      list.push(resolve)
    })
  },
}