@kaynooo/cli-wt 0.1.2 → 0.1.7

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.
Files changed (47) hide show
  1. package/README.md +17 -10
  2. package/dist/cli-0gbs87r4.js +313 -0
  3. package/dist/cli-1nyesy1b.js +674 -0
  4. package/dist/cli-4g5ehhgn.js +251 -0
  5. package/dist/cli-6ybxw5sc.js +97 -0
  6. package/dist/cli-dmkfxdbr.js +153 -0
  7. package/dist/cli-dmzvmpge.js +106 -0
  8. package/dist/cli-e2h20nyy.js +36 -0
  9. package/dist/cli-j82fak6j.js +69 -0
  10. package/dist/cli-k4471y24.js +779 -0
  11. package/dist/cli-kek450vq.js +519 -0
  12. package/dist/cli-n5rt07v7.js +105 -0
  13. package/dist/cli-pkvw2k4x.js +37 -0
  14. package/dist/cli-w4w36hng.js +67 -0
  15. package/dist/cli.js +238 -2592
  16. package/dist/commands-jtnbchtb.js +222 -0
  17. package/dist/init-4ynjrztr.js +166 -0
  18. package/dist/list-js6drtvg.js +88 -0
  19. package/dist/print-q6qaqg22.js +77 -0
  20. package/dist/prompt-y71tp3f5.js +436 -0
  21. package/dist/prune-beweag7w.js +17 -0
  22. package/dist/run-7eayrqwy.js +18 -0
  23. package/dist/shell-xrgvqrpp.js +55 -0
  24. package/dist/stack-h3pgyx1e.js +20 -0
  25. package/dist/tools-4j56r47a.js +13 -0
  26. package/package.json +6 -6
  27. package/src/cli.ts +270 -76
  28. package/src/commands.ts +58 -42
  29. package/src/compose.ts +37 -14
  30. package/src/config.ts +8 -1
  31. package/src/errors.ts +31 -5
  32. package/src/files.ts +15 -23
  33. package/src/git.ts +53 -7
  34. package/src/index.ts +3 -2
  35. package/src/init.ts +56 -10
  36. package/src/jobs.ts +60 -19
  37. package/src/list.ts +26 -13
  38. package/src/print.ts +76 -0
  39. package/src/project.ts +134 -23
  40. package/src/proxy.ts +9 -9
  41. package/src/prune.ts +149 -0
  42. package/src/queue.ts +27 -3
  43. package/src/run.ts +82 -23
  44. package/src/shell.ts +34 -7
  45. package/src/stack.ts +10 -12
  46. package/src/sync.ts +28 -3
  47. package/src/tools.ts +91 -0
package/src/run.ts CHANGED
@@ -1,14 +1,15 @@
1
1
  import type { ComposeConfig } from './compose'
2
2
  import type { RunConfig, Worktree } from './project'
3
- import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
3
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
4
4
  import { userInfo } from 'node:os'
5
- import { join } from 'node:path'
5
+ import { join, resolve } from 'node:path'
6
+ import { holdSignals } from '@kaynooo/cli-kit'
6
7
  import { $ } from 'bun'
7
- import { composeConfig } from './compose'
8
+ import { baseComposeFiles, composeConfig } from './compose'
8
9
  import { wtConfig } from './config'
9
10
  import { readEnvFile } from './env_file'
10
- import { assertWorktreeExists, locateWorktree, WtError } from './project'
11
- import { inLine, queueDir } from './queue'
11
+ import { assertWorktreeExists, currentDir, locateWorktree, WtError } from './project'
12
+ import { holding, inLine, queueDir } from './queue'
12
13
 
13
14
  export interface TestDatabase {
14
15
  // The host the test env dials, which the throwaway database answers to on the private network.
@@ -18,6 +19,13 @@ export interface TestDatabase {
18
19
  password: string
19
20
  }
20
21
 
22
+ // What a run needs of main's compose config: where the service mounts the run dir, its image, and the test database's image.
23
+ export interface RunInputs {
24
+ target: string
25
+ image: string
26
+ databaseImage: string
27
+ }
28
+
21
29
  export interface RunPlan {
22
30
  network: string
23
31
  container: string
@@ -63,19 +71,57 @@ function databaseImage(config: ComposeConfig, host: string): string {
63
71
  return service.image
64
72
  }
65
73
 
66
- // The worktree's `dir` goes where the service mounts main's, so the image finds it where it expects; the database is one container per project, on a network of its own, so neither touches the user's stack.
67
- export function runPlan(worktree: Worktree, run: RunConfig, config: ComposeConfig, database: TestDatabase, ids: { uid: number, gid: number } = userInfo(), tty = false): RunPlan {
74
+ export function runInputs(root: string, run: RunConfig, config: ComposeConfig, host: string): RunInputs {
68
75
  const service = config.services[run.service]
69
76
 
70
77
  if (!service)
71
78
  throw new WtError(`${config.name} has no service ${run.service}`)
72
79
 
73
- const source = join(worktree.project.root, run.dir)
80
+ const source = join(root, run.dir)
74
81
  const target = service.volumes?.find(volume => volume.type === 'bind' && volume.source === source)?.target
75
82
 
76
83
  if (target === undefined)
77
84
  throw new WtError(`${run.service} does not bind-mount ${source}, so wt cannot tell where the worktree's copy goes`)
78
85
 
86
+ return { target, image: service.image ?? `${config.name}-${run.service}`, databaseImage: databaseImage(config, host) }
87
+ }
88
+
89
+ // The files main's compose config is read from, each with its size and time, a missing one (a project with no .env) as null.
90
+ function inputsKey(root: string, overrides: string, run: RunConfig, host: string): string {
91
+ const files = ['.env', ...baseComposeFiles(root, overrides)].map(file => resolve(root, file))
92
+
93
+ return JSON.stringify([run.service, run.dir, host, ...files.map((file) => {
94
+ const stat = statSync(file, { throwIfNoEntry: false })
95
+
96
+ return [file, stat?.mtimeMs ?? null, stat?.size ?? null]
97
+ })])
98
+ }
99
+
100
+ // Kept until main's .env or compose files change, so a repeated run skips `docker compose config`; a file they pull in (`include:`, `env_file`) is not in the key, so a change to it alone needs `<state>/<name>.run.json` deleted.
101
+ async function cachedRunInputs(worktree: Worktree, run: RunConfig, host: string): Promise<RunInputs> {
102
+ const { root, name, settings } = worktree.project
103
+ const file = join(settings.state, `${name}.run.json`)
104
+ const key = inputsKey(root, settings.overrides, run, host)
105
+
106
+ try {
107
+ const cached = JSON.parse(readFileSync(file, 'utf8')) as { key: string, inputs: RunInputs }
108
+
109
+ if (cached.key === key)
110
+ return cached.inputs
111
+ }
112
+ catch {}
113
+
114
+ const inputs = runInputs(root, run, await composeConfig(root), host)
115
+
116
+ mkdirSync(settings.state, { recursive: true })
117
+ writeFileSync(file, JSON.stringify({ key, inputs }))
118
+
119
+ return inputs
120
+ }
121
+
122
+ // The worktree's `dir` goes where the service mounts main's, so the image finds it where it expects; the database is one container per project, on a network of its own, so neither touches the user's stack.
123
+ export function runPlan(worktree: Worktree, run: RunConfig, inputs: RunInputs, database: TestDatabase, ids: { uid: number, gid: number } = userInfo(), tty = false): RunPlan {
124
+ const { target } = inputs
79
125
  const network = `wt-${worktree.project.name}-test`
80
126
  const container = testContainer(worktree)
81
127
 
@@ -99,7 +145,7 @@ export function runPlan(worktree: Worktree, run: RunConfig, config: ComposeConfi
99
145
  'POSTGRES_PASSWORD',
100
146
  '-e',
101
147
  `PGPORT=${database.port}`,
102
- databaseImage(config, database.host),
148
+ inputs.databaseImage,
103
149
  ],
104
150
  runner: command => [
105
151
  'run',
@@ -122,7 +168,7 @@ export function runPlan(worktree: Worktree, run: RunConfig, config: ComposeConfi
122
168
  `${join(worktree.dir, run.dir)}:${target}`,
123
169
  '-w',
124
170
  target,
125
- service.image ?? `${config.name}-${run.service}`,
171
+ inputs.image,
126
172
  ...command,
127
173
  ],
128
174
  }
@@ -134,6 +180,13 @@ async function runningId(container: string): Promise<string | undefined> {
134
180
  return result.text().trim() || undefined
135
181
  }
136
182
 
183
+ // The running database's id when it already answers, in one docker call: pg_isready, then its hostname, which Docker sets to the container's short id.
184
+ async function answeringDatabase(plan: RunPlan, database: TestDatabase): Promise<string | undefined> {
185
+ const result = await $`docker exec ${plan.container} sh -c ${'pg_isready -q -h 127.0.0.1 -U "$1" && hostname'} sh ${database.user}`.quiet().nothrow()
186
+
187
+ return result.exitCode === 0 ? result.text().trim() || undefined : undefined
188
+ }
189
+
137
190
  // Started once and shared by the project's worktrees until it is removed; its data lives in memory, so a restart means fresh databases.
138
191
  async function ensureDatabase(plan: RunPlan, database: TestDatabase): Promise<string> {
139
192
  if ((await $`docker network inspect ${plan.network}`.quiet().nothrow()).exitCode !== 0)
@@ -166,18 +219,16 @@ async function ensureDatabase(plan: RunPlan, database: TestDatabase): Promise<st
166
219
 
167
220
  // Forwards an interrupt to the child, a `docker run` passing it on to the container, and resolves with its exit code.
168
221
  export async function runInherit(command: string[]): Promise<number> {
222
+ const held = holdSignals()
169
223
  const child = Bun.spawn(command, { stdio: ['inherit', 'inherit', 'inherit'] })
170
- const forward = (signal: NodeJS.Signals) => child.kill(signal)
171
224
 
172
- process.on('SIGINT', forward)
173
- process.on('SIGTERM', forward)
225
+ held.forward(child)
174
226
 
175
227
  try {
176
228
  return await child.exited
177
229
  }
178
230
  finally {
179
- process.off('SIGINT', forward)
180
- process.off('SIGTERM', forward)
231
+ held.release()
181
232
  }
182
233
  }
183
234
 
@@ -218,7 +269,7 @@ async function provision(worktree: Worktree, run: RunConfig, plan: RunPlan, data
218
269
 
219
270
  for (const step of run.provision) {
220
271
  if (await runInherit(['docker', ...plan.runner(['sh', '-c', step])]) !== 0)
221
- throw new WtError(`provisioning failed on \`${step}\`, run it again with \`wt run ${worktree.task} -- sh -c '${step}'\``)
272
+ throw new WtError(`provisioning failed on \`${step}\``, `run it again with \`wt run ${worktree.task} -- sh -c '${step}'\``)
222
273
  }
223
274
 
224
275
  mkdirSync(markers, { recursive: true })
@@ -227,25 +278,33 @@ async function provision(worktree: Worktree, run: RunConfig, plan: RunPlan, data
227
278
  }
228
279
 
229
280
  export async function runTask(task: string, command: string[], project?: string): Promise<number> {
230
- const worktree = await locateWorktree(process.cwd(), task, project)
231
- const { run, name, root } = worktree.project
281
+ const worktree = await locateWorktree(currentDir(), task, project)
282
+ const { run, name } = worktree.project
232
283
 
233
284
  assertWorktreeExists(worktree)
234
285
 
235
286
  if (!run)
236
287
  throw new WtError(`${name} has no \`run\` in its manifest, so wt cannot tell which service runs its tests`)
237
288
 
238
- const database = testDatabase(join(worktree.dir, run.dir))
239
- const plan = runPlan(worktree, run, await composeConfig(root), database, userInfo(), Boolean(process.stdin.isTTY && process.stdout.isTTY))
289
+ // Held while it runs, so `wt rm` does not pull the worktree from under its container
290
+ return holding(runsDir(worktree), command.join(' '), async () => {
291
+ const database = testDatabase(join(worktree.dir, run.dir))
292
+ const plan = runPlan(worktree, run, await cachedRunInputs(worktree, run, database.host), database, userInfo(), Boolean(process.stdin.isTTY && process.stdout.isTTY))
240
293
 
241
- await provision(worktree, run, plan, await ensureDatabase(plan, database))
294
+ await provision(worktree, run, plan, await answeringDatabase(plan, database) ?? await ensureDatabase(plan, database))
295
+
296
+ return runInherit(['docker', ...plan.runner(command)])
297
+ })
298
+ }
242
299
 
243
- return runInherit(['docker', ...plan.runner(command)])
300
+ /** The folder each `wt run` of the worktree holds a ticket in while it runs. */
301
+ export function runsDir(worktree: Worktree): string {
302
+ return queueDir(worktree.project.settings, `${worktree.id}.runs`)
244
303
  }
245
304
 
246
305
  // One heavy command at a time across every session on the machine, the rest waiting their turn in arrival order.
247
306
  export async function runHeavy(command: string[]): Promise<number> {
248
- const label = `${command.join(' ')} (in ${process.cwd()})`
307
+ const label = `${command.join(' ')} (in ${currentDir()})`
249
308
 
250
309
  return inLine(queueDir(await wtConfig(), 'heavy'), label, (ahead, running) => console.error(`wt heavy: ${ahead} ahead, running ${running}`), async () => runInherit(command))
251
310
  }
package/src/shell.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { completionScript } from '@kaynooo/cli-kit'
1
2
  import { KnownError } from './errors'
2
3
 
3
4
  // What a child process cannot do for its shell: `wt cd` changes directory, and `wt rm` leaves the folder it just removed for main.
@@ -15,14 +16,40 @@ const FISH = `function wt --description 'git worktrees of a compose project, eac
15
16
  case '*'
16
17
  command wt $argv
17
18
  end
18
- end
19
- command wt --completions fish | source
20
- complete -c wt -n __fish_use_subcommand -a cd -d 'go to a worktree, or main'
21
- complete -c wt -n '__fish_seen_subcommand_from cd' -f -a '(command wt tasks) main'`
19
+ end`
22
20
 
21
+ // The same function in the syntax bash and zsh share.
22
+ const POSIX = `wt() {
23
+ case "$1" in
24
+ cd)
25
+ local dir
26
+ dir=$(command wt path "\${@:2}") || return
27
+ builtin cd "$dir"
28
+ ;;
29
+ rm)
30
+ local main code
31
+ main=$(command wt path 2>/dev/null)
32
+ command wt "$@"
33
+ code=$?
34
+ [ -d "$PWD" ] || builtin cd "$main"
35
+ return $code
36
+ ;;
37
+ *)
38
+ command wt "$@"
39
+ ;;
40
+ esac
41
+ }`
42
+
43
+ const WRAPPERS: Record<string, [wrapper: string, shell: 'fish' | 'bash' | 'zsh']> = { fish: [FISH, 'fish'], bash: [POSIX, 'bash'], zsh: [POSIX, 'zsh'] }
44
+
45
+ const WRAPPED_SHELLS = Object.keys(WRAPPERS)
46
+
47
+ /** The wrapper and its completion in one script, which the shell reads at start without running anything. */
23
48
  export function shellWrapper(shell: string | undefined): string {
24
- if (shell !== 'fish')
25
- throw new KnownError(`no wrapper for ${shell ?? 'that shell'} yet, only fish`)
49
+ const found = shell === undefined ? undefined : WRAPPERS[shell]
50
+
51
+ if (found === undefined)
52
+ throw new KnownError(`no wrapper for ${shell ?? 'that shell'}, only ${WRAPPED_SHELLS.join(', ')}`)
26
53
 
27
- return FISH
54
+ return `${found[0]}\n${completionScript(found[1], ['wt'], `# Completion, as \`wt --completions ${found[1]}\` prints it`)}`
28
55
  }
package/src/stack.ts CHANGED
@@ -4,20 +4,13 @@ import type { Worktree } from './project'
4
4
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
5
5
  import { homedir } from 'node:os'
6
6
  import { dirname } from 'node:path'
7
+ import { warn } from '@kaynooo/cli-kit'
7
8
  import { $ } from 'bun'
8
9
  import { composeEnv } from './compose'
9
10
  import { configPath, fillTemplate } from './config'
10
11
  import { WtError } from './project'
11
12
  import { devproxyUp, hasDevproxy } from './proxy'
12
13
 
13
- const LEADING_ROOT = /^[/~]+/
14
- const UNSAFE_IN_FILE_NAME = /[^\w.-]+/g
15
-
16
- /** The name a stack's job files go by: `booki/planning` gives `booki--planning`, as athome names them. */
17
- export function slugOf(ref: string): string {
18
- return ref.replace(LEADING_ROOT, '').replace(UNSAFE_IN_FILE_NAME, '--')
19
- }
20
-
21
14
  // The env is always passed: a spawn given none gets the env the process started with, missing the WT_JOBS_HELD a job sets since.
22
15
  async function spawnInherit(argv: string[], cwd: string, env: Record<string, string | undefined> = process.env): Promise<number> {
23
16
  return Bun.spawn(argv, { cwd, env, stdio: ['inherit', 'inherit', 'inherit'] }).exited
@@ -32,7 +25,7 @@ async function spawnRunner(role: Role, argv: string[], cwd: string): Promise<num
32
25
  }
33
26
  catch (error) {
34
27
  if ((error as NodeJS.ErrnoException).code === 'ENOENT')
35
- throw new WtError(`\`${argv[0]}\` is not on PATH: fix runner.${role} in ${configPath()}`)
28
+ throw new WtError(`\`${argv[0]}\` is not on PATH`, `fix runner.${role} in ${configPath()}`)
36
29
 
37
30
  throw error
38
31
  }
@@ -72,7 +65,7 @@ export async function stackUp(worktree: Worktree): Promise<void> {
72
65
  return runTemplate('up', up, worktree)
73
66
 
74
67
  // The override puts routed services on the proxy's network, which must exist before compose starts them
75
- if (await hasDevproxy())
68
+ if (hasDevproxy())
76
69
  await devproxyUp()
77
70
 
78
71
  const network = worktree.project.settings.proxyNetwork
@@ -101,6 +94,11 @@ export async function stackDown(worktree: Worktree): Promise<void> {
101
94
  throw new WtError(`docker compose down failed for ${worktree.id}`)
102
95
  }
103
96
 
97
+ /** Follows the stack's compose logs from their last 100 lines until interrupted, returning compose's exit code. */
98
+ export async function followLogs(worktree: Worktree): Promise<number> {
99
+ return spawnInherit(['docker', 'compose', 'logs', '--follow', '--tail', '100'], worktree.dir, composeEnv())
100
+ }
101
+
104
102
  /** Runs the config's `removed` command once a worktree is gone, from the project's root. */
105
103
  export async function afterRemove(worktree: Worktree): Promise<void> {
106
104
  const { removed } = worktree.project.settings.runner
@@ -112,14 +110,14 @@ export async function afterRemove(worktree: Worktree): Promise<void> {
112
110
 
113
111
  try {
114
112
  if (await spawnRunner('removed', argv, worktree.project.root) !== 0)
115
- console.warn(`wt: \`${argv.join(' ')}\` failed after removing ${worktree.id}`)
113
+ warn(`\`${argv.join(' ')}\` failed after removing ${worktree.id}`)
116
114
  }
117
115
  catch (error) {
118
116
  // The worktree is gone already: what is left to do is said, not failed on
119
117
  if (!(error instanceof WtError))
120
118
  throw error
121
119
 
122
- console.warn(`wt: ${error.message}, after removing ${worktree.id}`)
120
+ warn(`${error.message}, after removing ${worktree.id}`)
123
121
  }
124
122
  }
125
123
 
package/src/sync.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import type { Worktree } from './project'
2
- import { baseComposeFiles, composeConfig, overrideWarnings, renderOverride } from './compose'
2
+ import { warn } from '@kaynooo/cli-kit'
3
+ import { baseComposeFiles, composeConfig, overrideWarnings, renderOverride, unknownServices } from './compose'
3
4
  import { cloneData, copyFromMain, linkFromMain, writeEnvFiles, writeIfChanged } from './files'
4
- import { assertWorktreeExists } from './project'
5
+ import { stringToPort } from './port'
6
+ import { assertWorktreeExists, listTasks, loadProjects, worktreeOf } from './project'
5
7
  import { writeStackCerts } from './routes'
6
8
 
7
9
  // Everything a worktree needs besides its git checkouts. Safe to run again: copies and clones never overwrite, generated files are rewritten.
@@ -10,6 +12,7 @@ export async function syncWorktree(worktree: Worktree): Promise<void> {
10
12
 
11
13
  const [warnings, main] = await Promise.all([copyFromMain(worktree), composeConfig(worktree.project.root)])
12
14
 
15
+ warnings.push(...await unknownServices(worktree.project, main))
13
16
  linkFromMain(worktree)
14
17
  writeEnvFiles(worktree)
15
18
  warnings.push(...await cloneData(worktree, main))
@@ -23,6 +26,28 @@ export async function syncWorktree(worktree: Worktree): Promise<void> {
23
26
  await composeConfig(worktree.dir)
24
27
  await writeStackCerts(worktree)
25
28
 
29
+ warnings.push(...await portClashes(worktree))
30
+
26
31
  for (const warning of warnings)
27
- console.warn(`wt: ${warning}`)
32
+ warn(warning)
33
+ }
34
+
35
+ // Ports are hashed from names, so two may land on one; main's is hashed from its project's name. Whether the port is in use is asked on add only, as the worktree's own dev server holds it once running.
36
+ async function portClashes(worktree: Worktree): Promise<string[]> {
37
+ const port = worktree.clientPort
38
+ const sharing: string[] = []
39
+
40
+ for (const project of await loadProjects(() => undefined)) {
41
+ if (stringToPort(project.name) === port)
42
+ sharing.push(`${project.name}'s main`)
43
+
44
+ for (const task of listTasks(project)) {
45
+ const other = worktreeOf(project, task)
46
+
47
+ if (other.id !== worktree.id && other.clientPort === port)
48
+ sharing.push(`${project.name}/${task}`)
49
+ }
50
+ }
51
+
52
+ return sharing.length ? [`dev server port ${port} of ${worktree.task} is also the one of ${sharing.join(', ')}: give one of them its own in the manifest's ports`] : []
28
53
  }
package/src/tools.ts ADDED
@@ -0,0 +1,91 @@
1
+ /** The programs wt runs, found on PATH: `wt add` checks the ones it will need before changing anything, `wt doctor` lists them all. */
2
+
3
+ import type { Project } from './project'
4
+ import { table } from '@kaynooo/cli-kit'
5
+ import { $ } from 'bun'
6
+ import { WtError } from './project'
7
+ import { devproxyArgv } from './proxy'
8
+
9
+ interface Tool {
10
+ name: string
11
+ /** What wt runs it for. */
12
+ for: string
13
+ /** How to get it. */
14
+ get: string
15
+ /** Whether wt needs it: for every project, for the ones it picks, or never, only for comfort. */
16
+ needs: 'always' | 'optional' | ((project: Project) => boolean)
17
+ /** Where it is, or undefined when it is missing. */
18
+ find?: () => Promise<string | undefined> | string | undefined
19
+ }
20
+
21
+ // devproxy is installed with wt, so only a broken install misses it
22
+ function findDevproxy(): string | undefined {
23
+ return devproxyArgv().at(-1)
24
+ }
25
+
26
+ // docker without its compose plugin cannot run a stack
27
+ async function findCompose(): Promise<string | undefined> {
28
+ const docker = Bun.which('docker')
29
+
30
+ if (docker === null)
31
+ return undefined
32
+
33
+ const version = await $`${docker} compose version --short`.quiet().nothrow()
34
+
35
+ return version.exitCode === 0 ? `${docker} compose ${version.text().trim()}` : undefined
36
+ }
37
+
38
+ const TOOLS: Tool[] = [
39
+ { name: 'git', for: 'checks the worktrees out', get: 'the git package of the system', needs: 'always' },
40
+ { name: 'docker', for: 'reads the compose project, clones its volumes and runs the stacks', get: 'https://docs.docker.com/engine/install/', needs: 'always' },
41
+ { name: 'docker compose', for: 'runs the stacks', get: 'the docker compose plugin, https://docs.docker.com/compose/install/linux/', needs: 'always', find: findCompose },
42
+ { name: 'mkcert', for: 'issues the certificates of a project with `certs`', get: 'https://github.com/FiloSottile/mkcert, then `mkcert -install`', needs: project => project.certs !== undefined },
43
+ { name: 'devproxy', for: 'routes the subdomains', get: 'installed with wt, else `bun add -g @kaynooo/devproxy`', needs: 'optional', find: findDevproxy },
44
+ { name: 'notify-send', for: 'tells a --bg job is over', get: 'the libnotify package of the system', needs: 'optional' },
45
+ ]
46
+
47
+ function neededBy(tool: Tool, project: Project): boolean {
48
+ return typeof tool.needs === 'function' ? tool.needs(project) : tool.needs === 'always'
49
+ }
50
+
51
+ async function locateTool(tool: Tool): Promise<string | undefined> {
52
+ return tool.find ? tool.find() : Bun.which(tool.name) ?? undefined
53
+ }
54
+
55
+ /** Refuses before anything is made when a program the project needs is missing, naming each with how to get it. */
56
+ export async function assertTools(project: Project): Promise<void> {
57
+ const needed = TOOLS.filter(tool => neededBy(tool, project))
58
+ const found = await Promise.all(needed.map(locateTool))
59
+ const missing = needed.filter((_, index) => found[index] === undefined)
60
+
61
+ if (missing.length)
62
+ throw new WtError(`${missing.map(tool => `${tool.name} is not on PATH, ${tool.get}`).join('\n')}\nwt needs it for ${project.name}`, '`wt doctor` lists every program')
63
+ }
64
+
65
+ /** Prints each program wt runs, where it is or how to get it; 1 when one the projects need is missing. */
66
+ export async function doctor(projects: Project[]): Promise<number> {
67
+ const found = await Promise.all(TOOLS.map(locateTool))
68
+ let code = 0
69
+
70
+ const rows = TOOLS.map((tool, index) => {
71
+ const at = found[index]
72
+ const by = projects.filter(project => neededBy(tool, project)).map(project => project.name)
73
+ const required = tool.needs === 'always' || by.length > 0
74
+ let use = tool.for
75
+
76
+ if (typeof tool.needs === 'function')
77
+ use += by.length ? ` (${by.join(', ')})` : ', no project has them'
78
+
79
+ if (at !== undefined)
80
+ return ['ok', tool.name, at, use]
81
+
82
+ if (required)
83
+ code = 1
84
+
85
+ return [required ? 'missing' : 'absent', tool.name, tool.get, use]
86
+ })
87
+
88
+ console.log(table([['', 'program', 'where', 'for'], ...rows], { header: true }))
89
+
90
+ return code
91
+ }