@kaynooo/cli-wt 0.1.6 → 0.1.8

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-02xxc9xk.js +67 -0
  3. package/dist/cli-5khwxy5g.js +36 -0
  4. package/dist/cli-6k7xzgw2.js +519 -0
  5. package/dist/cli-96wy1q8e.js +97 -0
  6. package/dist/cli-9m1jyyrf.js +69 -0
  7. package/dist/cli-fa4fh6ex.js +37 -0
  8. package/dist/cli-fdwwsds1.js +153 -0
  9. package/dist/cli-jb9a8d46.js +674 -0
  10. package/dist/cli-k4471y24.js +779 -0
  11. package/dist/cli-kt6d30zz.js +106 -0
  12. package/dist/cli-q7e6gegw.js +105 -0
  13. package/dist/cli-qwe5ykfs.js +313 -0
  14. package/dist/cli-tp4q5w5x.js +251 -0
  15. package/dist/cli.js +228 -2809
  16. package/dist/commands-jqr92tk6.js +222 -0
  17. package/dist/init-0ws4c883.js +166 -0
  18. package/dist/list-83vq4jng.js +88 -0
  19. package/dist/print-d4aq2eqw.js +77 -0
  20. package/dist/prompt-y71tp3f5.js +436 -0
  21. package/dist/prune-7ex1qyd3.js +17 -0
  22. package/dist/run-jrmm9gg8.js +18 -0
  23. package/dist/shell-1smv2vf9.js +55 -0
  24. package/dist/stack-2zj6r6py.js +20 -0
  25. package/dist/tools-c4m5037s.js +13 -0
  26. package/package.json +4 -4
  27. package/src/cli.ts +250 -69
  28. package/src/commands.ts +51 -38
  29. package/src/compose.ts +37 -14
  30. package/src/config.ts +8 -1
  31. package/src/errors.ts +16 -6
  32. package/src/files.ts +14 -15
  33. package/src/git.ts +53 -7
  34. package/src/index.ts +2 -1
  35. package/src/init.ts +56 -10
  36. package/src/jobs.ts +54 -15
  37. package/src/list.ts +26 -13
  38. package/src/print.ts +76 -0
  39. package/src/project.ts +129 -28
  40. package/src/proxy.ts +5 -5
  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/commands.ts CHANGED
@@ -1,13 +1,18 @@
1
1
  import type { Worktree } from './project'
2
2
  import { existsSync, rmSync } from 'node:fs'
3
+ import { isListening, warn } from '@kaynooo/cli-kit'
3
4
  import { $ } from 'bun'
5
+ import { runningProjects } from './compose'
4
6
  import { knownMessage } from './errors'
5
7
  import { addWorktrees, dirtyRepos, isRegistered, removeWorktrees, unreachableCommits } from './git'
6
- import { assertWorktreeExists, listTasks, locate, locateWorktree, worktreeOf, WtError } from './project'
8
+ import { assertWorktreeExists, currentDir, locate, locateWorktree, worktreeOf, WtError } from './project'
9
+ import { removeQueues } from './prune'
10
+ import { holders } from './queue'
7
11
  import { urlsOf } from './routes'
8
- import { forgetTestDatabases } from './run'
12
+ import { forgetTestDatabases, runsDir } from './run'
9
13
  import { afterRemove, hasContainers, stackDown, stackUp } from './stack'
10
14
  import { syncWorktree } from './sync'
15
+ import { assertTools } from './tools'
11
16
 
12
17
  export interface GlobalOptions {
13
18
  project?: string
@@ -42,12 +47,19 @@ async function removeVolumes(worktree: Worktree, anonymous: string[]): Promise<v
42
47
  throw new WtError(`could not remove the volumes of ${worktree.id}:\n${removed.stderr.toString().trim()}`)
43
48
  }
44
49
 
45
- export async function addTask(task: string, branch: string | undefined, options: GlobalOptions): Promise<void> {
46
- const { project } = await locate(process.cwd(), options.project)
50
+ /** Creates the worktree, then starts its stack with `up`, else names the command that would. */
51
+ export async function addTask(task: string, branch: string | undefined, options: GlobalOptions & { up?: boolean, from?: string }): Promise<void> {
52
+ const { project } = await locate(currentDir(), options.project)
47
53
  const worktree = worktreeOf(project, task)
48
54
  const checkout = branch ?? `wt/${task}`
49
55
 
50
- await addWorktrees(worktree, checkout)
56
+ await assertTools(project)
57
+
58
+ // Its own dev server is not up yet, so whatever holds the port would take its requests
59
+ if (isListening(worktree.clientPort))
60
+ warn(`dev server port ${worktree.clientPort} of ${task} is in use already: give it its own in the manifest's ports`)
61
+
62
+ const starts = await addWorktrees(worktree, checkout, options.from)
51
63
 
52
64
  try {
53
65
  await syncWorktree(worktree)
@@ -58,29 +70,45 @@ export async function addTask(task: string, branch: string | undefined, options:
58
70
  const message = knownMessage(error)
59
71
 
60
72
  if (message !== undefined)
61
- throw new WtError(`${message}\n${way}`)
73
+ throw new WtError(message, way)
62
74
 
63
75
  // A bug keeps its stack trace
64
- console.error(`wt: ${way}`)
76
+ warn(way)
65
77
 
66
78
  throw error
67
79
  }
68
80
 
69
- console.log(`wt: created ${worktree.dir} on ${checkout}`)
81
+ console.log(`wt: created ${worktree.dir}${project.repos.length ? '' : ` ${starts[0]!}`}`)
82
+
83
+ if (project.repos.length) {
84
+ for (const start of starts)
85
+ console.log(` ${start}`)
86
+ }
70
87
 
71
88
  for (const url of urlsOf(worktree))
72
89
  console.log(` ${url}`)
73
90
 
74
- console.log(` wt up ${task}`)
91
+ if (options.up)
92
+ await stackUp(worktree)
93
+ else
94
+ console.log(` wt up ${task}`)
75
95
  }
76
96
 
77
97
  export async function syncTask(task: string | undefined, options: GlobalOptions): Promise<void> {
78
- const worktree = await locateWorktree(process.cwd(), task, options.project)
98
+ const worktree = await locateWorktree(currentDir(), task, options.project)
79
99
 
80
100
  await syncWorktree(worktree)
81
101
  console.log(`wt: synced ${worktree.id}`)
82
102
  }
83
103
 
104
+ /** Refuses a removal while a `wt run` uses the worktree, forced or not: its container has the worktree mounted. */
105
+ function refuseWhileRun(worktree: Worktree): void {
106
+ const runs = holders(runsDir(worktree))
107
+
108
+ if (runs.length)
109
+ throw new WtError(`${worktree.task} is in use by wt run (${runs.map(command => `\`${command}\``).join(', ')})`, 'remove it once that ends')
110
+ }
111
+
84
112
  /** Refuses a removal that would lose uncommitted changes or commits on no branch, unless forced. */
85
113
  async function refuseLosingWork(worktree: Worktree, force: boolean): Promise<void> {
86
114
  if (force || !existsSync(worktree.dir))
@@ -89,7 +117,7 @@ async function refuseLosingWork(worktree: Worktree, force: boolean): Promise<voi
89
117
  const dirty = await dirtyRepos(worktree)
90
118
 
91
119
  if (dirty.length)
92
- throw new WtError(`uncommitted changes in ${dirty.join(', ')}, commit them or pass --force`)
120
+ throw new WtError(`uncommitted changes in ${dirty.join(', ')}`, 'commit them, or pass --force to drop them')
93
121
 
94
122
  const unreachable = await unreachableCommits(worktree)
95
123
 
@@ -99,18 +127,19 @@ async function refuseLosingWork(worktree: Worktree, force: boolean): Promise<voi
99
127
 
100
128
  /** Refuses a removal with nothing to remove, or work it would lose, before it claims a job: a job left recording a worktree never there, or a `--bg` one failing out of sight. */
101
129
  export async function assertRemovable(task: string, options: GlobalOptions & { force?: boolean }): Promise<Worktree> {
102
- const worktree = await locateWorktree(process.cwd(), task, options.project)
130
+ const worktree = await locateWorktree(currentDir(), task, options.project)
103
131
 
104
132
  if (!existsSync(worktree.dir) && !Object.values(worktree.files).some(file => existsSync(file)) && !await isRegistered(worktree))
105
133
  throw new WtError(`no worktree ${worktree.task} of ${worktree.project.name}, nothing removed`)
106
134
 
135
+ refuseWhileRun(worktree)
107
136
  await refuseLosingWork(worktree, options.force === true)
108
137
 
109
138
  return worktree
110
139
  }
111
140
 
112
141
  export async function removeTask(task: string, options: GlobalOptions & { force?: boolean }): Promise<void> {
113
- const worktree = await locateWorktree(process.cwd(), task, options.project)
142
+ const worktree = await locateWorktree(currentDir(), task, options.project)
114
143
 
115
144
  // Every command after this one spawns from the cwd, which may be the directory about to go.
116
145
  process.chdir(worktree.project.root)
@@ -118,6 +147,7 @@ export async function removeTask(task: string, options: GlobalOptions & { force?
118
147
  const anonymous = await anonymousVolumes(worktree)
119
148
 
120
149
  // Again inside the job: the tree may have changed since the check before it
150
+ refuseWhileRun(worktree)
121
151
  await refuseLosingWork(worktree, options.force === true)
122
152
 
123
153
  // With the folder gone, its containers may still hold its volumes
@@ -130,6 +160,7 @@ export async function removeTask(task: string, options: GlobalOptions & { force?
130
160
  rmSync(file, { force: true })
131
161
 
132
162
  await forgetTestDatabases(worktree)
163
+ removeQueues(worktree)
133
164
 
134
165
  await removeWorktrees(worktree)
135
166
  await afterRemove(worktree)
@@ -137,36 +168,18 @@ export async function removeTask(task: string, options: GlobalOptions & { force?
137
168
  console.log(`wt: removed ${worktree.id}, its branches are kept`)
138
169
  }
139
170
 
140
- export async function printUrls(task: string | undefined, options: GlobalOptions): Promise<void> {
141
- for (const url of urlsOf(await locateWorktree(process.cwd(), task, options.project)))
142
- console.log(url)
143
- }
144
-
145
171
  export async function upTask(worktree: Worktree): Promise<void> {
146
172
  assertWorktreeExists(worktree)
147
173
  await stackUp(worktree)
148
174
  }
149
175
 
150
- export async function downTask(worktree: Worktree): Promise<void> {
151
- assertWorktreeExists(worktree)
152
- await stackDown(worktree)
176
+ /** A worktree whose folder went while its stack stayed can still be stopped, by its compose project name. */
177
+ export async function assertStoppable(worktree: Worktree): Promise<void> {
178
+ if (!existsSync(worktree.dir) && !(await runningProjects(true)).has(worktree.id))
179
+ assertWorktreeExists(worktree)
153
180
  }
154
181
 
155
- export async function printPath(task: string | undefined, options: GlobalOptions): Promise<void> {
156
- const { project } = await locate(process.cwd(), options.project)
157
-
158
- if (task === undefined || task === 'main')
159
- return console.log(project.root)
160
-
161
- const worktree = worktreeOf(project, task)
162
-
163
- assertWorktreeExists(worktree)
164
- console.log(worktree.dir)
165
- }
166
-
167
- export async function printTasks(options: GlobalOptions): Promise<void> {
168
- try {
169
- console.log(listTasks((await locate(process.cwd(), options.project)).project).join('\n'))
170
- }
171
- catch {}
182
+ export async function downTask(worktree: Worktree): Promise<void> {
183
+ await assertStoppable(worktree)
184
+ await stackDown(worktree)
172
185
  }
package/src/compose.ts CHANGED
@@ -1,7 +1,7 @@
1
- import type { Worktree } from './project'
1
+ import type { Project, Worktree } from './project'
2
2
  import { existsSync, readFileSync } from 'node:fs'
3
3
  import { join } from 'node:path'
4
- import { $ } from 'bun'
4
+ import { compose } from '@kaynooo/cli-kit'
5
5
  import { worktreeHost, WtError } from './project'
6
6
 
7
7
  interface ServiceNetwork {
@@ -35,20 +35,18 @@ export interface ComposeConfig {
35
35
  export const COMPOSE_FILES = ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml']
36
36
  const SKIP_PROFILE = 'wt-skip'
37
37
 
38
- // Compose settings wt decides on, so a COMPOSE_FILE exported in the calling shell cannot leak in.
38
+ // Compose settings wt decides on, so a COMPOSE_FILE exported in the calling shell cannot leak in: set to undefined, a spawn leaves them out.
39
39
  export function composeEnv(overrides: Record<string, string> = {}): Record<string, string | undefined> {
40
- const env = Object.entries(process.env).filter(([key]) => key !== 'COMPOSE_FILE' && key !== 'COMPOSE_PROJECT_NAME')
41
-
42
- return { ...Object.fromEntries(env), ...overrides }
40
+ return { ...process.env, COMPOSE_FILE: undefined, COMPOSE_PROJECT_NAME: undefined, ...overrides }
43
41
  }
44
42
 
45
43
  export async function composeConfig(dir: string, env: Record<string, string> = {}): Promise<ComposeConfig> {
46
- const result = await $`docker compose config --format json`.cwd(dir).env(composeEnv(env)).quiet().nothrow()
44
+ const result = await compose(['config', '--format', 'json'], { cwd: dir, env: composeEnv(env) })
47
45
 
48
- if (result.exitCode !== 0)
49
- throw new WtError(`docker compose config failed in ${dir}:\n${result.stderr.toString()}`)
46
+ if (result.code !== 0)
47
+ throw new WtError(`docker compose config failed in ${dir}:\n${result.stderr}`)
50
48
 
51
- return JSON.parse(result.stdout.toString()) as ComposeConfig
49
+ return JSON.parse(result.stdout) as ComposeConfig
52
50
  }
53
51
 
54
52
  const COMPOSE_FILE_LINE = /^COMPOSE_FILE=(.*)$/m
@@ -202,11 +200,36 @@ export function overrideWarnings(worktree: Worktree, config: ComposeConfig): str
202
200
  return warnings
203
201
  }
204
202
 
205
- export async function runningProjects(): Promise<Set<string>> {
206
- const result = await $`docker compose ls --format json`.quiet().nothrow()
203
+ /** The manifest's service names compose does not know, each a setting that would quietly do nothing (or fail `wt run`), `config` being main's. */
204
+ export async function unknownServices(project: Project, config: ComposeConfig): Promise<string[]> {
205
+ const named: [setting: string, names: string[]][] = [
206
+ ['skip', project.skip ?? []],
207
+ ['routeHosts', project.routeHosts ?? []],
208
+ ['routes', project.routes.filter(route => route.to !== 'client').map(route => SERVICE.exec(route.to)![0])],
209
+ ['run.service', project.run ? [project.run.service] : []],
210
+ ]
211
+ const missing = named.flatMap(([setting, names]) => [...new Set(names)].filter(name => config.services[name] === undefined).map(name => [setting, name] as const))
212
+
213
+ if (!missing.length)
214
+ return []
215
+
216
+ // The config leaves out the services of a profile not enabled, so a name is only unknown once every profile is
217
+ const profiled = await compose(['--profile', '*', 'config', '--services'], { cwd: project.root, env: composeEnv() })
218
+ const every = new Set(profiled.code === 0 ? profiled.stdout.split('\n').filter(Boolean) : [])
219
+
220
+ return missing.filter(([, name]) => !every.has(name)).map(([setting, name]) => `${project.name}: ${setting} names ${name}, which is not a service of ${config.name}`)
221
+ }
222
+
223
+ /** The compose projects with containers, running ones only unless `all`. */
224
+ export async function runningProjects(all = false): Promise<Set<string>> {
225
+ // Spawning a missing program throws, and without docker no stack runs.
226
+ if (Bun.which('docker') === null)
227
+ return new Set()
228
+
229
+ const result = await compose(['ls', ...all ? ['-a'] : [], '--format', 'json'])
207
230
 
208
- if (result.exitCode !== 0)
231
+ if (result.code !== 0)
209
232
  return new Set()
210
233
 
211
- return new Set((JSON.parse(result.stdout.toString()) as { Name: string }[]).map(stack => stack.Name))
234
+ return new Set((JSON.parse(result.stdout) as { Name: string }[]).map(stack => stack.Name))
212
235
  }
package/src/config.ts CHANGED
@@ -3,7 +3,9 @@
3
3
  import { existsSync } from 'node:fs'
4
4
  import { homedir } from 'node:os'
5
5
  import { join } from 'node:path'
6
+ import { configBase } from '@kaynooo/cli-kit'
6
7
  import { KnownError } from './errors'
8
+ import { Jobs } from './jobs'
7
9
 
8
10
  export interface WtConfig {
9
11
  /** The folder of `<name>.ts` manifests. */
@@ -38,7 +40,7 @@ export function expandHome(path: string): string {
38
40
  return path.replace(LEADING_TILDE, homedir())
39
41
  }
40
42
 
41
- export const configPath = () => process.env.WT_CONFIG ?? join((process.env.XDG_CONFIG_HOME ?? '') || join(homedir(), '.config'), 'wt', 'config.ts')
43
+ export const configPath = () => process.env.WT_CONFIG ?? join(configBase(), 'wt', 'config.ts')
42
44
 
43
45
  export function resolveConfig(config: WtConfig = {}): Resolved {
44
46
  const configDir = join(configPath(), '..')
@@ -81,3 +83,8 @@ export async function wtConfig(): Promise<Resolved> {
81
83
  export function fillTemplate(argv: string[], values: Record<string, string>): string[] {
82
84
  return argv.map(arg => arg.replaceAll(/\{(\w+)\}/g, (match, key: string) => values[key] ?? match))
83
85
  }
86
+
87
+ /** The job records of wt's stacks, in the config's jobs folder. */
88
+ export async function wtJobs(): Promise<Jobs> {
89
+ return new Jobs({ dir: (await wtConfig()).jobs, app: 'wt' })
90
+ }
package/src/errors.ts CHANGED
@@ -2,8 +2,12 @@ import { readFileSync } from 'node:fs'
2
2
  import { fail } from '@kaynooo/cli-kit'
3
3
  import { $ } from 'bun'
4
4
 
5
- /** A failure the user is to fix (a manifest, a ref, an action refused): its message alone ends the command, where anything else shows its stack trace. */
6
- export class KnownError extends Error {}
5
+ /** A failure the user is to fix (a manifest, a ref, an action refused): its message alone ends the command, where anything else shows its stack trace; `hint` says how to go on, under it. */
6
+ export class KnownError extends Error {
7
+ constructor(message: string, readonly hint?: string) {
8
+ super(message)
9
+ }
10
+ }
7
11
 
8
12
  const BOOT_TIME_LINE = /^btime (\d+)$/m
9
13
 
@@ -36,17 +40,23 @@ export function knownMessage(error: unknown): string | undefined {
36
40
  return error instanceof $.ShellError ? error.stderr.toString().trim() || error.message : undefined
37
41
  }
38
42
 
39
- /** What a failed command said, else the error's message. */
43
+ export function knownHint(error: unknown): string | undefined {
44
+ return error instanceof KnownError ? error.hint : undefined
45
+ }
46
+
47
+ /** What a failed command said, else the error's message, its hint after it. */
40
48
  export function failureText(error: unknown): string {
41
- return knownMessage(error) ?? (error instanceof Error ? error.message : String(error))
49
+ const hint = knownHint(error)
50
+
51
+ return `${knownMessage(error) ?? (error instanceof Error ? error.message : String(error))}${hint === undefined ? '' : `\n${hint}`}`
42
52
  }
43
53
 
44
- /** Ends the command on a known failure with its message and exit code 1; anything else is thrown on. */
54
+ /** Ends the command on a known failure with its message, its hint and exit code 1; anything else is thrown on. */
45
55
  export function failKnown(error: unknown): never {
46
56
  const message = knownMessage(error)
47
57
 
48
58
  if (message !== undefined)
49
- fail(message, 1)
59
+ fail(message, 1, knownHint(error))
50
60
 
51
61
  throw error
52
62
  }
package/src/files.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import type { ComposeConfig } from './compose'
2
2
  import type { Route, Worktree } from './project'
3
3
  import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
4
- import { constants } from 'node:os'
5
4
  import { basename, dirname, join } from 'node:path'
5
+ import { holdSignals } from '@kaynooo/cli-kit'
6
6
  import { escapeRegExp } from '@kaynooo/utils/text'
7
7
  import { $ } from 'bun'
8
8
  import { baseComposeFiles } from './compose'
@@ -12,7 +12,6 @@ import { inLine, queueDir } from './queue'
12
12
 
13
13
  // A copy lands under this suffix and is renamed once whole, so one cut short is never taken for done.
14
14
  const PARTIAL = '.wt-partial'
15
- const PAUSE_SIGNALS: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP']
16
15
 
17
16
  export function writeIfChanged(path: string, content: string): boolean {
18
17
  if (existsSync(path) && readFileSync(path, 'utf8') === content)
@@ -73,6 +72,11 @@ const WILDCARD_LABEL = /^\*\./
73
72
  // Main hosts become the worktree's; the lookbehind keeps api.booki.localhost whole and makes a second pass a no-op.
74
73
  export function rewriteHosts(text: string, routes: Route[], task: string): string {
75
74
  const hosts = [...new Set(routes.map(route => route.host.replace(WILDCARD_LABEL, '')))].sort((a, b) => b.length - a.length)
75
+
76
+ // An empty alternation would match the empty string between any two characters.
77
+ if (hosts.length === 0)
78
+ return text
79
+
76
80
  const pattern = new RegExp(`(?<![\\w.-])(\\.?)(${hosts.map(escapeRegExp).join('|')})(?![\\w.-])`, 'g')
77
81
 
78
82
  return text.replace(pattern, (_, dot: string, host: string) => `${dot}${worktreeHost(host, task)}`)
@@ -83,7 +87,7 @@ export function setEnvValue(text: string, key: string, value: string): string {
83
87
  const pattern = new RegExp(`^${escapeRegExp(key)}=.*$`, 'm')
84
88
 
85
89
  if (pattern.test(text))
86
- return text.replace(pattern, line)
90
+ return text.replace(pattern, () => line)
87
91
 
88
92
  return `${text}${text === '' || text.endsWith('\n') ? '' : '\n'}${line}\n`
89
93
  }
@@ -150,14 +154,11 @@ export async function whilePaused<T>(ids: string[], work: () => Promise<T>, abor
150
154
  if (record !== undefined)
151
155
  rmSync(record, { force: true })
152
156
  }
153
- const onSignal = (signal: NodeJS.Signals) => {
157
+ // A signal aborts the copies and unpauses main, then ends the process as it would have
158
+ const held = holdSignals(() => {
154
159
  abort?.()
155
160
  release()
156
- process.exit(128 + constants.signals[signal])
157
- }
158
-
159
- for (const signal of PAUSE_SIGNALS)
160
- process.once(signal, onSignal)
161
+ })
161
162
 
162
163
  try {
163
164
  if (ids.length) {
@@ -172,9 +173,7 @@ export async function whilePaused<T>(ids: string[], work: () => Promise<T>, abor
172
173
  return await work()
173
174
  }
174
175
  finally {
175
- for (const signal of PAUSE_SIGNALS)
176
- process.off(signal, onSignal)
177
-
176
+ held.release()
178
177
  release()
179
178
  }
180
179
  }
@@ -271,7 +270,7 @@ async function cloneInLine(worktree: Worktree, main: ComposeConfig): Promise<str
271
270
  }
272
271
 
273
272
  if (volume.driver_opts?.device !== undefined && volume.driver_opts.device !== '')
274
- throw new WtError(`clone: volume ${entry} is a bind to ${volume.driver_opts.device}, list that path instead`)
273
+ throw new WtError(`clone: volume ${entry} is a bind to ${volume.driver_opts.device}`, 'list that path in clone instead')
275
274
 
276
275
  const sourceVolume = volume.name ?? `${main.name}_${entry}`
277
276
  const targetVolume = `${worktree.id}_${entry}`
@@ -283,7 +282,7 @@ async function cloneInLine(worktree: Worktree, main: ComposeConfig): Promise<str
283
282
  const removed = await $`docker volume rm ${targetVolume}`.quiet().nothrow()
284
283
 
285
284
  if (removed.exitCode !== 0)
286
- throw new WtError(`clone: volume ${targetVolume} was cut short mid-copy and cannot be emptied (${removed.stderr.toString().trim()}), \`wt down ${worktree.task}\` then \`wt sync ${worktree.task}\``)
285
+ throw new WtError(`clone: volume ${targetVolume} was cut short mid-copy and cannot be emptied (${removed.stderr.toString().trim()})`, `\`wt down ${worktree.task}\` then \`wt sync ${worktree.task}\``)
287
286
  }
288
287
 
289
288
  if (!await volumeExists(sourceVolume)) {
@@ -320,7 +319,7 @@ async function cloneInLine(worktree: Worktree, main: ComposeConfig): Promise<str
320
319
  writePending(worktree.files.clonesPending, unfinished)
321
320
 
322
321
  if (failures.length)
323
- throw new WtError(`clone failed, \`wt sync ${worktree.task}\` starts it again:\n${failures.map(failureText).join('\n')}`)
322
+ throw new WtError(`clone failed:\n${failures.map(failureText).join('\n')}`, `\`wt sync ${worktree.task}\` starts it again`)
324
323
 
325
324
  return warnings
326
325
  }
package/src/git.ts CHANGED
@@ -17,34 +17,80 @@ async function branchExists(repo: string, branch: string): Promise<boolean> {
17
17
  return (await git(repo, 'for-each-ref', '--format=%(refname)', `refs/remotes/*/${branch}`)).out !== ''
18
18
  }
19
19
 
20
- // A branch neither local nor remote is created from the repo's current HEAD; a remote one is checked out tracking it.
21
- async function onBranch(repo: string, dir: string, branch: string): Promise<{ ok: boolean, out: string }> {
22
- return git(repo, 'worktree', 'add', ...await branchExists(repo, branch) ? [dir, branch] : ['-b', branch, dir])
20
+ // What a new branch forks from, named as the user knows it: `main (1a2b3c4)`, the ref given, or `a detached HEAD (1a2b3c4)`.
21
+ async function forkPoint(repo: string, from: string | undefined): Promise<string | undefined> {
22
+ const sha = await git(repo, 'rev-parse', '--short', `${from ?? 'HEAD'}^{commit}`)
23
+
24
+ if (!sha.ok)
25
+ return undefined
26
+
27
+ if (from !== undefined)
28
+ return `${from} (${sha.out})`
29
+
30
+ const name = (await git(repo, 'rev-parse', '--abbrev-ref', 'HEAD')).out
31
+
32
+ return name === 'HEAD' ? `a detached HEAD (${sha.out})` : `${name} (${sha.out})`
33
+ }
34
+
35
+ // A branch neither local nor remote is created from `from`, the repo's current HEAD by default; one that exists, a remote one tracked, is checked out as it is. Says which, for the user to see where the work starts.
36
+ async function onBranch(repo: string, dir: string, branch: string, from: string | undefined): Promise<{ ok: boolean, out: string, start: string }> {
37
+ if (await branchExists(repo, branch))
38
+ return { ...await git(repo, 'worktree', 'add', dir, branch), start: `on ${branch} as it is` }
39
+
40
+ const point = await forkPoint(repo, from)
41
+
42
+ if (point === undefined)
43
+ return { ok: false, out: `no commit ${from ?? 'HEAD'} in ${repo}`, start: '' }
44
+
45
+ return { ...await git(repo, 'worktree', 'add', '-b', branch, dir, ...from === undefined ? [] : [from]), start: `on ${branch}, forked from ${point}` }
23
46
  }
24
47
 
25
48
  // Every repo inside the root checks out the branch; the root does too when it is the only repo, and is detached otherwise, its nested repos holding the work.
26
- export async function addWorktrees(worktree: Worktree, branch: string): Promise<void> {
49
+ /** Checks the worktree out, `from` the ref a new branch forks from; says where each repo starts, the root first. */
50
+ export async function addWorktrees(worktree: Worktree, branch: string, from?: string): Promise<string[]> {
27
51
  const { project, dir } = worktree
28
52
 
29
53
  if (existsSync(dir))
30
- throw new WtError(`${dir} already exists: \`wt sync ${worktree.task} -p ${project.name}\` finishes it, \`wt rm ${worktree.task} -p ${project.name}\` removes it`)
54
+ throw new WtError(`${dir} already exists`, `\`wt sync ${worktree.task} -p ${project.name}\` finishes it, \`wt rm ${worktree.task} -p ${project.name}\` removes it`)
55
+
56
+ if (from !== undefined) {
57
+ for (const repo of project.repos.length ? project.repos : ['.']) {
58
+ if (await branchExists(join(project.root, repo), branch))
59
+ throw new WtError(`${branch} already exists${repo === '.' ? '' : ` in ${repo}`}, so it is checked out as it is`, 'drop --from, or name a new branch')
60
+ }
61
+ }
31
62
 
32
63
  mkdirSync(dirname(dir), { recursive: true })
33
64
 
34
- const root = project.repos.length ? await git(project.root, 'worktree', 'add', '--detach', dir) : await onBranch(project.root, dir, branch)
65
+ if (!project.repos.length) {
66
+ const root = await onBranch(project.root, dir, branch, from)
67
+
68
+ if (!root.ok)
69
+ throw new WtError(`git worktree add failed for the root:\n${root.out}`)
70
+
71
+ return [root.start]
72
+ }
73
+
74
+ const root = await git(project.root, 'worktree', 'add', '--detach', dir)
35
75
 
36
76
  if (!root.ok)
37
77
  throw new WtError(`git worktree add failed for the root:\n${root.out}`)
38
78
 
79
+ const starts: string[] = []
80
+
39
81
  for (const repo of project.repos) {
40
- const added = await onBranch(join(project.root, repo), join(dir, repo), branch)
82
+ const added = await onBranch(join(project.root, repo), join(dir, repo), branch, from)
41
83
 
42
84
  if (!added.ok) {
43
85
  await removeWorktrees(worktree)
44
86
 
45
87
  throw new WtError(`git worktree add failed for ${repo}, rolled back:\n${added.out}`)
46
88
  }
89
+
90
+ starts.push(`${repo} ${added.start}`)
47
91
  }
92
+
93
+ return starts
48
94
  }
49
95
 
50
96
  export async function removeWorktrees(worktree: Worktree): Promise<void> {
package/src/index.ts CHANGED
@@ -7,10 +7,11 @@ export { expandHome, wtConfig } from './config'
7
7
  export { alive, bootTime, failKnown, KnownError } from './errors'
8
8
  export type { Job, JobStack, JobState, JobWords } from './jobs'
9
9
  export { HELD_ENV, Jobs, logTail } from './jobs'
10
+ export { slugOf } from './jobs'
10
11
  export type { Project, ProjectConfig, Route, RunConfig, Worktree } from './project'
11
12
  export { findProject, listTasks, loadProjects, locate, locateWorktree, worktreeHost, worktreeOf, WtError } from './project'
12
13
  export type { ProxyHost } from './proxy'
13
14
  export { devproxyUp, proxyHostList } from './proxy'
14
15
  export { inLine, queueDir } from './queue'
15
16
  export { urlsOf } from './routes'
16
- export { runSetup, slugOf } from './stack'
17
+ export { runSetup } from './stack'