@kaynooo/cli-wt 0.1.1 → 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.
- package/README.md +17 -10
- package/dist/cli-0gbs87r4.js +313 -0
- package/dist/cli-1nyesy1b.js +674 -0
- package/dist/cli-4g5ehhgn.js +251 -0
- package/dist/cli-6ybxw5sc.js +97 -0
- package/dist/cli-dmkfxdbr.js +153 -0
- package/dist/cli-dmzvmpge.js +106 -0
- package/dist/cli-e2h20nyy.js +36 -0
- package/dist/cli-j82fak6j.js +69 -0
- package/dist/cli-k4471y24.js +779 -0
- package/dist/cli-kek450vq.js +519 -0
- package/dist/cli-n5rt07v7.js +105 -0
- package/dist/cli-pkvw2k4x.js +37 -0
- package/dist/cli-w4w36hng.js +67 -0
- package/dist/cli.js +238 -2576
- package/dist/commands-jtnbchtb.js +222 -0
- package/dist/init-4ynjrztr.js +166 -0
- package/dist/list-js6drtvg.js +88 -0
- package/dist/print-q6qaqg22.js +77 -0
- package/dist/prompt-y71tp3f5.js +436 -0
- package/dist/prune-beweag7w.js +17 -0
- package/dist/run-7eayrqwy.js +18 -0
- package/dist/shell-xrgvqrpp.js +55 -0
- package/dist/stack-h3pgyx1e.js +20 -0
- package/dist/tools-4j56r47a.js +13 -0
- package/package.json +6 -6
- package/src/cli.ts +270 -76
- package/src/commands.ts +58 -42
- package/src/compose.ts +37 -14
- package/src/config.ts +8 -1
- package/src/errors.ts +31 -5
- package/src/files.ts +15 -23
- package/src/git.ts +53 -7
- package/src/index.ts +3 -2
- package/src/init.ts +56 -10
- package/src/jobs.ts +60 -19
- package/src/list.ts +26 -13
- package/src/print.ts +76 -0
- package/src/project.ts +134 -23
- package/src/proxy.ts +9 -9
- package/src/prune.ts +149 -0
- package/src/queue.ts +27 -3
- package/src/run.ts +82 -23
- package/src/shell.ts +34 -7
- package/src/stack.ts +41 -17
- package/src/sync.ts +28 -3
- package/src/tools.ts +91 -0
package/src/commands.ts
CHANGED
|
@@ -1,14 +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'
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
5
|
+
import { runningProjects } from './compose'
|
|
6
|
+
import { knownMessage } from './errors'
|
|
6
7
|
import { addWorktrees, dirtyRepos, isRegistered, removeWorktrees, unreachableCommits } from './git'
|
|
7
|
-
import { assertWorktreeExists,
|
|
8
|
+
import { assertWorktreeExists, currentDir, locate, locateWorktree, worktreeOf, WtError } from './project'
|
|
9
|
+
import { removeQueues } from './prune'
|
|
10
|
+
import { holders } from './queue'
|
|
8
11
|
import { urlsOf } from './routes'
|
|
9
|
-
import { forgetTestDatabases } from './run'
|
|
12
|
+
import { forgetTestDatabases, runsDir } from './run'
|
|
10
13
|
import { afterRemove, hasContainers, stackDown, stackUp } from './stack'
|
|
11
14
|
import { syncWorktree } from './sync'
|
|
15
|
+
import { assertTools } from './tools'
|
|
12
16
|
|
|
13
17
|
export interface GlobalOptions {
|
|
14
18
|
project?: string
|
|
@@ -43,12 +47,19 @@ async function removeVolumes(worktree: Worktree, anonymous: string[]): Promise<v
|
|
|
43
47
|
throw new WtError(`could not remove the volumes of ${worktree.id}:\n${removed.stderr.toString().trim()}`)
|
|
44
48
|
}
|
|
45
49
|
|
|
46
|
-
|
|
47
|
-
|
|
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)
|
|
48
53
|
const worktree = worktreeOf(project, task)
|
|
49
54
|
const checkout = branch ?? `wt/${task}`
|
|
50
55
|
|
|
51
|
-
await
|
|
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)
|
|
52
63
|
|
|
53
64
|
try {
|
|
54
65
|
await syncWorktree(worktree)
|
|
@@ -56,30 +67,48 @@ export async function addTask(task: string, branch: string | undefined, options:
|
|
|
56
67
|
catch (error) {
|
|
57
68
|
const way = `the worktree is checked out but not ready: \`wt sync ${task} -p ${project.name}\` resumes it, \`wt rm ${task} -p ${project.name}\` removes it`
|
|
58
69
|
|
|
59
|
-
|
|
60
|
-
|
|
70
|
+
const message = knownMessage(error)
|
|
71
|
+
|
|
72
|
+
if (message !== undefined)
|
|
73
|
+
throw new WtError(message, way)
|
|
61
74
|
|
|
62
75
|
// A bug keeps its stack trace
|
|
63
|
-
|
|
76
|
+
warn(way)
|
|
64
77
|
|
|
65
78
|
throw error
|
|
66
79
|
}
|
|
67
80
|
|
|
68
|
-
console.log(`wt: created ${worktree.dir}
|
|
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
|
+
}
|
|
69
87
|
|
|
70
88
|
for (const url of urlsOf(worktree))
|
|
71
89
|
console.log(` ${url}`)
|
|
72
90
|
|
|
73
|
-
|
|
91
|
+
if (options.up)
|
|
92
|
+
await stackUp(worktree)
|
|
93
|
+
else
|
|
94
|
+
console.log(` wt up ${task}`)
|
|
74
95
|
}
|
|
75
96
|
|
|
76
97
|
export async function syncTask(task: string | undefined, options: GlobalOptions): Promise<void> {
|
|
77
|
-
const worktree = await locateWorktree(
|
|
98
|
+
const worktree = await locateWorktree(currentDir(), task, options.project)
|
|
78
99
|
|
|
79
100
|
await syncWorktree(worktree)
|
|
80
101
|
console.log(`wt: synced ${worktree.id}`)
|
|
81
102
|
}
|
|
82
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
|
+
|
|
83
112
|
/** Refuses a removal that would lose uncommitted changes or commits on no branch, unless forced. */
|
|
84
113
|
async function refuseLosingWork(worktree: Worktree, force: boolean): Promise<void> {
|
|
85
114
|
if (force || !existsSync(worktree.dir))
|
|
@@ -88,7 +117,7 @@ async function refuseLosingWork(worktree: Worktree, force: boolean): Promise<voi
|
|
|
88
117
|
const dirty = await dirtyRepos(worktree)
|
|
89
118
|
|
|
90
119
|
if (dirty.length)
|
|
91
|
-
throw new WtError(`uncommitted changes in ${dirty.join(', ')}
|
|
120
|
+
throw new WtError(`uncommitted changes in ${dirty.join(', ')}`, 'commit them, or pass --force to drop them')
|
|
92
121
|
|
|
93
122
|
const unreachable = await unreachableCommits(worktree)
|
|
94
123
|
|
|
@@ -97,17 +126,20 @@ async function refuseLosingWork(worktree: Worktree, force: boolean): Promise<voi
|
|
|
97
126
|
}
|
|
98
127
|
|
|
99
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. */
|
|
100
|
-
export async function assertRemovable(task: string, options: GlobalOptions & { force?: boolean }): Promise<
|
|
101
|
-
const worktree = await locateWorktree(
|
|
129
|
+
export async function assertRemovable(task: string, options: GlobalOptions & { force?: boolean }): Promise<Worktree> {
|
|
130
|
+
const worktree = await locateWorktree(currentDir(), task, options.project)
|
|
102
131
|
|
|
103
132
|
if (!existsSync(worktree.dir) && !Object.values(worktree.files).some(file => existsSync(file)) && !await isRegistered(worktree))
|
|
104
133
|
throw new WtError(`no worktree ${worktree.task} of ${worktree.project.name}, nothing removed`)
|
|
105
134
|
|
|
135
|
+
refuseWhileRun(worktree)
|
|
106
136
|
await refuseLosingWork(worktree, options.force === true)
|
|
137
|
+
|
|
138
|
+
return worktree
|
|
107
139
|
}
|
|
108
140
|
|
|
109
141
|
export async function removeTask(task: string, options: GlobalOptions & { force?: boolean }): Promise<void> {
|
|
110
|
-
const worktree = await locateWorktree(
|
|
142
|
+
const worktree = await locateWorktree(currentDir(), task, options.project)
|
|
111
143
|
|
|
112
144
|
// Every command after this one spawns from the cwd, which may be the directory about to go.
|
|
113
145
|
process.chdir(worktree.project.root)
|
|
@@ -115,6 +147,7 @@ export async function removeTask(task: string, options: GlobalOptions & { force?
|
|
|
115
147
|
const anonymous = await anonymousVolumes(worktree)
|
|
116
148
|
|
|
117
149
|
// Again inside the job: the tree may have changed since the check before it
|
|
150
|
+
refuseWhileRun(worktree)
|
|
118
151
|
await refuseLosingWork(worktree, options.force === true)
|
|
119
152
|
|
|
120
153
|
// With the folder gone, its containers may still hold its volumes
|
|
@@ -127,6 +160,7 @@ export async function removeTask(task: string, options: GlobalOptions & { force?
|
|
|
127
160
|
rmSync(file, { force: true })
|
|
128
161
|
|
|
129
162
|
await forgetTestDatabases(worktree)
|
|
163
|
+
removeQueues(worktree)
|
|
130
164
|
|
|
131
165
|
await removeWorktrees(worktree)
|
|
132
166
|
await afterRemove(worktree)
|
|
@@ -134,36 +168,18 @@ export async function removeTask(task: string, options: GlobalOptions & { force?
|
|
|
134
168
|
console.log(`wt: removed ${worktree.id}, its branches are kept`)
|
|
135
169
|
}
|
|
136
170
|
|
|
137
|
-
export async function printUrls(task: string | undefined, options: GlobalOptions): Promise<void> {
|
|
138
|
-
for (const url of urlsOf(await locateWorktree(process.cwd(), task, options.project)))
|
|
139
|
-
console.log(url)
|
|
140
|
-
}
|
|
141
|
-
|
|
142
171
|
export async function upTask(worktree: Worktree): Promise<void> {
|
|
143
172
|
assertWorktreeExists(worktree)
|
|
144
173
|
await stackUp(worktree)
|
|
145
174
|
}
|
|
146
175
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
await
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
export async function printPath(task: string | undefined, options: GlobalOptions): Promise<void> {
|
|
153
|
-
const { project } = await locate(process.cwd(), options.project)
|
|
154
|
-
|
|
155
|
-
if (task === undefined || task === 'main')
|
|
156
|
-
return console.log(project.root)
|
|
157
|
-
|
|
158
|
-
const worktree = worktreeOf(project, task)
|
|
159
|
-
|
|
160
|
-
assertWorktreeExists(worktree)
|
|
161
|
-
console.log(worktree.dir)
|
|
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)
|
|
162
180
|
}
|
|
163
181
|
|
|
164
|
-
export async function
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
}
|
|
168
|
-
catch {}
|
|
182
|
+
export async function downTask(worktree: Worktree): Promise<void> {
|
|
183
|
+
await assertStoppable(worktree)
|
|
184
|
+
await stackDown(worktree)
|
|
169
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 {
|
|
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
|
-
|
|
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
|
|
44
|
+
const result = await compose(['config', '--format', 'json'], { cwd: dir, env: composeEnv(env) })
|
|
47
45
|
|
|
48
|
-
if (result.
|
|
49
|
-
throw new WtError(`docker compose config failed in ${dir}:\n${result.stderr
|
|
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
|
|
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
|
-
|
|
206
|
-
|
|
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.
|
|
231
|
+
if (result.code !== 0)
|
|
209
232
|
return new Set()
|
|
210
233
|
|
|
211
|
-
return new Set((JSON.parse(result.stdout
|
|
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((
|
|
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
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs'
|
|
2
2
|
import { fail } from '@kaynooo/cli-kit'
|
|
3
|
+
import { $ } from 'bun'
|
|
3
4
|
|
|
4
|
-
/** 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. */
|
|
5
|
-
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
|
+
}
|
|
6
11
|
|
|
7
12
|
const BOOT_TIME_LINE = /^btime (\d+)$/m
|
|
8
13
|
|
|
@@ -27,10 +32,31 @@ export function alive(pid: number): boolean {
|
|
|
27
32
|
}
|
|
28
33
|
}
|
|
29
34
|
|
|
30
|
-
/**
|
|
31
|
-
export function
|
|
35
|
+
/** The message of a failure the user is to fix, a command that failed included (docker stopped, a pull refused): what it said, not a stack trace; undefined for a bug. */
|
|
36
|
+
export function knownMessage(error: unknown): string | undefined {
|
|
32
37
|
if (error instanceof KnownError)
|
|
33
|
-
|
|
38
|
+
return error.message
|
|
39
|
+
|
|
40
|
+
return error instanceof $.ShellError ? error.stderr.toString().trim() || error.message : undefined
|
|
41
|
+
}
|
|
42
|
+
|
|
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. */
|
|
48
|
+
export function failureText(error: unknown): string {
|
|
49
|
+
const hint = knownHint(error)
|
|
50
|
+
|
|
51
|
+
return `${knownMessage(error) ?? (error instanceof Error ? error.message : String(error))}${hint === undefined ? '' : `\n${hint}`}`
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Ends the command on a known failure with its message, its hint and exit code 1; anything else is thrown on. */
|
|
55
|
+
export function failKnown(error: unknown): never {
|
|
56
|
+
const message = knownMessage(error)
|
|
57
|
+
|
|
58
|
+
if (message !== undefined)
|
|
59
|
+
fail(message, 1, knownHint(error))
|
|
34
60
|
|
|
35
61
|
throw error
|
|
36
62
|
}
|
package/src/files.ts
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
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'
|
|
9
|
+
import { failureText } from './errors'
|
|
9
10
|
import { worktreeHost, WtError } from './project'
|
|
10
11
|
import { inLine, queueDir } from './queue'
|
|
11
12
|
|
|
12
13
|
// A copy lands under this suffix and is renamed once whole, so one cut short is never taken for done.
|
|
13
14
|
const PARTIAL = '.wt-partial'
|
|
14
|
-
const PAUSE_SIGNALS: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP']
|
|
15
15
|
|
|
16
16
|
export function writeIfChanged(path: string, content: string): boolean {
|
|
17
17
|
if (existsSync(path) && readFileSync(path, 'utf8') === content)
|
|
@@ -72,6 +72,11 @@ const WILDCARD_LABEL = /^\*\./
|
|
|
72
72
|
// Main hosts become the worktree's; the lookbehind keeps api.booki.localhost whole and makes a second pass a no-op.
|
|
73
73
|
export function rewriteHosts(text: string, routes: Route[], task: string): string {
|
|
74
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
|
+
|
|
75
80
|
const pattern = new RegExp(`(?<![\\w.-])(\\.?)(${hosts.map(escapeRegExp).join('|')})(?![\\w.-])`, 'g')
|
|
76
81
|
|
|
77
82
|
return text.replace(pattern, (_, dot: string, host: string) => `${dot}${worktreeHost(host, task)}`)
|
|
@@ -82,7 +87,7 @@ export function setEnvValue(text: string, key: string, value: string): string {
|
|
|
82
87
|
const pattern = new RegExp(`^${escapeRegExp(key)}=.*$`, 'm')
|
|
83
88
|
|
|
84
89
|
if (pattern.test(text))
|
|
85
|
-
return text.replace(pattern, line)
|
|
90
|
+
return text.replace(pattern, () => line)
|
|
86
91
|
|
|
87
92
|
return `${text}${text === '' || text.endsWith('\n') ? '' : '\n'}${line}\n`
|
|
88
93
|
}
|
|
@@ -149,14 +154,11 @@ export async function whilePaused<T>(ids: string[], work: () => Promise<T>, abor
|
|
|
149
154
|
if (record !== undefined)
|
|
150
155
|
rmSync(record, { force: true })
|
|
151
156
|
}
|
|
152
|
-
|
|
157
|
+
// A signal aborts the copies and unpauses main, then ends the process as it would have
|
|
158
|
+
const held = holdSignals(() => {
|
|
153
159
|
abort?.()
|
|
154
160
|
release()
|
|
155
|
-
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
for (const signal of PAUSE_SIGNALS)
|
|
159
|
-
process.once(signal, onSignal)
|
|
161
|
+
})
|
|
160
162
|
|
|
161
163
|
try {
|
|
162
164
|
if (ids.length) {
|
|
@@ -171,9 +173,7 @@ export async function whilePaused<T>(ids: string[], work: () => Promise<T>, abor
|
|
|
171
173
|
return await work()
|
|
172
174
|
}
|
|
173
175
|
finally {
|
|
174
|
-
|
|
175
|
-
process.off(signal, onSignal)
|
|
176
|
-
|
|
176
|
+
held.release()
|
|
177
177
|
release()
|
|
178
178
|
}
|
|
179
179
|
}
|
|
@@ -185,14 +185,6 @@ export async function settle(copies: (() => Promise<void>)[]): Promise<unknown[]
|
|
|
185
185
|
return results.flatMap(result => result.status === 'rejected' ? [result.reason as unknown] : [])
|
|
186
186
|
}
|
|
187
187
|
|
|
188
|
-
/** What a failed command said, else the error's message. */
|
|
189
|
-
export function failureText(error: unknown): string {
|
|
190
|
-
if (error instanceof $.ShellError)
|
|
191
|
-
return error.stderr.toString().trim() || error.message
|
|
192
|
-
|
|
193
|
-
return error instanceof Error ? error.message : String(error)
|
|
194
|
-
}
|
|
195
|
-
|
|
196
188
|
// The ids of main's containers a clone of the project paused, one per line, while it copies.
|
|
197
189
|
const pausedRecord = (worktree: Worktree) => queueDir(worktree.project.settings, `${worktree.project.name}.paused`)
|
|
198
190
|
|
|
@@ -278,7 +270,7 @@ async function cloneInLine(worktree: Worktree, main: ComposeConfig): Promise<str
|
|
|
278
270
|
}
|
|
279
271
|
|
|
280
272
|
if (volume.driver_opts?.device !== undefined && volume.driver_opts.device !== '')
|
|
281
|
-
throw new WtError(`clone: volume ${entry} is a bind to ${volume.driver_opts.device}
|
|
273
|
+
throw new WtError(`clone: volume ${entry} is a bind to ${volume.driver_opts.device}`, 'list that path in clone instead')
|
|
282
274
|
|
|
283
275
|
const sourceVolume = volume.name ?? `${main.name}_${entry}`
|
|
284
276
|
const targetVolume = `${worktree.id}_${entry}`
|
|
@@ -290,7 +282,7 @@ async function cloneInLine(worktree: Worktree, main: ComposeConfig): Promise<str
|
|
|
290
282
|
const removed = await $`docker volume rm ${targetVolume}`.quiet().nothrow()
|
|
291
283
|
|
|
292
284
|
if (removed.exitCode !== 0)
|
|
293
|
-
throw new WtError(`clone: volume ${targetVolume} was cut short mid-copy and cannot be emptied (${removed.stderr.toString().trim()})
|
|
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}\``)
|
|
294
286
|
}
|
|
295
287
|
|
|
296
288
|
if (!await volumeExists(sourceVolume)) {
|
|
@@ -327,7 +319,7 @@ async function cloneInLine(worktree: Worktree, main: ComposeConfig): Promise<str
|
|
|
327
319
|
writePending(worktree.files.clonesPending, unfinished)
|
|
328
320
|
|
|
329
321
|
if (failures.length)
|
|
330
|
-
throw new WtError(`clone failed
|
|
322
|
+
throw new WtError(`clone failed:\n${failures.map(failureText).join('\n')}`, `\`wt sync ${worktree.task}\` starts it again`)
|
|
331
323
|
|
|
332
324
|
return warnings
|
|
333
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
|
-
//
|
|
21
|
-
async function
|
|
22
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** What other tools build on wt with:
|
|
1
|
+
/** What other tools build on wt with: a project tool reads the manifests and worktrees, shares the job locks and runs a worktree's setup. */
|
|
2
2
|
|
|
3
3
|
export type { ComposeConfig } from './compose'
|
|
4
4
|
export { COMPOSE_FILES, composeEnv } from './compose'
|
|
@@ -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
|
|
17
|
+
export { runSetup } from './stack'
|