@kaynooo/cli-wt 0.0.0-stage → 0.1.0

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/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-wt",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "type": "module",
4
+ "version": "0.1.0",
5
+ "description": "wt: git worktrees of a compose project, each with its own stack, data and <task>.<host> subdomains beside main.",
6
+ "author": "Kaynooo <contact@kaynooo.fr>",
7
+ "license": "MIT",
8
+ "homepage": "https://git.kaynooo.fr/kaynooo/cli/src/branch/main/packages/wt#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://git.kaynooo.fr/kaynooo/cli.git",
12
+ "directory": "packages/wt"
13
+ },
14
+ "bugs": "https://git.kaynooo.fr/kaynooo/cli/issues",
15
+ "keywords": ["git", "worktree", "docker", "compose", "devproxy", "cli", "bun"],
16
+ "exports": {
17
+ ".": "./src/index.ts"
18
+ },
19
+ "bin": {
20
+ "wt": "./dist/cli.js"
21
+ },
22
+ "files": ["dist", "src"],
23
+ "engines": {
24
+ "bun": ">=1.4.3"
25
+ },
26
+ "publishConfig": {
27
+ "registry": "https://git.kaynooo.fr/api/packages/kaynooo/npm/"
28
+ },
29
+ "scripts": {
30
+ "build": "$npm_execpath build src/cli.ts --target bun --outdir dist",
31
+ "wt": "$npm_execpath src/cli.ts"
32
+ },
33
+ "dependencies": {
34
+ "@kaynooo/cli-env": "0.14.1",
35
+ "@kaynooo/cli-kit": "0.41.0",
36
+ "@kaynooo/devproxy": "0.2.0",
37
+ "@kaynooo/utils": "3.0.0"
38
+ }
39
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,319 @@
1
+ #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
+
3
+ import type { GlobalOptions } from './commands'
4
+ import process from 'node:process'
5
+ import { badUsage, parse, runCli } from '@kaynooo/cli-kit'
6
+ import { addTask, assertRemovable, downTask, printPath, printTasks, printUrls, removeTask, syncTask, upTask } from './commands'
7
+ import { wtConfig } from './config'
8
+ import { failKnown } from './errors'
9
+ import { initProject } from './init'
10
+ import { Jobs } from './jobs'
11
+ import { listWorktrees } from './list'
12
+ import { listTasks, loadProjects, locate, locateWorktree } from './project'
13
+ import { runHeavy, runTask } from './run'
14
+ import { shellWrapper } from './shell'
15
+ import { slugOf } from './stack'
16
+
17
+ async function jobs(): Promise<Jobs> {
18
+ return new Jobs({ dir: (await wtConfig()).jobs, app: 'wt' })
19
+ }
20
+
21
+ // A config that does not load fails like any other known error.
22
+ async function guarded(action: () => Promise<number | void>): Promise<number> {
23
+ try {
24
+ return await (await jobs()).guarded(action)
25
+ }
26
+ catch (error) {
27
+ return failKnown(error)
28
+ }
29
+ }
30
+
31
+ async function projectNames(): Promise<string[]> {
32
+ return (await loadProjects()).map(project => project.name)
33
+ }
34
+
35
+ // The worktrees of the project the current directory belongs to, none outside one.
36
+ async function taskNames(): Promise<string[]> {
37
+ try {
38
+ return listTasks((await locate(process.cwd())).project)
39
+ }
40
+ catch {
41
+ return []
42
+ }
43
+ }
44
+
45
+ const TASK = { '[task]': taskNames, '<task>': taskNames }
46
+
47
+ // Every command that reads a manifest takes it, as the kit has no option before the command name.
48
+ const PROJECT_OPTION = { type: 'string', short: 'p', candidates: projectNames, description: 'manifest to use instead of the one the current directory belongs to' } as const
49
+
50
+ const BG_OPTION = { type: 'boolean', description: 'run it away from any terminal, its output in the worktree\'s job log, a notification saying how it went' } as const
51
+
52
+ // Every action on a worktree holds its stack's lock, so an up cannot race a removal, and --bg detaches it.
53
+ async function asWorktreeJob(verb: 'add' | 'sync' | 'rm' | 'up' | 'down', task: string, options: GlobalOptions & { bg?: boolean }, argv: string[], work: () => Promise<void>): Promise<number> {
54
+ const { project } = await locate(process.cwd(), options.project)
55
+ const ref = `${project.name}/${task}`
56
+ const stack = { ref, slug: slugOf(ref) }
57
+ const queue = await jobs()
58
+
59
+ if (!options.bg) {
60
+ const code = await queue.run(stack, verb, work)
61
+
62
+ // A removed worktree leaves no job history for one made again under its name
63
+ if (verb === 'rm' && code === 0)
64
+ queue.forget(stack)
65
+
66
+ return code
67
+ }
68
+
69
+ try {
70
+ const job = queue.detach(stack, verb, [import.meta.path, ...argv, '-p', project.name])
71
+
72
+ console.log(`wt: ${verb} ${ref} runs out of sight, its output in ${job.log}`)
73
+ }
74
+ catch (error) {
75
+ await queue.notifyRefused(`wt ${verb} ${ref}`, error instanceof Error ? error.message : String(error))
76
+
77
+ throw error
78
+ }
79
+
80
+ return 0
81
+ }
82
+
83
+ const ADD_USAGE = `wt add <task> [branch] [-p <name>] [--bg]
84
+
85
+ Creates a worktree, copies its files and data from main, and routes its subdomains. The task is a lowercase name, also the subdomain label; the branch defaults to wt/<task>.
86
+
87
+ Exits 0 once the worktree is ready, 1 when it cannot be made or provisioned, 2 on a usage error.`
88
+
89
+ const SYNC_USAGE = `wt sync [task] [-p <name>]
90
+
91
+ Provisions a worktree again after a manifest change: missing copies and clones, compose override, certificates and routes. The task defaults to the worktree the current directory is in.
92
+
93
+ Exits 0 once it is provisioned, 1 when a step fails, 2 on a usage error.`
94
+
95
+ const RM_USAGE = `wt rm <task> [-f] [-p <name>] [--bg]
96
+
97
+ Stops a worktree stack and deletes its checkouts, volumes, certificates and routes, keeping its branches.
98
+
99
+ Exits 0 once it is gone, 1 when uncommitted changes or lost commits refuse it (unless --force) or a step fails, 2 on a usage error.`
100
+
101
+ const UP_USAGE = `wt up [task] [-p <name>] [--bg]
102
+
103
+ Starts a worktree stack: \`docker compose up -d --build\` in the worktree then the manifest's setup the first time, or the config's runner.up. The task defaults to the worktree the current directory is in.
104
+
105
+ Exits 0 once the stack is up, 1 when a command fails, 2 on a usage error.`
106
+
107
+ const DOWN_USAGE = `wt down [task] [-p <name>] [--bg]
108
+
109
+ Stops a worktree stack: \`docker compose down\` in the worktree, or the config's runner.down. The task defaults to the worktree the current directory is in.
110
+
111
+ Exits 0 once the stack is down, 1 when a command fails, 2 on a usage error.`
112
+
113
+ const SHELL_USAGE = `wt shell <shell>
114
+
115
+ Prints the shell function that lets \`wt cd\` change directory and \`wt rm\` leave the folder it removes: \`wt shell fish | source\` in config.fish.
116
+
117
+ Exits 0 when it printed the wrapper, 1 for a shell it has none for, 2 on a usage error.`
118
+
119
+ const LS_USAGE = `wt ls [-a] [-p <name>] [--json]
120
+
121
+ Lists main and the worktrees of the current project, or of every project, with their changed files.
122
+
123
+ Exits 0 when it listed them, 1 when a manifest does not load, 2 on a usage error.`
124
+
125
+ const PATH_USAGE = `wt path [task] [-p <name>]
126
+
127
+ Prints the directory of a worktree, or of main when no task is given.
128
+
129
+ Exits 0 when it printed it, 1 when there is no such worktree or project, 2 on a usage error.`
130
+
131
+ const INIT_USAGE = `wt init [dir] [--name <name>] [--print]
132
+
133
+ Drafts a manifest for the project checked out in a directory, the current one by default, into the config's manifests folder.
134
+
135
+ Exits 0 once it is written or printed, 1 when the folder holds no compose project, 2 on a usage error.`
136
+
137
+ const RUN_USAGE = `wt run <task> [-p <name>] -- <command>...
138
+
139
+ Runs a command of a worktree in a throwaway container of its run service, against a test database of its own, provisioned on first use.
140
+
141
+ Exits with the command's code, 1 when the test database cannot be provisioned, 2 on a usage error.`
142
+
143
+ const HEAVY_USAGE = `wt heavy -- <command>...
144
+
145
+ Runs a heavy command (a full suite, e2e) once those queued before it, from any session, are done.
146
+
147
+ Exits with the command's code, 2 on a usage error.`
148
+
149
+ const URL_USAGE = `wt url [task] [-p <name>]
150
+
151
+ Prints the URLs of a worktree.
152
+
153
+ Exits 0 when it printed it, 1 when there is no such worktree or project, 2 on a usage error.`
154
+
155
+ const TASKS_USAGE = `wt tasks [-p <name>]
156
+
157
+ Prints the worktree names of the project, one per line.
158
+
159
+ Exits 0 when it printed them, 1 when there is no such project, 2 on a usage error.`
160
+
161
+ process.exitCode = await runCli({
162
+ name: 'wt',
163
+ about: 'git worktrees of a compose project, each with its own stack, data and <task>.<host> subdomains beside main',
164
+ replaces: 'a second clone, port juggling and a shared database to try a branch',
165
+ examples: [['wt add planning', 'a worktree on wt/planning with its own stack'], ['wt up planning', 'start it'], ['wt rm planning', 'stop and delete it, keeping its branches']],
166
+ commands: {
167
+ add: {
168
+ summary: 'create a worktree, copy its files and data from main, and route its subdomains',
169
+ run: async (args) => {
170
+ const { values, positionals: [task, branch] } = parse(args, ADD_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ['<task>', '[branch]'] })
171
+
172
+ return guarded(async () => asWorktreeJob('add', task, values, ['add', task, ...(branch === undefined ? [] : [branch])], async () => addTask(task, branch, values)))
173
+ },
174
+ },
175
+ sync: {
176
+ summary: 'provision a worktree again after a manifest change',
177
+ run: async (args) => {
178
+ const { values, positionals: [task] } = parse(args, SYNC_USAGE, { project: PROJECT_OPTION }, { positionals: ['[task]'], candidates: TASK })
179
+
180
+ return guarded(async () => {
181
+ const { task: name } = await locateWorktree(process.cwd(), task, values.project)
182
+
183
+ return asWorktreeJob('sync', name, values, ['sync', name], async () => syncTask(name, values))
184
+ })
185
+ },
186
+ },
187
+ rm: {
188
+ summary: 'stop a worktree stack and delete its checkouts, volumes, certificates and routes, keeping its branches',
189
+ run: async (args) => {
190
+ const { values, positionals: [task] } = parse(args, RM_USAGE, {
191
+ project: PROJECT_OPTION,
192
+ force: { type: 'boolean', short: 'f', description: 'remove even with uncommitted changes or commits on no branch' },
193
+ bg: BG_OPTION,
194
+ }, { positionals: ['<task>'], candidates: TASK })
195
+
196
+ return guarded(async () => {
197
+ await assertRemovable(task, values)
198
+
199
+ return asWorktreeJob('rm', task, values, ['rm', task, ...(values.force ? ['--force'] : [])], async () => removeTask(task, values))
200
+ })
201
+ },
202
+ },
203
+ up: {
204
+ summary: 'start a worktree stack',
205
+ run: async (args) => {
206
+ const { values, positionals: [task] } = parse(args, UP_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ['[task]'], candidates: TASK })
207
+
208
+ return guarded(async () => {
209
+ const worktree = await locateWorktree(process.cwd(), task, values.project)
210
+
211
+ return asWorktreeJob('up', worktree.task, values, ['up', worktree.task], async () => upTask(worktree))
212
+ })
213
+ },
214
+ },
215
+ down: {
216
+ summary: 'stop a worktree stack',
217
+ run: async (args) => {
218
+ const { values, positionals: [task] } = parse(args, DOWN_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ['[task]'], candidates: TASK })
219
+
220
+ return guarded(async () => {
221
+ const worktree = await locateWorktree(process.cwd(), task, values.project)
222
+
223
+ return asWorktreeJob('down', worktree.task, values, ['down', worktree.task], async () => downTask(worktree))
224
+ })
225
+ },
226
+ },
227
+ ls: {
228
+ summary: 'list main and the worktrees of the current project, or of every project',
229
+ run: async (args) => {
230
+ const { values } = parse(args, LS_USAGE, {
231
+ project: PROJECT_OPTION,
232
+ all: { type: 'boolean', short: 'a', description: 'every project, even from inside one' },
233
+ json: { type: 'boolean', description: 'print { project, checkouts }, project being the one the directory is in, null outside every one' },
234
+ }, { positionals: [] })
235
+
236
+ return guarded(async () => listWorktrees(values))
237
+ },
238
+ },
239
+ path: {
240
+ summary: 'print the directory of a worktree, or of main',
241
+ run: async (args) => {
242
+ const { values, positionals: [task] } = parse(args, PATH_USAGE, { project: PROJECT_OPTION }, { positionals: ['[task]'], candidates: TASK })
243
+
244
+ return guarded(async () => printPath(task, values))
245
+ },
246
+ },
247
+ init: {
248
+ summary: 'draft a manifest for the project checked out in a directory',
249
+ run: async (args) => {
250
+ const { values, positionals: [dir] } = parse(args, INIT_USAGE, {
251
+ name: { type: 'string', description: 'the manifest\'s name, also hashed into the dev server port (the checkout\'s folder name)' },
252
+ print: { type: 'boolean', description: 'print the draft instead of writing it' },
253
+ }, { positionals: ['[dir]'] })
254
+
255
+ return guarded(async () => initProject(dir ?? process.cwd(), values))
256
+ },
257
+ },
258
+ run: {
259
+ summary: 'run a command of a worktree in a throwaway container of its run service, against a test database of its own',
260
+ run: async (args) => {
261
+ const { values, positionals: [task], rest } = parse(args, RUN_USAGE, { project: PROJECT_OPTION }, {
262
+ positionals: ['<task>'],
263
+ candidates: TASK,
264
+ rest: true,
265
+ examples: [['wt run planning -- vendor/bin/phpunit --filter Foo', 'a test run in the planning worktree']],
266
+ })
267
+
268
+ if (rest === undefined || rest.length === 0)
269
+ badUsage('give the command after --')
270
+
271
+ return guarded(async () => runTask(task, rest, values.project))
272
+ },
273
+ },
274
+ heavy: {
275
+ summary: 'run a heavy command once those queued before it, from any session, are done',
276
+ run: async (args) => {
277
+ const { rest } = parse(args, HEAVY_USAGE, {}, {
278
+ positionals: [],
279
+ rest: true,
280
+ examples: [['wt heavy -- wt run planning -- vendor/bin/phpunit', 'a full suite, queued']],
281
+ })
282
+
283
+ if (rest === undefined || rest.length === 0)
284
+ badUsage('give the command after --')
285
+
286
+ return guarded(async () => runHeavy(rest))
287
+ },
288
+ },
289
+ shell: {
290
+ summary: 'print the shell function letting `wt cd` change directory',
291
+ run: async (args) => {
292
+ const { positionals: [shell] } = parse(args, SHELL_USAGE, {}, { positionals: ['<shell>'], candidates: { '<shell>': async () => Promise.resolve(['fish']) } })
293
+
294
+ return guarded(async () => {
295
+ console.log(shellWrapper(shell))
296
+ await Promise.resolve()
297
+ })
298
+ },
299
+ },
300
+ url: {
301
+ summary: 'print the URLs of a worktree',
302
+ hidden: true,
303
+ run: async (args) => {
304
+ const { values, positionals: [task] } = parse(args, URL_USAGE, { project: PROJECT_OPTION }, { positionals: ['[task]'], candidates: TASK })
305
+
306
+ return guarded(async () => printUrls(task, values))
307
+ },
308
+ },
309
+ tasks: {
310
+ summary: 'print the worktree names of the project',
311
+ hidden: true,
312
+ run: async (args) => {
313
+ const { values } = parse(args, TASKS_USAGE, { project: PROJECT_OPTION }, { positionals: [] })
314
+
315
+ return guarded(async () => printTasks(values))
316
+ },
317
+ },
318
+ },
319
+ })
@@ -0,0 +1,160 @@
1
+ import type { Worktree } from './project'
2
+ import { existsSync, rmSync } from 'node:fs'
3
+ import { $ } from 'bun'
4
+ import { KnownError } from './errors'
5
+ import { failureText } from './files'
6
+ import { addWorktrees, dirtyRepos, isRegistered, removeWorktrees, unreachableCommits } from './git'
7
+ import { assertWorktreeExists, listTasks, locate, locateWorktree, worktreeOf, WtError } from './project'
8
+ import { urlsOf } from './routes'
9
+ import { forgetTestDatabases } from './run'
10
+ import { afterRemove, hasContainers, stackDown, stackUp } from './stack'
11
+ import { syncWorktree } from './sync'
12
+
13
+ export interface GlobalOptions {
14
+ project?: string
15
+ }
16
+
17
+ const ANONYMOUS_VOLUME = /^[0-9a-f]{64}$/
18
+ const WHITESPACE = /\s+/
19
+
20
+ /** The anonymous volumes of the worktree's containers, read before they are removed, as nothing ties those volumes to the worktree afterwards. */
21
+ async function anonymousVolumes(worktree: Worktree): Promise<string[]> {
22
+ const containers = (await $`docker ps -aq --filter ${`label=com.docker.compose.project=${worktree.id}`}`.quiet().text()).split('\n').filter(Boolean)
23
+
24
+ if (!containers.length)
25
+ return []
26
+
27
+ const mounts = await $`docker inspect --format ${'{{range .Mounts}}{{if eq .Type "volume"}}{{.Name}} {{end}}{{end}}'} ${containers}`.quiet().nothrow()
28
+
29
+ return mounts.text().split(WHITESPACE).filter(name => ANONYMOUS_VOLUME.test(name))
30
+ }
31
+
32
+ // Only volumes compose made for the worktree go: a volume with a fixed `name:` may be main's, whatever project created it.
33
+ async function removeVolumes(worktree: Worktree, anonymous: string[]): Promise<void> {
34
+ const named = (await $`docker volume ls -q --filter ${`label=com.docker.compose.project=${worktree.id}`}`.quiet().text()).split('\n').filter(volume => volume.startsWith(`${worktree.id}_`))
35
+ const volumes = [...new Set([...named, ...anonymous])]
36
+
37
+ if (!volumes.length)
38
+ return
39
+
40
+ const removed = await $`docker volume rm ${volumes}`.quiet().nothrow()
41
+
42
+ if (removed.exitCode !== 0)
43
+ throw new WtError(`could not remove the volumes of ${worktree.id}:\n${removed.stderr.toString().trim()}`)
44
+ }
45
+
46
+ export async function addTask(task: string, branch: string | undefined, options: GlobalOptions): Promise<void> {
47
+ const { project } = await locate(process.cwd(), options.project)
48
+ const worktree = worktreeOf(project, task)
49
+ const checkout = branch ?? `wt/${task}`
50
+
51
+ await addWorktrees(worktree, checkout)
52
+
53
+ try {
54
+ await syncWorktree(worktree)
55
+ }
56
+ catch (error) {
57
+ 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
+
59
+ if (error instanceof KnownError || error instanceof $.ShellError)
60
+ throw new WtError(`${failureText(error)}\n${way}`)
61
+
62
+ // A bug keeps its stack trace
63
+ console.error(`wt: ${way}`)
64
+
65
+ throw error
66
+ }
67
+
68
+ console.log(`wt: created ${worktree.dir} on ${checkout}`)
69
+
70
+ for (const url of urlsOf(worktree))
71
+ console.log(` ${url}`)
72
+
73
+ console.log(` wt up ${task}`)
74
+ }
75
+
76
+ export async function syncTask(task: string | undefined, options: GlobalOptions): Promise<void> {
77
+ const worktree = await locateWorktree(process.cwd(), task, options.project)
78
+
79
+ await syncWorktree(worktree)
80
+ console.log(`wt: synced ${worktree.id}`)
81
+ }
82
+
83
+ /** Refuses a removal with nothing to remove, before it claims a job that would leave a record of a worktree never there. */
84
+ export async function assertRemovable(task: string, options: GlobalOptions): Promise<void> {
85
+ const worktree = await locateWorktree(process.cwd(), task, options.project)
86
+
87
+ if (!existsSync(worktree.dir) && !Object.values(worktree.files).some(file => existsSync(file)) && !await isRegistered(worktree))
88
+ throw new WtError(`no worktree ${worktree.task} of ${worktree.project.name}, nothing removed`)
89
+ }
90
+
91
+ export async function removeTask(task: string, options: GlobalOptions & { force?: boolean }): Promise<void> {
92
+ const worktree = await locateWorktree(process.cwd(), task, options.project)
93
+
94
+ // Every command after this one spawns from the cwd, which may be the directory about to go.
95
+ process.chdir(worktree.project.root)
96
+
97
+ const anonymous = await anonymousVolumes(worktree)
98
+
99
+ if (existsSync(worktree.dir)) {
100
+ const dirty = options.force ? [] : await dirtyRepos(worktree)
101
+
102
+ if (dirty.length)
103
+ throw new WtError(`uncommitted changes in ${dirty.join(', ')}, commit them or pass --force`)
104
+
105
+ const unreachable = options.force ? [] : await unreachableCommits(worktree)
106
+
107
+ if (unreachable.length)
108
+ throw new WtError(`commits on no branch in ${unreachable.join(', ')} would be lost, \`git switch -c <branch>\` there or pass --force`)
109
+ }
110
+
111
+ // With the folder gone, its containers may still hold its volumes
112
+ if (existsSync(worktree.dir) || await hasContainers(worktree.id))
113
+ await stackDown(worktree)
114
+
115
+ await removeVolumes(worktree, anonymous)
116
+
117
+ for (const file of Object.values(worktree.files))
118
+ rmSync(file, { force: true })
119
+
120
+ await forgetTestDatabases(worktree)
121
+
122
+ await removeWorktrees(worktree)
123
+ await afterRemove(worktree)
124
+
125
+ console.log(`wt: removed ${worktree.id}, its branches are kept`)
126
+ }
127
+
128
+ export async function printUrls(task: string | undefined, options: GlobalOptions): Promise<void> {
129
+ for (const url of urlsOf(await locateWorktree(process.cwd(), task, options.project)))
130
+ console.log(url)
131
+ }
132
+
133
+ export async function upTask(worktree: Worktree): Promise<void> {
134
+ assertWorktreeExists(worktree)
135
+ await stackUp(worktree)
136
+ }
137
+
138
+ export async function downTask(worktree: Worktree): Promise<void> {
139
+ assertWorktreeExists(worktree)
140
+ await stackDown(worktree)
141
+ }
142
+
143
+ export async function printPath(task: string | undefined, options: GlobalOptions): Promise<void> {
144
+ const { project } = await locate(process.cwd(), options.project)
145
+
146
+ if (task === undefined || task === 'main')
147
+ return console.log(project.root)
148
+
149
+ const worktree = worktreeOf(project, task)
150
+
151
+ assertWorktreeExists(worktree)
152
+ console.log(worktree.dir)
153
+ }
154
+
155
+ export async function printTasks(options: GlobalOptions): Promise<void> {
156
+ try {
157
+ console.log(listTasks((await locate(process.cwd(), options.project)).project).join('\n'))
158
+ }
159
+ catch {}
160
+ }