@kaynooo/cli-wt 0.1.2 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +17 -10
  2. package/dist/cli-0gbs87r4.js +313 -0
  3. package/dist/cli-1nyesy1b.js +674 -0
  4. package/dist/cli-4g5ehhgn.js +251 -0
  5. package/dist/cli-6ybxw5sc.js +97 -0
  6. package/dist/cli-dmkfxdbr.js +153 -0
  7. package/dist/cli-dmzvmpge.js +106 -0
  8. package/dist/cli-e2h20nyy.js +36 -0
  9. package/dist/cli-j82fak6j.js +69 -0
  10. package/dist/cli-k4471y24.js +779 -0
  11. package/dist/cli-kek450vq.js +519 -0
  12. package/dist/cli-n5rt07v7.js +105 -0
  13. package/dist/cli-pkvw2k4x.js +37 -0
  14. package/dist/cli-w4w36hng.js +67 -0
  15. package/dist/cli.js +238 -2592
  16. package/dist/commands-jtnbchtb.js +222 -0
  17. package/dist/init-4ynjrztr.js +166 -0
  18. package/dist/list-js6drtvg.js +88 -0
  19. package/dist/print-q6qaqg22.js +77 -0
  20. package/dist/prompt-y71tp3f5.js +436 -0
  21. package/dist/prune-beweag7w.js +17 -0
  22. package/dist/run-7eayrqwy.js +18 -0
  23. package/dist/shell-xrgvqrpp.js +55 -0
  24. package/dist/stack-h3pgyx1e.js +20 -0
  25. package/dist/tools-4j56r47a.js +13 -0
  26. package/package.json +6 -6
  27. package/src/cli.ts +270 -76
  28. package/src/commands.ts +58 -42
  29. package/src/compose.ts +37 -14
  30. package/src/config.ts +8 -1
  31. package/src/errors.ts +31 -5
  32. package/src/files.ts +15 -23
  33. package/src/git.ts +53 -7
  34. package/src/index.ts +3 -2
  35. package/src/init.ts +56 -10
  36. package/src/jobs.ts +60 -19
  37. package/src/list.ts +26 -13
  38. package/src/print.ts +76 -0
  39. package/src/project.ts +134 -23
  40. package/src/proxy.ts +9 -9
  41. package/src/prune.ts +149 -0
  42. package/src/queue.ts +27 -3
  43. package/src/run.ts +82 -23
  44. package/src/shell.ts +34 -7
  45. package/src/stack.ts +10 -12
  46. package/src/sync.ts +28 -3
  47. package/src/tools.ts +91 -0
package/src/init.ts CHANGED
@@ -3,15 +3,16 @@ import type { Project, Route } from './project'
3
3
  import { existsSync, mkdirSync, readdirSync, statSync, writeFileSync } from 'node:fs'
4
4
  import { homedir } from 'node:os'
5
5
  import { basename, join, relative } from 'node:path'
6
+ import { warn } from '@kaynooo/cli-kit'
6
7
  import { composeConfig } from './compose'
7
8
  import { wtConfig } from './config'
8
9
  import { volumeExists } from './files'
9
10
  import { git } from './git'
10
11
  import { stringToPort } from './port'
11
12
  import { WtError } from './project'
12
- import { proxyHostList } from './proxy'
13
+ import { hasDevproxy, proxyHostList } from './proxy'
13
14
 
14
- type Draft = Omit<Project, 'link' | 'env' | 'setup' | 'settings'> & Required<Pick<Project, 'copy' | 'clone' | 'skip'>>
15
+ export type Draft = Omit<Project, 'link' | 'env' | 'setup' | 'settings'> & Required<Pick<Project, 'copy' | 'clone' | 'skip'>>
15
16
 
16
17
  const CERT_PATH = /cert/i
17
18
  // devproxy's upstreams: `http://<container>:<port>` or `host:<port>`, and `<container>:<port>` for a passthrough.
@@ -43,8 +44,9 @@ async function findRoutes(config: ComposeConfig, name: string, network: string):
43
44
  || `${config.name}-${service}-1` === target
44
45
  || settings.networks?.[network]?.aliases?.includes(target))?.[0]
45
46
  const routes: Route[] = []
47
+ const hosts = await proxyHostList()
46
48
 
47
- for (const { host, to, passthrough } of await proxyHostList()) {
49
+ for (const { host, group, to, passthrough } of hosts) {
48
50
  const [, target = '', port = ''] = (passthrough ? PASSTHROUGH_TARGET : HTTP_TARGET).exec(to) ?? []
49
51
  const service = serviceOf(target)
50
52
 
@@ -52,8 +54,18 @@ async function findRoutes(config: ComposeConfig, name: string, network: string):
52
54
  routes.push({ host, to: 'client' })
53
55
  else if (service !== undefined)
54
56
  routes.push({ host, to: `${service}:${Number(port)}`, ...passthrough ? { passthrough } : {} })
57
+ // A label of main's own stack, so one of its hosts, yet the draft cannot tell which service it reaches
58
+ else if (group === `docker-${config.name}`)
59
+ warn(`devproxy serves ${host} from ${config.name}'s labels, to ${to}, which is no service of it: add its route by hand`)
55
60
  }
56
61
 
62
+ if (!hasDevproxy())
63
+ warn('devproxy is not installed or has no config, so the draft has no routes: write them by hand, or set devproxy up and run init again')
64
+ else if (!hosts.length)
65
+ warn('devproxy serves no hosts, so the draft has no routes: start main\'s stack for devproxy to read its labels and run init again, or write them by hand')
66
+ else if (!routes.length)
67
+ warn(`none of the hosts devproxy serves leads to ${config.name}, so the draft has no routes: start main's stack and run init again, or write them by hand`)
68
+
57
69
  return routes
58
70
  }
59
71
 
@@ -94,7 +106,7 @@ async function draftFor(dir: string, given?: string): Promise<Draft> {
94
106
 
95
107
  return {
96
108
  name,
97
- root: root.replace(homedir(), '~'),
109
+ root: fromHome(root, homedir()),
98
110
  repos,
99
111
  copy: [...secrets, ...ignoredMounts.filter(path => CERT_PATH.test(path))],
100
112
  clone: [...ignoredMounts.filter(path => !CERT_PATH.test(path)), ...volumes.filter((_, index) => volumesExist[index]).map(([key]) => key)],
@@ -104,22 +116,32 @@ async function draftFor(dir: string, given?: string): Promise<Draft> {
104
116
  }
105
117
  }
106
118
 
107
- const list = (values: string[]) => `[${values.map(value => `'${value}'`).join(', ')}]`
119
+ /** The path as `~/…` when it lies under home, as it is otherwise. */
120
+ export function fromHome(path: string, home: string): string {
121
+ return path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path
122
+ }
123
+
124
+ const QUOTED = /['\\\n\r]/g
125
+ const ESCAPES: Record<string, string> = { '\'': '\\\'', '\\': '\\\\', '\n': '\\n', '\r': '\\r' }
108
126
 
109
- function render(draft: Draft): string {
110
- const routes = draft.routes.map(route => ` { host: '${route.host}', to: '${route.to}'${route.passthrough ? ', passthrough: true' : ''} },`)
127
+ // A single-quoted TypeScript string, its quotes, backslashes and line breaks escaped.
128
+ const str = (value: string) => `'${value.replace(QUOTED, char => ESCAPES[char]!)}'`
129
+ const list = (values: string[]) => `[${values.map(str).join(', ')}]`
130
+
131
+ export function render(draft: Draft): string {
132
+ const routes = draft.routes.map(route => ` { host: ${str(route.host)}, to: ${str(route.to)}${route.passthrough ? ', passthrough: true' : ''} },`)
111
133
 
112
134
  return [
113
135
  `import type { ProjectConfig } from '@kaynooo/cli-wt'`,
114
136
  '',
115
137
  '// Drafted by `wt init`: check every list against the stack before the first `wt add`.',
116
138
  'export default {',
117
- ` root: '${draft.root}',`,
139
+ ` root: ${str(draft.root)},`,
118
140
  ` repos: ${list(draft.repos)},`,
119
141
  ` copy: ${list(draft.copy)},`,
120
142
  ` clone: ${list(draft.clone)},`,
121
143
  ...draft.skip.length ? [` skip: ${list(draft.skip)},`] : [],
122
- ...draft.certs !== undefined ? [` certs: '${draft.certs}',`] : [],
144
+ ...draft.certs !== undefined ? [` certs: ${str(draft.certs)},`] : [],
123
145
  ' setup: [],',
124
146
  ' routes: [',
125
147
  ...routes,
@@ -142,8 +164,32 @@ export async function initProject(dir: string, options: { print?: boolean, name?
142
164
  mkdirSync(manifests, { recursive: true })
143
165
 
144
166
  if (existsSync(file))
145
- throw new WtError(`${file} already exists, compare with \`wt init --print\``)
167
+ throw new WtError(`${file} already exists`, 'compare it with `wt init --print`')
146
168
 
147
169
  writeFileSync(file, content)
170
+ writeTsconfig(manifests)
148
171
  console.log(`wt: drafted ${file}, review it before \`wt add\``)
149
172
  }
173
+
174
+ // wt's own folder, from src/ or the built dist/ alike; the package ships its sources.
175
+ const PACKAGE_ROOT = join(import.meta.dir, '..')
176
+
177
+ // Nothing resolves the manifests' `@kaynooo/cli-wt` import where they live, so a tsconfig beside them points it at the wt that wrote it, for an editor to type-check them. One already there is the user's and stays.
178
+ function writeTsconfig(manifests: string): void {
179
+ const file = join(manifests, 'tsconfig.json')
180
+
181
+ if (existsSync(file))
182
+ return
183
+
184
+ const compilerOptions = {
185
+ target: 'ESNext',
186
+ module: 'Preserve',
187
+ moduleResolution: 'bundler',
188
+ strict: true,
189
+ noEmit: true,
190
+ skipLibCheck: true,
191
+ paths: { '@kaynooo/cli-wt': [join(PACKAGE_ROOT, 'src', 'index.ts')] },
192
+ }
193
+
194
+ writeFileSync(file, `${JSON.stringify({ compilerOptions }, null, 2)}\n`)
195
+ }
package/src/jobs.ts CHANGED
@@ -1,13 +1,14 @@
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
+ import { formatAge, printError } from '@kaynooo/cli-kit'
9
10
  import { $ } from 'bun'
10
- import { alive, bootTime, failKnown, KnownError } from './errors'
11
+ import { alive, bootTime, failKnown, failureText, KnownError, knownHint, knownMessage } from './errors'
11
12
 
12
13
  export interface Job {
13
14
  ref: string
@@ -36,7 +37,7 @@ export interface JobState {
36
37
  last?: Job
37
38
  }
38
39
 
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. */
40
+ /** 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
41
  export const HELD_ENV = 'WT_JOBS_HELD'
41
42
  /** How long a detached job may take to write its pid before its lock counts as abandoned. */
42
43
  const STARTING_MS = 30_000
@@ -44,15 +45,26 @@ const STARTING_MS = 30_000
44
45
  const TAKEOVER_MS = 5_000
45
46
  const TAIL_BYTES = 4096
46
47
  /** What a refusal says of wt's own actions; another tool sharing the folder adds its verbs through `words`. */
47
- const DOING: Record<string, string> = { up: 'coming up', down: 'stopping', add: 'being made', sync: 'syncing', rm: 'being removed' }
48
+ const DOING: Record<string, string> = { 'up': 'coming up', 'down': 'stopping', 'add': 'being made', 'add --up': 'being made and brought up', 'sync': 'syncing', 'rm': 'being removed' }
48
49
  /** The actions a notification reports the success of, as a title and a body. */
49
- const DONE: Record<string, [string, string]> = { up: ['is up', 'Its stack came up'], add: ['is ready', 'The worktree is made, its stack still down'] }
50
+ const DONE: Record<string, [string, string]> = { 'up': ['is up', 'Its stack came up'], 'add': ['is ready', 'The worktree is made, its stack still down'], 'add --up': ['is up', 'The worktree is made and its stack came up'] }
51
+
52
+ /** How a job ended, by its exit code: null for one killed before it could say, any other code a failure. */
53
+ const OUTCOMES: Record<string, string> = { 0: 'ok', null: 'killed' }
50
54
 
51
55
  export interface JobWords {
52
56
  doing?: Record<string, string>
53
57
  done?: Record<string, [string, string]>
54
58
  }
55
59
 
60
+ const LEADING_ROOT = /^[/~]+/
61
+ const UNSAFE_IN_FILE_NAME = /[^\w.-]+/g
62
+
63
+ /** The name a stack's job files go by: `booki/planning` gives `booki--planning`, as other tools name them. */
64
+ export function slugOf(ref: string): string {
65
+ return ref.replace(LEADING_ROOT, '').replace(UNSAFE_IN_FILE_NAME, '--')
66
+ }
67
+
56
68
  /** Written beside the file and renamed over it, so a mod reading it meanwhile never sees half of it. */
57
69
  function writeJob(file: string, job: Job): void {
58
70
  const partial = `${file}.${process.pid}.tmp`
@@ -164,9 +176,24 @@ export function logTail(file: string, lines = 5): string {
164
176
  }
165
177
  }
166
178
 
179
+ // macOS has no notify-send; the title and body reach AppleScript as arguments, so nothing in them is read as script.
180
+ const OSASCRIPT_NOTIFY = ['-e', 'on run argv', '-e', 'display notification (item 2 of argv) with title (item 1 of argv)', '-e', 'end run']
181
+
182
+ /** Whether this machine shows a detached job's end: notify-send, or osascript on macOS. */
183
+ export function canNotify(): boolean {
184
+ return Bun.which('notify-send') !== null || Bun.which('osascript') !== null
185
+ }
186
+
167
187
  async function notify(app: string, title: string, body: string, critical = false): Promise<void> {
168
188
  if (Bun.which('notify-send') !== null)
169
189
  await $`notify-send -a ${app} ${critical ? ['-u', 'critical'] : []} ${title} ${body}`.quiet().nothrow()
190
+ else if (Bun.which('osascript') !== null)
191
+ await $`osascript ${OSASCRIPT_NOTIFY} ${`${app}: ${title}`} ${body}`.quiet().nothrow()
192
+ }
193
+
194
+ /** A `--bg` command refused before any job started (the stack busy, a ref it does not know, a config that does not load): told by notification, as its caller is often a popup that closed meanwhile. */
195
+ export async function notifyRefused(app: string, what: string, message: string): Promise<void> {
196
+ await notify(app, `${what} not started`, message, true)
170
197
  }
171
198
 
172
199
  /** The jobs of one folder, notified under `app`, whose `<APP>_JOB` env var marks the detached process of a job. */
@@ -281,6 +308,17 @@ export class Jobs {
281
308
  return states
282
309
  }
283
310
 
311
+ /** A stack's job in a few words: "coming up" while one runs, else how the last ended, "up ok 5m ago", "rm failed 2h ago"; empty when it never had one. */
312
+ summary({ running, last }: JobState, now = Date.now()): string {
313
+ if (running !== undefined)
314
+ return doing(this.doing, running)
315
+
316
+ if (last === undefined)
317
+ return ''
318
+
319
+ return [last.verb, last.service, OUTCOMES[String(last.code)] ?? 'failed', formatAge(last.endedAt ?? last.startedAt, now)].filter(word => word !== undefined).join(' ')
320
+ }
321
+
284
322
  /** Drops what a stack's jobs left, for a worktree removed for good: one made again under its name starts with no history. */
285
323
  forget(stack: Pick<JobStack, 'slug'>): void {
286
324
  for (const file of Object.values(this.paths(stack.slug)))
@@ -294,7 +332,7 @@ export class Jobs {
294
332
  */
295
333
  async run(stack: JobStack, verb: string, work: (detached: boolean) => Promise<void>, service?: string): Promise<number> {
296
334
  if (this.holds(stack))
297
- return attempt(async () => work(false))
335
+ return attempt(`${this.app} ${verb}`, async () => work(false))
298
336
 
299
337
  const detached = process.env[this.env] === stack.slug
300
338
  const job = detached ? this.adopt(stack) : this.claim(stack, verb, false, service)
@@ -307,7 +345,7 @@ export class Jobs {
307
345
  let code = 1
308
346
 
309
347
  try {
310
- code = await attempt(async () => work(detached))
348
+ code = await attempt(`${this.app} ${verb}`, async () => work(detached))
311
349
  }
312
350
  finally {
313
351
  if (before === undefined)
@@ -354,28 +392,25 @@ export class Jobs {
354
392
  return await action() ?? 0
355
393
  }
356
394
  catch (error) {
357
- const message = error instanceof Error ? error.message : String(error)
395
+ const message = failureText(error)
358
396
 
359
397
  await this.failDetached(message)
360
398
 
361
399
  if (bg !== undefined)
362
- await this.notifyRefused(bg, message)
400
+ await notifyRefused(this.app, bg, message)
363
401
 
364
402
  return failKnown(error)
365
403
  }
366
404
  }
367
405
 
368
- /** A `--bg` command refused before any job started (the stack busy, a ref it does not know): told by notification, as its caller is often a popup that closed meanwhile. */
369
- async notifyRefused(what: string, message: string): Promise<void> {
370
- await notify(this.app, `${what} not started`, message, true)
371
- }
372
-
373
406
  /** Runs `argv` with bun away from any terminal, in a session of its own that outlives the caller (a Herdr popup that closes), the output in the stack's log. */
374
407
  detach(stack: JobStack, verb: string, argv: string[], service?: string): Job {
375
408
  const job = this.claim(stack, verb, true, service)
376
- const out = openSync(job.log, 'w')
409
+ let out: number | undefined
377
410
 
411
+ // A log that cannot be opened ends the job too, or its pid-less lock would read as starting for STARTING_MS
378
412
  try {
413
+ out = openSync(job.log, 'w')
379
414
  // Not setsid -f, which busybox and macOS lack
380
415
  Bun.spawn([process.execPath, '--no-env-file', ...argv], { stdio: ['ignore', out, out], env: { ...process.env, [this.env]: stack.slug }, detached: true }).unref()
381
416
  }
@@ -385,13 +420,14 @@ export class Jobs {
385
420
  throw error
386
421
  }
387
422
  finally {
388
- closeSync(out)
423
+ if (out !== undefined)
424
+ closeSync(out)
389
425
  }
390
426
 
391
427
  return job
392
428
  }
393
429
 
394
- /** The command a job ran, as a notification title names it: "athome restart booki php". */
430
+ /** The command a job ran, as a notification title names it: "proj restart booki php". */
395
431
  what(job: Pick<Job, 'verb' | 'ref' | 'service'>): string {
396
432
  return [this.app, job.verb, job.ref, ...job.service !== undefined ? [job.service] : []].join(' ')
397
433
  }
@@ -411,14 +447,19 @@ export class Jobs {
411
447
  }
412
448
  }
413
449
 
414
- async function attempt(work: () => Promise<void>): Promise<number> {
450
+ async function attempt(prefix: string, work: () => Promise<void>): Promise<number> {
415
451
  try {
416
452
  await work()
417
453
 
418
454
  return 0
419
455
  }
420
456
  catch (error) {
421
- console.error(error instanceof KnownError ? `error: ${error.message}` : error)
457
+ const message = knownMessage(error)
458
+
459
+ if (message !== undefined)
460
+ printError(prefix, message, knownHint(error))
461
+ else
462
+ console.error(error)
422
463
 
423
464
  return 1
424
465
  }
package/src/list.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  import type { GlobalOptions } from './commands'
2
+ import type { Jobs, JobState } from './jobs'
2
3
  import type { Project } from './project'
3
4
  import { basename, join } from 'node:path'
5
+ import { printJson, table } from '@kaynooo/cli-kit'
4
6
  import { runningProjects } from './compose'
7
+ import { wtJobs } from './config'
5
8
  import { currentBranch, git, unreachableCount } from './git'
6
- import { listTasks, loadProjects, locate, worktreeOf } from './project'
9
+ import { slugOf } from './jobs'
10
+ import { currentDir, listTasks, loadProjects, locate, stackName, worktreeOf } from './project'
7
11
  import { urlsOf } from './routes'
8
12
 
9
13
  export interface Checkout {
@@ -19,6 +23,8 @@ export interface Checkout {
19
23
  unbranched: number
20
24
  /** The terminal session name of the checkout: its folder's name for main, `<repo>--<task>` for a worktree, as Herdr spaces are named. */
21
25
  session: string
26
+ /** The job running on its stack, or how the last one ended: "coming up", "up ok 5m ago"; empty when it never had one. */
27
+ job: string
22
28
  }
23
29
 
24
30
  // A session name holds no "." or ":" (nor a slash or a blank), which a terminal's address reads as separators.
@@ -35,9 +41,13 @@ async function projectsToList(options: ListOptions): Promise<{ here: Project | n
35
41
  let here: Project | null = null
36
42
 
37
43
  try {
38
- here = (await locate(process.cwd(), options.project)).project
44
+ here = (await locate(currentDir(), options.project)).project
45
+ }
46
+ catch (error) {
47
+ // A project named on the command line that does not load is the user's to hear of
48
+ if (options.project !== undefined)
49
+ throw error
39
50
  }
40
- catch {}
41
51
 
42
52
  const everywhere = options.all === true || (!here && !options.json)
43
53
 
@@ -56,10 +66,10 @@ async function dirtyCount(dir: string, repos: string[]): Promise<number> {
56
66
  return changedFiles(statuses.filter(status => status.ok).map(status => status.out))
57
67
  }
58
68
 
59
- async function checkoutsOf(project: Project, running: Set<string>): Promise<Checkout[]> {
69
+ async function checkoutsOf(project: Project, running: Set<string>, jobs: Jobs, states: Map<string, JobState>): Promise<Checkout[]> {
60
70
  const branchDir = project.repos[0] ?? '.'
61
71
  const mainHost = project.routes.find(route => !route.host.startsWith('*.'))?.host
62
- const main = { id: basename(project.root), task: 'main', dir: project.root, url: mainHost !== undefined ? `https://${mainHost}` : '' }
72
+ const main = { id: stackName(project), task: 'main', dir: project.root, url: mainHost !== undefined ? `https://${mainHost}` : '' }
63
73
  const worktrees = listTasks(project).map((task) => {
64
74
  const worktree = worktreeOf(project, task)
65
75
 
@@ -76,23 +86,26 @@ async function checkoutsOf(project: Project, running: Set<string>): Promise<Chec
76
86
  dirty: await dirtyCount(dir, project.repos),
77
87
  unbranched: task === 'main' ? 0 : await unreachableCount(dir, project.repos),
78
88
  session: sessionOf(task === 'main' ? basename(dir) : id),
89
+ job: jobs.summary(states.get(slugOf(`${project.name}/${task}`)) ?? {}),
79
90
  })))
80
91
  }
81
92
 
82
- // One row per checkout, `*` marking a stack that is up; as JSON, `{ project, checkouts }`, project being the one the directory is in, null outside every one.
93
+ // One row per checkout under a header, `*` marking a stack that is up; as JSON, `{ project, checkouts }`, project being the one the directory is in, null outside every one.
83
94
  export async function listWorktrees(options: ListOptions): Promise<void> {
84
- const [running, { here, projects }] = await Promise.all([runningProjects(), projectsToList(options)])
85
- const checkouts = (await Promise.all(projects.map(async project => checkoutsOf(project, running)))).flat()
95
+ const [running, { here, projects }, jobs] = await Promise.all([runningProjects(), projectsToList(options), wtJobs()])
96
+ const states = jobs.states()
97
+ const checkouts = (await Promise.all(projects.map(async project => checkoutsOf(project, running, jobs, states)))).flat()
86
98
 
87
99
  if (options.json) {
88
- console.log(JSON.stringify({ project: here?.name ?? null, checkouts }))
100
+ printJson({ project: here?.name ?? null, checkouts })
89
101
 
90
102
  return
91
103
  }
92
104
 
93
- const rows = checkouts.map(checkout => [checkout.running ? '*' : ' ', checkout.project, checkout.task, checkout.branch, checkout.url, [checkout.dirty ? `${checkout.dirty} changed` : '', checkout.unbranched ? `${checkout.unbranched} on no branch` : ''].filter(Boolean).join(', ')])
94
- const widths = rows[0]?.map((_, column) => Math.max(...rows.map(row => row[column]!.length))) ?? []
105
+ if (!checkouts.length)
106
+ return
107
+
108
+ const rows = checkouts.map(checkout => [checkout.running ? '*' : '', checkout.project, checkout.task, checkout.branch, checkout.url, checkout.job, [checkout.dirty ? `${checkout.dirty} changed` : '', checkout.unbranched ? `${checkout.unbranched} on no branch` : ''].filter(Boolean).join(', ')])
95
109
 
96
- for (const row of rows)
97
- console.log(row.map((cell, column) => cell.padEnd(widths[column]!)).join(' ').trimEnd())
110
+ console.log(table([['up', 'project', 'task', 'branch', 'url', 'job', 'changes'], ...rows], { header: true }))
98
111
  }
package/src/print.ts ADDED
@@ -0,0 +1,76 @@
1
+ import type { GlobalOptions } from './commands'
2
+ import type { Jobs } from './jobs'
3
+ import type { Worktree } from './project'
4
+ import { existsSync } from 'node:fs'
5
+ import { openUrl, warn } from '@kaynooo/cli-kit'
6
+ import { slugOf } from './jobs'
7
+ import { assertWorktreeExists, currentDir, listTasks, locate, locateWorktree, worktreeOf, WtError } from './project'
8
+ import { urlsOf } from './routes'
9
+
10
+ /** Prints the log of the worktree's last --bg job: a job run in a terminal printed there and kept none, which a note says when it came after. */
11
+ export async function printJobLog(worktree: Worktree, jobs: Jobs): Promise<void> {
12
+ const ref = `${worktree.project.name}/${worktree.task}`
13
+ const slug = slugOf(ref)
14
+ const { log } = jobs.paths(slug)
15
+
16
+ if (!existsSync(log))
17
+ throw new WtError(`no job of ${ref} ran with --bg, which alone keeps a log`)
18
+
19
+ const state = jobs.states().get(slug) ?? {}
20
+
21
+ if (state.running?.log === '')
22
+ warn(`${ref} is ${jobs.summary(state)} in a terminal; this log is of the last --bg one`)
23
+ else if (state.running === undefined && state.last?.log === '')
24
+ warn(`the last job (${jobs.summary(state)}) ran in a terminal; this log is of the last --bg one`)
25
+
26
+ await Bun.write(Bun.stdout, Bun.file(log))
27
+ }
28
+
29
+ export async function printUrls(task: string | undefined, options: GlobalOptions): Promise<void> {
30
+ for (const url of urlsOf(await locateWorktree(currentDir(), task, options.project)))
31
+ console.log(url)
32
+ }
33
+
34
+ export async function printPath(task: string | undefined, options: GlobalOptions): Promise<void> {
35
+ const { project } = await locate(currentDir(), options.project)
36
+
37
+ if (task === undefined || task === 'main')
38
+ return console.log(project.root)
39
+
40
+ const worktree = worktreeOf(project, task)
41
+
42
+ assertWorktreeExists(worktree)
43
+ console.log(worktree.dir)
44
+ }
45
+
46
+ /** Opens a worktree's main URL in the browser, main's when the task is `main` or the current directory is main's checkout. */
47
+ export async function openTask(task: string | undefined, options: GlobalOptions): Promise<void> {
48
+ const here = await locate(currentDir(), options.project)
49
+ const name = task ?? here.task
50
+ let url: string | undefined
51
+
52
+ if (name === 'main') {
53
+ const host = here.project.routes.find(route => !route.host.startsWith('*.'))?.host
54
+
55
+ url = host === undefined ? undefined : `https://${host}`
56
+ }
57
+ else {
58
+ const worktree = worktreeOf(here.project, name)
59
+
60
+ assertWorktreeExists(worktree)
61
+ url = urlsOf(worktree)[0]
62
+ }
63
+
64
+ if (url === undefined)
65
+ throw new WtError(`${here.project.name} routes no host, so ${name} has no URL to open`)
66
+
67
+ if (!openUrl(url))
68
+ throw new WtError(`no browser could be started for ${url}`)
69
+
70
+ console.log(`wt: opened ${url}`)
71
+ }
72
+
73
+ export async function printTasks(options: GlobalOptions): Promise<void> {
74
+ for (const task of listTasks((await locate(currentDir(), options.project)).project))
75
+ console.log(task)
76
+ }