@kaynooo/cli-wt 0.1.2 → 0.1.3

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,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-wt",
3
3
  "type": "module",
4
- "version": "0.1.2",
4
+ "version": "0.1.3",
5
5
  "description": "wt: git worktrees of a compose project, each with its own stack, data and <task>.<host> subdomains beside main.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -31,9 +31,9 @@
31
31
  "wt": "$npm_execpath src/cli.ts"
32
32
  },
33
33
  "dependencies": {
34
- "@kaynooo/cli-env": "0.14.1",
35
- "@kaynooo/cli-kit": "0.41.0",
34
+ "@kaynooo/cli-env": "0.15.0",
35
+ "@kaynooo/cli-kit": "0.45.0",
36
36
  "@kaynooo/devproxy": "0.2.0",
37
- "@kaynooo/utils": "3.0.0"
37
+ "@kaynooo/utils": "3.1.0"
38
38
  }
39
39
  }
package/src/cli.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
 
3
3
  import type { GlobalOptions } from './commands'
4
+ import type { Worktree } from './project'
4
5
  import process from 'node:process'
5
6
  import { badUsage, parse, runCli } from '@kaynooo/cli-kit'
6
7
  import { addTask, assertRemovable, downTask, printPath, printTasks, printUrls, removeTask, syncTask, upTask } from './commands'
@@ -9,7 +10,7 @@ import { failKnown } from './errors'
9
10
  import { initProject } from './init'
10
11
  import { Jobs } from './jobs'
11
12
  import { listWorktrees } from './list'
12
- import { listTasks, loadProjects, locate, locateWorktree } from './project'
13
+ import { assertWorktreeExists, listTasks, loadProjects, locate, locateWorktree, worktreeOf } from './project'
13
14
  import { runHeavy, runTask } from './run'
14
15
  import { shellWrapper } from './shell'
15
16
  import { slugOf } from './stack'
@@ -18,18 +19,28 @@ async function jobs(): Promise<Jobs> {
18
19
  return new Jobs({ dir: (await wtConfig()).jobs, app: 'wt' })
19
20
  }
20
21
 
21
- // A config that does not load fails like any other known error.
22
- async function guarded(action: () => Promise<number | void>): Promise<number> {
22
+ // A config that does not load fails like any other known error; `bg` names a `--bg` command, whose refusal is notified too.
23
+ async function guarded(action: () => Promise<number | void>, bg?: string): Promise<number> {
23
24
  try {
24
- return await (await jobs()).guarded(action)
25
+ return await (await jobs()).guarded(action, bg)
25
26
  }
26
27
  catch (error) {
27
28
  return failKnown(error)
28
29
  }
29
30
  }
30
31
 
32
+ // The name a `--bg` command is notified under, none without `--bg`.
33
+ function bgName(values: { bg?: boolean }, ...words: (string | undefined)[]): string | undefined {
34
+ return values.bg ? ['wt', ...words.filter(word => word !== undefined)].join(' ') : undefined
35
+ }
36
+
31
37
  async function projectNames(): Promise<string[]> {
32
- return (await loadProjects()).map(project => project.name)
38
+ try {
39
+ return (await loadProjects()).map(project => project.name)
40
+ }
41
+ catch {
42
+ return []
43
+ }
33
44
  }
34
45
 
35
46
  // The worktrees of the project the current directory belongs to, none outside one.
@@ -49,9 +60,8 @@ const PROJECT_OPTION = { type: 'string', short: 'p', candidates: projectNames, d
49
60
 
50
61
  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
62
 
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)
63
+ // Every action on a worktree holds its stack's lock, so an up cannot race a removal, and --bg detaches it. Its caller checks the worktree first: a job claimed for one that cannot be acted on leaves a record behind, or a `--bg` one failing out of sight.
64
+ async function asWorktreeJob(verb: 'add' | 'sync' | 'rm' | 'up' | 'down', { project, task }: Worktree, options: GlobalOptions & { bg?: boolean }, argv: string[], work: () => Promise<void>): Promise<number> {
55
65
  const ref = `${project.name}/${task}`
56
66
  const stack = { ref, slug: slugOf(ref) }
57
67
  const queue = await jobs()
@@ -66,16 +76,9 @@ async function asWorktreeJob(verb: 'add' | 'sync' | 'rm' | 'up' | 'down', task:
66
76
  return code
67
77
  }
68
78
 
69
- try {
70
- const job = queue.detach(stack, verb, [import.meta.path, ...argv, '-p', project.name])
79
+ const job = queue.detach(stack, verb, [import.meta.path, ...argv, '-p', project.name])
71
80
 
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
- }
81
+ console.log(`wt: ${verb} ${ref} runs out of sight, its output in ${job.log}`)
79
82
 
80
83
  return 0
81
84
  }
@@ -169,7 +172,11 @@ process.exitCode = await runCli({
169
172
  run: async (args) => {
170
173
  const { values, positionals: [task, branch] } = parse(args, ADD_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ['<task>', '[branch]'] })
171
174
 
172
- return guarded(async () => asWorktreeJob('add', task, values, ['add', task, ...(branch === undefined ? [] : [branch])], async () => addTask(task, branch, values)))
175
+ return guarded(async () => {
176
+ const worktree = worktreeOf((await locate(process.cwd(), values.project)).project, task)
177
+
178
+ return asWorktreeJob('add', worktree, values, ['add', task, ...(branch === undefined ? [] : [branch])], async () => addTask(task, branch, values))
179
+ }, bgName(values, 'add', task))
173
180
  },
174
181
  },
175
182
  sync: {
@@ -178,9 +185,11 @@ process.exitCode = await runCli({
178
185
  const { values, positionals: [task] } = parse(args, SYNC_USAGE, { project: PROJECT_OPTION }, { positionals: ['[task]'], candidates: TASK })
179
186
 
180
187
  return guarded(async () => {
181
- const { task: name } = await locateWorktree(process.cwd(), task, values.project)
188
+ const worktree = await locateWorktree(process.cwd(), task, values.project)
189
+
190
+ assertWorktreeExists(worktree)
182
191
 
183
- return asWorktreeJob('sync', name, values, ['sync', name], async () => syncTask(name, values))
192
+ return asWorktreeJob('sync', worktree, values, ['sync', worktree.task], async () => syncTask(worktree.task, values))
184
193
  })
185
194
  },
186
195
  },
@@ -194,10 +203,10 @@ process.exitCode = await runCli({
194
203
  }, { positionals: ['<task>'], candidates: TASK })
195
204
 
196
205
  return guarded(async () => {
197
- await assertRemovable(task, values)
206
+ const worktree = await assertRemovable(task, values)
198
207
 
199
- return asWorktreeJob('rm', task, values, ['rm', task, ...(values.force ? ['--force'] : [])], async () => removeTask(task, values))
200
- })
208
+ return asWorktreeJob('rm', worktree, values, ['rm', task, ...(values.force ? ['--force'] : [])], async () => removeTask(task, values))
209
+ }, bgName(values, 'rm', task))
201
210
  },
202
211
  },
203
212
  up: {
@@ -208,8 +217,10 @@ process.exitCode = await runCli({
208
217
  return guarded(async () => {
209
218
  const worktree = await locateWorktree(process.cwd(), task, values.project)
210
219
 
211
- return asWorktreeJob('up', worktree.task, values, ['up', worktree.task], async () => upTask(worktree))
212
- })
220
+ assertWorktreeExists(worktree)
221
+
222
+ return asWorktreeJob('up', worktree, values, ['up', worktree.task], async () => upTask(worktree))
223
+ }, bgName(values, 'up', task))
213
224
  },
214
225
  },
215
226
  down: {
@@ -220,8 +231,10 @@ process.exitCode = await runCli({
220
231
  return guarded(async () => {
221
232
  const worktree = await locateWorktree(process.cwd(), task, values.project)
222
233
 
223
- return asWorktreeJob('down', worktree.task, values, ['down', worktree.task], async () => downTask(worktree))
224
- })
234
+ assertWorktreeExists(worktree)
235
+
236
+ return asWorktreeJob('down', worktree, values, ['down', worktree.task], async () => downTask(worktree))
237
+ }, bgName(values, 'down', task))
225
238
  },
226
239
  },
227
240
  ls: {
package/src/commands.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  import type { Worktree } from './project'
2
2
  import { existsSync, rmSync } from 'node:fs'
3
3
  import { $ } from 'bun'
4
- import { KnownError } from './errors'
5
- import { failureText } from './files'
4
+ import { knownMessage } from './errors'
6
5
  import { addWorktrees, dirtyRepos, isRegistered, removeWorktrees, unreachableCommits } from './git'
7
6
  import { assertWorktreeExists, listTasks, locate, locateWorktree, worktreeOf, WtError } from './project'
8
7
  import { urlsOf } from './routes'
@@ -56,8 +55,10 @@ export async function addTask(task: string, branch: string | undefined, options:
56
55
  catch (error) {
57
56
  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
57
 
59
- if (error instanceof KnownError || error instanceof $.ShellError)
60
- throw new WtError(`${failureText(error)}\n${way}`)
58
+ const message = knownMessage(error)
59
+
60
+ if (message !== undefined)
61
+ throw new WtError(`${message}\n${way}`)
61
62
 
62
63
  // A bug keeps its stack trace
63
64
  console.error(`wt: ${way}`)
@@ -97,13 +98,15 @@ async function refuseLosingWork(worktree: Worktree, force: boolean): Promise<voi
97
98
  }
98
99
 
99
100
  /** 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<void> {
101
+ export async function assertRemovable(task: string, options: GlobalOptions & { force?: boolean }): Promise<Worktree> {
101
102
  const worktree = await locateWorktree(process.cwd(), task, options.project)
102
103
 
103
104
  if (!existsSync(worktree.dir) && !Object.values(worktree.files).some(file => existsSync(file)) && !await isRegistered(worktree))
104
105
  throw new WtError(`no worktree ${worktree.task} of ${worktree.project.name}, nothing removed`)
105
106
 
106
107
  await refuseLosingWork(worktree, options.force === true)
108
+
109
+ return worktree
107
110
  }
108
111
 
109
112
  export async function removeTask(task: string, options: GlobalOptions & { force?: boolean }): Promise<void> {
package/src/errors.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { readFileSync } from 'node:fs'
2
2
  import { fail } from '@kaynooo/cli-kit'
3
+ import { $ } from 'bun'
3
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. */
5
6
  export class KnownError extends Error {}
@@ -27,10 +28,25 @@ export function alive(pid: number): boolean {
27
28
  }
28
29
  }
29
30
 
31
+ /** 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. */
32
+ export function knownMessage(error: unknown): string | undefined {
33
+ if (error instanceof KnownError)
34
+ return error.message
35
+
36
+ return error instanceof $.ShellError ? error.stderr.toString().trim() || error.message : undefined
37
+ }
38
+
39
+ /** What a failed command said, else the error's message. */
40
+ export function failureText(error: unknown): string {
41
+ return knownMessage(error) ?? (error instanceof Error ? error.message : String(error))
42
+ }
43
+
30
44
  /** Ends the command on a known failure with its message and exit code 1; anything else is thrown on. */
31
45
  export function failKnown(error: unknown): never {
32
- if (error instanceof KnownError)
33
- fail(error.message, 1)
46
+ const message = knownMessage(error)
47
+
48
+ if (message !== undefined)
49
+ fail(message, 1)
34
50
 
35
51
  throw error
36
52
  }
package/src/files.ts CHANGED
@@ -6,6 +6,7 @@ import { basename, dirname, join } from 'node:path'
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
 
@@ -185,14 +186,6 @@ export async function settle(copies: (() => Promise<void>)[]): Promise<unknown[]
185
186
  return results.flatMap(result => result.status === 'rejected' ? [result.reason as unknown] : [])
186
187
  }
187
188
 
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
189
  // The ids of main's containers a clone of the project paused, one per line, while it copies.
197
190
  const pausedRecord = (worktree: Worktree) => queueDir(worktree.project.settings, `${worktree.project.name}.paused`)
198
191
 
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- /** What other tools build on wt with: athome reads the manifests and worktrees, shares the job locks and runs a worktree's setup. */
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'
package/src/jobs.ts CHANGED
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  * One action at a time per stack: each holds the stack's lock while it runs and leaves a job file saying what ran and how it ended.
3
3
  * `--bg` runs the action detached from any terminal, its output in the stack's log, a notification telling how it went.
4
- * Tools pointing at the same folder share the locks: athome's up and wt's rm of one worktree never run together.
4
+ * Tools pointing at the same folder share the locks: a project tool's up and wt's rm of one worktree never run together.
5
5
  */
6
6
 
7
7
  import { closeSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
8
8
  import { join } from 'node:path'
9
9
  import { $ } from 'bun'
10
- import { alive, bootTime, failKnown, KnownError } from './errors'
10
+ import { alive, bootTime, failKnown, failureText, KnownError, knownMessage } from './errors'
11
11
 
12
12
  export interface Job {
13
13
  ref: string
@@ -36,7 +36,7 @@ export interface JobState {
36
36
  last?: Job
37
37
  }
38
38
 
39
- /** The locks the jobs of this process tree hold, one `<pid> <lock path>` per line, so a command a job runs (wt rm running `athome down`) works inside it instead of being refused. */
39
+ /** The locks the jobs of this process tree hold, one `<pid> <lock path>` per line, so a command a job runs (wt rm running a project tool's `down`) works inside it instead of being refused. */
40
40
  export const HELD_ENV = 'WT_JOBS_HELD'
41
41
  /** How long a detached job may take to write its pid before its lock counts as abandoned. */
42
42
  const STARTING_MS = 30_000
@@ -354,7 +354,7 @@ export class Jobs {
354
354
  return await action() ?? 0
355
355
  }
356
356
  catch (error) {
357
- const message = error instanceof Error ? error.message : String(error)
357
+ const message = failureText(error)
358
358
 
359
359
  await this.failDetached(message)
360
360
 
@@ -391,7 +391,7 @@ export class Jobs {
391
391
  return job
392
392
  }
393
393
 
394
- /** The command a job ran, as a notification title names it: "athome restart booki php". */
394
+ /** The command a job ran, as a notification title names it: "proj restart booki php". */
395
395
  what(job: Pick<Job, 'verb' | 'ref' | 'service'>): string {
396
396
  return [this.app, job.verb, job.ref, ...job.service !== undefined ? [job.service] : []].join(' ')
397
397
  }
@@ -418,7 +418,9 @@ async function attempt(work: () => Promise<void>): Promise<number> {
418
418
  return 0
419
419
  }
420
420
  catch (error) {
421
- console.error(error instanceof KnownError ? `error: ${error.message}` : error)
421
+ const message = knownMessage(error)
422
+
423
+ console.error(message !== undefined ? `error: ${message}` : error)
422
424
 
423
425
  return 1
424
426
  }
package/src/project.ts CHANGED
@@ -106,7 +106,7 @@ export async function loadProjects(): Promise<Project[]> {
106
106
  const settings = await wtConfig()
107
107
  const files = existsSync(settings.manifests) ? readdirSync(settings.manifests).filter(file => file.endsWith('.ts')).sort() : []
108
108
 
109
- return Promise.all(files.map(async (file) => {
109
+ const projects = await Promise.all(files.map(async (file) => {
110
110
  const { default: config } = await import(join(settings.manifests, file)) as { default: ProjectConfig }
111
111
  const project = { ...config, root: expandHome(config.root), name: basename(file, '.ts'), settings }
112
112
 
@@ -114,6 +114,16 @@ export async function loadProjects(): Promise<Project[]> {
114
114
 
115
115
  return project
116
116
  }))
117
+
118
+ // A worktree's stack is named after its checkout's folder, kept so that running stacks keep their containers and volumes.
119
+ for (const [index, project] of projects.entries()) {
120
+ const twin = projects.slice(0, index).find(other => basename(other.root) === basename(project.root))
121
+
122
+ if (twin)
123
+ throw new WtError(`${twin.name}.ts and ${project.name}.ts both have a checkout named ${basename(project.root)}, so their worktrees would share stacks and volumes: rename the folder of a checkout that has no worktrees yet, or remove one of the files`)
124
+ }
125
+
126
+ return projects
117
127
  }
118
128
 
119
129
  export async function findProject(name: string): Promise<Project> {
package/src/proxy.ts CHANGED
@@ -12,15 +12,15 @@ export interface ProxyHost {
12
12
  passthrough: boolean
13
13
  }
14
14
 
15
- // PATH first, so a test sandbox's fake answers instead of the real one.
16
- function devproxyArgv(): string[] {
17
- const onPath = Bun.which('devproxy')
15
+ // PATH first, so a test sandbox's fake answers instead of the real one. The installed copy runs with devproxy's own shebang flags, so the cwd's .env (a worktree's COMPOSE_PROJECT_NAME) stays out of it.
16
+ export function devproxyArgv(path = process.env.PATH ?? ''): string[] {
17
+ const onPath = Bun.which('devproxy', { PATH: path })
18
18
 
19
19
  if (onPath !== null)
20
20
  return [onPath]
21
21
 
22
22
  try {
23
- return [process.execPath, join(dirname(Bun.resolveSync('@kaynooo/devproxy', import.meta.dir)), '..', 'dist', 'cli.js')]
23
+ return [process.execPath, '--no-env-file', '--config=/dev/null', join(dirname(Bun.resolveSync('@kaynooo/devproxy', import.meta.dir)), '..', 'dist', 'cli.js')]
24
24
  }
25
25
  catch {
26
26
  return []
package/src/stack.ts CHANGED
@@ -13,7 +13,7 @@ import { devproxyUp, hasDevproxy } from './proxy'
13
13
  const LEADING_ROOT = /^[/~]+/
14
14
  const UNSAFE_IN_FILE_NAME = /[^\w.-]+/g
15
15
 
16
- /** The name a stack's job files go by: `booki/planning` gives `booki--planning`, as athome names them. */
16
+ /** The name a stack's job files go by: `booki/planning` gives `booki--planning`, as other tools name them. */
17
17
  export function slugOf(ref: string): string {
18
18
  return ref.replace(LEADING_ROOT, '').replace(UNSAFE_IN_FILE_NAME, '--')
19
19
  }