@kaynooo/cli-docker 0.2.0 → 0.4.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/src/sf.ts ADDED
@@ -0,0 +1,368 @@
1
+ import type { Arg, Row } from '@kaynooo/cli-kit/fzf'
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
3
+ import { homedir } from 'node:os'
4
+ import { dirname, join, resolve } from 'node:path'
5
+ import process from 'node:process'
6
+ import { fail, paint, parse } from '@kaynooo/cli-kit'
7
+ import { byRecency, emit, fzf, list, record, runs, table } from '@kaynooo/cli-kit/fzf'
8
+ import { input } from '@kaynooo/cli-kit/prompt'
9
+ import { children, from, nearestStack, services, up } from './stack'
10
+
11
+ interface Argument {
12
+ name: string
13
+ is_required: boolean
14
+ is_array: boolean
15
+ description: string
16
+ }
17
+
18
+ interface Option {
19
+ name: string
20
+ shortcut: string
21
+ accept_value: boolean
22
+ description: string
23
+ }
24
+
25
+ /** A command as `bin/console list --format=json` describes it, a definition without arguments or options holding an empty array instead of an object. */
26
+ export interface Command {
27
+ name: string
28
+ description: string
29
+ help: string
30
+ usage: string[]
31
+ hidden: boolean
32
+ definition: { arguments: Record<string, Argument> | [], options: Record<string, Option> | [] }
33
+ }
34
+
35
+ /** One console, and how its commands are run and listed. */
36
+ export interface Console {
37
+ dir: string
38
+ run: string[]
39
+ list: { argv: string[], cwd: string, env: Record<string, string | undefined> }
40
+ }
41
+
42
+ export interface Entry {
43
+ app: Console
44
+ command: Command
45
+ }
46
+
47
+ const usage = `sf [command] [args...]
48
+ sf -
49
+
50
+ Picks a Symfony console command with fzf and runs it, asking for each required argument it needs. The commands last run come first, per folder, and the picker opens on the list cached from the last run while the console answers.
51
+ The console is the nearest bin/console up to the repository root, then those of the child folders (keyed \`api/cache:clear\`). It runs in the php service of the nearest compose stack when there is one, else with the local php; the container's working directory is taken to be the app.
52
+ \`sf -\` runs the last command again with the arguments it ran with, \`sf <command> [args...]\` runs without the picker: a name the list does not hold goes to the console as is, which resolves \`c:c\` to \`cache:clear\` itself. Without fzf or a terminal it lists the commands instead.
53
+ The hidden flags --list, --names, --rows, --show, --record and --emit are for term, tmux and the shell completions.
54
+
55
+ Exits with the code of the console, 1 when there is no bin/console here.`
56
+
57
+ /** Fzf paints its rows and previews itself, so these keep their colors whatever stream they are written to. */
58
+ const colors = paint({ isTTY: true })
59
+ const MARKUP = /<(info|comment|question|error)>(.*?)<\/\1>/gs
60
+ const TAGS = { info: 'green', comment: 'yellow', question: 'cyan', error: 'red' } as const
61
+ const LINKS = /<\/?href[^>]*>/g
62
+
63
+ /** Symfony's console markup, in the colors the console itself gives it. */
64
+ export function marked(text: string): string {
65
+ return text.replace(MARKUP, (_, tag: keyof typeof TAGS, inner: string) => colors[TAGS[tag]](inner)).replace(LINKS, '')
66
+ }
67
+
68
+ export function argumentsOf(command: Command): Argument[] {
69
+ return Array.isArray(command.definition.arguments) ? [] : Object.values(command.definition.arguments)
70
+ }
71
+
72
+ function optionsOf(command: Command): Option[] {
73
+ return Array.isArray(command.definition.options) ? [] : Object.values(command.definition.options)
74
+ }
75
+
76
+ /** The php service by name, `php` itself before `booki-php` or `dorad_php`. */
77
+ export function phpService(names: string[]): string | undefined {
78
+ return names.find(name => name === 'php') ?? names.find(name => name.includes('php'))
79
+ }
80
+
81
+ async function consoleAt(dir: string): Promise<Console> {
82
+ const stack = nearestStack(dir)
83
+ const php = stack === undefined ? undefined : phpService((await services(stack)).map(service => service.name))
84
+
85
+ if (stack !== undefined && php !== undefined)
86
+ return { dir, run: [...stack.run, 'exec', php, 'bin/console'], list: { ...stack.list, argv: [...stack.list.argv, 'exec', '-T', php, 'bin/console'] } }
87
+
88
+ return { dir, run: from(dir, ['php', 'bin/console']), list: { argv: ['php', 'bin/console'], cwd: resolve(dir), env: process.env } }
89
+ }
90
+
91
+ /** The console of this folder or its nearest parent, then those of the child folders. */
92
+ async function consoles(): Promise<Console[]> {
93
+ const here = up('.').find(dir => existsSync(join(dir, 'bin/console')))
94
+ const dirs = [...(here === undefined ? [] : [here]), ...children().filter(dir => existsSync(join(dir, 'bin/console')))]
95
+
96
+ return Promise.all([...new Set(dirs)].map(consoleAt))
97
+ }
98
+
99
+ function cached(dir: string): string {
100
+ return join(process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache'), 'sf', `${resolve(dir).replaceAll('/', '%')}.json`)
101
+ }
102
+
103
+ function fromCache(dir: string): Command[] | undefined {
104
+ try {
105
+ return existsSync(cached(dir)) ? JSON.parse(readFileSync(cached(dir), 'utf-8')) as Command[] : undefined
106
+ }
107
+ catch {
108
+ return undefined
109
+ }
110
+ }
111
+
112
+ async function live(app: Console): Promise<Command[]> {
113
+ const proc = Bun.spawn([...app.list.argv, 'list', '--format=json'], { cwd: app.list.cwd, env: app.list.env, stdout: 'pipe', stderr: 'pipe' })
114
+ const text = await new Response(proc.stdout).text()
115
+
116
+ if ((await proc.exited) !== 0)
117
+ return fromCache(app.dir) ?? []
118
+
119
+ const commands = (JSON.parse(text) as { commands: Command[] }).commands.filter(command => !command.hidden)
120
+
121
+ mkdirSync(dirname(cached(app.dir)), { recursive: true })
122
+ writeFileSync(cached(app.dir), JSON.stringify(commands))
123
+
124
+ return commands
125
+ }
126
+
127
+ async function entries(fresh: boolean): Promise<Entry[]> {
128
+ const found = await consoles()
129
+ const lists = await Promise.all(found.map(async app => (fresh ? live(app) : fromCache(app.dir) ?? live(app))))
130
+
131
+ return found.flatMap((app, index) => lists[index]!.map(command => ({ app, command })))
132
+ }
133
+
134
+ /** What names a command: `cache:clear` in this folder's console, `api/cache:clear` in a child's. */
135
+ export function key(entry: Entry): string {
136
+ return entry.app.dir === '.' ? entry.command.name : `${entry.app.dir}/${entry.command.name}`
137
+ }
138
+
139
+ /** The namespace dimmed, the command standing out: `cache:` in `cache:clear`. */
140
+ function named(name: string): string {
141
+ const colon = name.lastIndexOf(':')
142
+
143
+ return colon === -1 ? name : `${colors.dim(name.slice(0, colon + 1))}${name.slice(colon + 1)}`
144
+ }
145
+
146
+ /** Required arguments read as `<name>`, the others as `[name]`, a list as `name...`. */
147
+ export function signature(command: Command): string {
148
+ return argumentsOf(command)
149
+ .map(argument => `${argument.is_required ? '<' : '['}${argument.name}${argument.is_array ? '...' : ''}${argument.is_required ? '>' : ']'}`)
150
+ .join(' ')
151
+ }
152
+
153
+ function rows(found: Entry[]): Row[] {
154
+ return byRecency(found, runs('sf'), key).map(entry => ({
155
+ hidden: [entry.app.dir, entry.command.name],
156
+ cells: [entry.app.dir === '.' ? named(entry.command.name) : `${colors.dim(`${entry.app.dir}/`)}${named(entry.command.name)}`, colors.cyan(signature(entry.command)), colors.dim(entry.command.description)],
157
+ }))
158
+ }
159
+
160
+ /** From the cache alone, the preview being called at every move. */
161
+ function preview(dir: string, name: string): void {
162
+ const command = (fromCache(dir) ?? []).find(candidate => candidate.name === name)
163
+
164
+ if (!command)
165
+ return
166
+
167
+ // Laid out as `bin/console help` has it.
168
+ const lines = [
169
+ colors.bold(command.description),
170
+ '',
171
+ colors.yellow('Usage:'),
172
+ ...command.usage.map(line => ` ${line}`),
173
+ ...(argumentsOf(command).length ? ['', colors.yellow('Arguments:'), ...argumentsOf(command).map(argument => ` ${colors.green(argument.name.padEnd(20))} ${argument.description}`)] : []),
174
+ ...(optionsOf(command).length ? ['', colors.yellow('Options:'), ...optionsOf(command).map(option => ` ${colors.green(`--${option.name}${option.accept_value ? '=' : ''}`.padEnd(20))} ${option.description}`)] : []),
175
+ ...(command.help ? ['', colors.yellow('Help:'), command.help] : []),
176
+ ]
177
+
178
+ console.log(marked(lines.join('\n')))
179
+ }
180
+
181
+ /** The arguments given, then a prompt for each required one past them. */
182
+ export function commandFor(entry: Entry, given: string[]): Arg[] {
183
+ const prompts = argumentsOf(entry.command).filter(argument => argument.is_required).slice(given.length)
184
+
185
+ return [...entry.app.run, entry.command.name, ...given.map(value => ({ given: value })), ...prompts.map(argument => ({ ask: argument.name }))]
186
+ }
187
+
188
+ /** The words of a command with every prompt answered, and the arguments a run is remembered with; undefined once a prompt is cancelled. */
189
+ export async function answered(command: Arg[], ask: (name: string) => Promise<string | undefined>): Promise<{ argv: string[], given: string[] } | undefined> {
190
+ const argv: string[] = []
191
+ const given: string[] = []
192
+
193
+ for (const word of command) {
194
+ if (typeof word === 'string') {
195
+ argv.push(word)
196
+
197
+ continue
198
+ }
199
+
200
+ const value = 'given' in word ? word.given : await ask(word.ask)
201
+
202
+ if (value === undefined)
203
+ return undefined
204
+
205
+ argv.push(value)
206
+ given.push(value)
207
+ }
208
+
209
+ return { argv, given }
210
+ }
211
+
212
+ function interactive(): boolean {
213
+ return process.stdin.isTTY && process.stderr.isTTY
214
+ }
215
+
216
+ /** What `--emit` prints for tmux, or, standalone, the command run once its prompts are answered. */
217
+ async function execute(emitting: boolean, typed: string, recorded: string, command: Arg[]): Promise<number> {
218
+ if (emitting) {
219
+ emit('run', typed, recorded, command)
220
+
221
+ return 0
222
+ }
223
+
224
+ if (!interactive() && command.some(word => typeof word === 'object' && 'ask' in word))
225
+ fail('a required argument is missing and there is no terminal to ask for it', 1)
226
+
227
+ const done = await answered(command, async name => input(`${name}:`))
228
+
229
+ if (done === undefined)
230
+ return 1
231
+
232
+ if (recorded !== '')
233
+ record('sf', { id: recorded, args: done.given })
234
+
235
+ return Bun.spawn(done.argv, { stdio: ['inherit', 'inherit', 'inherit'] }).exited
236
+ }
237
+
238
+ function listing(found: Entry[]): string {
239
+ const sorted = byRecency(found, runs('sf'), key)
240
+ const labels = sorted.map(entry => [key(entry), signature(entry.command)].filter(Boolean).join(' '))
241
+ const width = Math.max(...labels.map(label => label.length))
242
+
243
+ return sorted.map((entry, index) => `${labels[index]!.padEnd(width)} ${entry.command.description}`.trimEnd()).join('\n')
244
+ }
245
+
246
+ /** The hidden flags term, tmux and the shell completions call, each printing and nothing more. */
247
+ async function hidden(flag: string, rest: string[]): Promise<number | undefined> {
248
+ if (flag === '--show') {
249
+ preview(rest[0] ?? '.', rest[1] ?? '')
250
+
251
+ return 0
252
+ }
253
+
254
+ if (flag === '--record') {
255
+ record('sf', { id: rest[0] ?? '', args: rest.slice(1) })
256
+
257
+ return 0
258
+ }
259
+
260
+ // Called back by fzf once the picker is open on the cached list.
261
+ if (flag === '--rows') {
262
+ console.log(table(rows(await entries(true))).join('\n'))
263
+
264
+ return 0
265
+ }
266
+
267
+ if (flag !== '--list' && flag !== '--names')
268
+ return undefined
269
+
270
+ const refreshed = flag === '--list' && (await consoles()).some(found => fromCache(found.dir) !== undefined)
271
+ const found = await entries(false)
272
+
273
+ if (flag === '--names') {
274
+ // With the description as the one fish shows beside each name.
275
+ console.log(found.map(entry => `${key(entry)}\t${entry.command.description}`).join('\n'))
276
+
277
+ return 0
278
+ }
279
+
280
+ // From the cache, which a list run in the background brings up to date for the next time, as fzf's reload does.
281
+ if (refreshed)
282
+ Bun.spawn([process.execPath, process.argv[1]!, '--rows'], { stdio: ['ignore', 'ignore', 'ignore'] }).unref()
283
+
284
+ list(byRecency(found, runs('sf'), key).map(entry => ({
285
+ label: [key(entry), signature(entry.command)].filter(Boolean).join(' '),
286
+ hint: entry.command.description,
287
+ typed: key(entry),
288
+ preview: ['--show', entry.app.dir, entry.command.name],
289
+ })))
290
+
291
+ return 0
292
+ }
293
+
294
+ export async function sf(args: string[]): Promise<number> {
295
+ const [flag = ''] = args
296
+ const flagged = await hidden(flag, args.slice(1))
297
+
298
+ if (flagged !== undefined)
299
+ return flagged
300
+
301
+ // The protocol the tmux picker reads instead of running the command: its mode, the words typed back, and the command's words.
302
+ const emitting = flag === '--emit'
303
+ const words = emitting ? args.slice(1) : args
304
+ const last = words[0] === '-'
305
+ const parsed = parse(last ? [] : words, usage, {}, {
306
+ positionals: ['[command]'],
307
+ trailing: true,
308
+ replaces: 'bin/console typed in the php container, with the command names and arguments looked up by hand',
309
+ examples: ['sf', ['sf cache:clear', 'run it without the picker'], ['sf c:c --env=prod', 'the console resolves abbreviations itself'], ['sf -', 'the last command again, with its arguments']],
310
+ })
311
+ const [command] = parsed.positionals
312
+ const given = last ? words.slice(1) : parsed.rest ?? []
313
+ const refreshed = command === undefined && !last && (await consoles()).some(found => fromCache(found.dir) !== undefined)
314
+ const found = await entries(false)
315
+
316
+ if (last) {
317
+ const previous = runs('sf')[0]
318
+ const entry = previous && found.find(candidate => key(candidate) === previous.id)
319
+
320
+ if (entry === undefined)
321
+ fail(previous ? `${previous.id} is gone` : 'nothing run here yet', 1)
322
+
323
+ return execute(emitting, key(entry), key(entry), commandFor(entry, [...previous!.args, ...given]))
324
+ }
325
+
326
+ if (command !== undefined) {
327
+ const entry = found.find(candidate => key(candidate) === command) ?? found.find(candidate => candidate.command.name === command)
328
+
329
+ if (entry !== undefined)
330
+ return execute(emitting, key(entry), key(entry), commandFor(entry, given))
331
+
332
+ // Left to the console, which knows its abbreviations and suggests the nearest command itself.
333
+ const [first] = await consoles()
334
+
335
+ if (first === undefined)
336
+ fail('no bin/console here', 1)
337
+
338
+ return execute(emitting, command, '', [...first.run, command, ...given.map(value => ({ given: value }))])
339
+ }
340
+
341
+ if (found.length === 0)
342
+ fail('no bin/console here, or it listed no command', 1)
343
+
344
+ if (!interactive() || Bun.which('fzf') === null) {
345
+ if (emitting)
346
+ fail('the picker needs a terminal and fzf', 1)
347
+
348
+ if (interactive())
349
+ console.error('fzf is not installed, listing the commands instead')
350
+
351
+ console.log(listing(found))
352
+
353
+ return 0
354
+ }
355
+
356
+ const self = `${process.execPath} ${process.argv[1]}`
357
+ const picked = fzf(rows(found), {
358
+ prompt: 'sf> ',
359
+ searched: 1,
360
+ preview: `${self} --show {1} {2}`,
361
+ // Once the cached list is in, and only once, the reload firing load again.
362
+ bind: refreshed ? [`load:unbind(load)+reload-sync(${self} --rows)`] : [],
363
+ })
364
+ // Read again, the reload having maybe brought a command the cached list did not hold.
365
+ const entry = picked && (await entries(false)).find(candidate => candidate.app.dir === picked.hidden[0] && candidate.command.name === picked.hidden[1])
366
+
367
+ return entry === undefined ? 1 : execute(emitting, key(entry), key(entry), commandFor(entry, []))
368
+ }
package/src/stack.ts CHANGED
@@ -42,6 +42,9 @@ export interface Container {
42
42
  Service: string
43
43
  State: string
44
44
  Status: string
45
+ /** Empty for a container with no healthcheck. */
46
+ Health?: string
47
+ ExitCode?: number
45
48
  }
46
49
 
47
50
  const LABEL_FORMAT = ['project', 'project.config_files', 'project.environment_file', 'project.working_dir'].map(label => `{{.Label "com.docker.compose.${label}"}}`).join('\t')
@@ -52,12 +55,12 @@ const SKIPPED = new Set(['node_modules', 'vendor', 'dist', 'build', 'target', 'v
52
55
  export const ACTIONS: Action[] = ['shell', 'logs', 'restart', 'up', 'stop', 'build']
53
56
 
54
57
  /** The command behind `env -C` when it runs from another folder than this one. */
55
- function from(dir: string, command: string[]): string[] {
58
+ export function from(dir: string, command: string[]): string[] {
56
59
  return dir === '.' ? command : ['env', '-C', dir, ...command]
57
60
  }
58
61
 
59
62
  /** The direct child folders, hidden and built ones aside. */
60
- function children(dir = '.'): string[] {
63
+ export function children(dir = '.'): string[] {
61
64
  return readdirSync(dir, { withFileTypes: true })
62
65
  .filter(child => child.isDirectory() && !child.name.startsWith('.') && !SKIPPED.has(child.name))
63
66
  .map(child => child.name)
@@ -65,7 +68,7 @@ function children(dir = '.'): string[] {
65
68
  }
66
69
 
67
70
  /** The folder and its parents, relative to it, up to the repository root. */
68
- function up(dir: string): string[] {
71
+ export function up(dir: string): string[] {
69
72
  const dirs: string[] = []
70
73
 
71
74
  for (let current = dir; ; current = join(current, '..')) {
@@ -158,10 +161,21 @@ export async function recordedNearby(): Promise<Labels[]> {
158
161
  return (await labels()).filter(stack => dirs.has(stack.workdir))
159
162
  }
160
163
 
161
- async function output(stack: Stack, args: string[]): Promise<string> {
164
+ /** What compose printed, and its stderr when it exited non-zero. */
165
+ export async function attempt(stack: Stack, args: string[]): Promise<{ text: string, error: string | undefined }> {
162
166
  const proc = Bun.spawn([...stack.list.argv, ...args], { cwd: stack.list.cwd, env: stack.list.env, stdout: 'pipe', stderr: 'pipe' })
167
+ const [text, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited])
168
+
169
+ if (code === 0)
170
+ return { text, error: undefined }
171
+
172
+ const last = stderr.trim().split('\n').at(-1) ?? ''
163
173
 
164
- return (await proc.exited) === 0 ? new Response(proc.stdout).text() : ''
174
+ return { text: '', error: last === '' ? `exit ${code}` : last }
175
+ }
176
+
177
+ async function output(stack: Stack, args: string[]): Promise<string> {
178
+ return (await attempt(stack, args)).text
165
179
  }
166
180
 
167
181
  /** Compose prints one container per line, where older versions printed a JSON array. */
package/src/history.ts DELETED
@@ -1,48 +0,0 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
- import { homedir } from 'node:os'
3
- import { dirname, join } from 'node:path'
4
- import process from 'node:process'
5
-
6
- export interface Run {
7
- id: string
8
- args: string[]
9
- }
10
-
11
- const REMEMBERED = 20
12
-
13
- function historyFile(): string {
14
- return join(process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache'), 'dx', 'history.json')
15
- }
16
-
17
- // Keyed by folder, a broken or missing file reading as nothing run yet.
18
- function history(): Record<string, Run[]> {
19
- try {
20
- const file = historyFile()
21
-
22
- return existsSync(file) ? JSON.parse(readFileSync(file, 'utf-8')) as Record<string, Run[]> : {}
23
- }
24
- catch {
25
- return {}
26
- }
27
- }
28
-
29
- export function runs(): Run[] {
30
- return history()[process.cwd()] ?? []
31
- }
32
-
33
- export function record(run: Run): void {
34
- const all = history()
35
- const file = historyFile()
36
-
37
- all[process.cwd()] = [run, ...(all[process.cwd()] ?? []).filter(earlier => earlier.id !== run.id)].slice(0, REMEMBERED)
38
- mkdirSync(dirname(file), { recursive: true })
39
- writeFileSync(file, JSON.stringify(all))
40
- }
41
-
42
- // The ones run last come first, most recent at the top, the rest keeping their order.
43
- export function byRecency<T>(items: T[], previous: Run[], idOf: (item: T) => string): T[] {
44
- const rank = new Map(previous.map((run, index) => [run.id, index]))
45
- const recent = items.filter(item => rank.has(idOf(item))).sort((a, b) => rank.get(idOf(a))! - rank.get(idOf(b))!)
46
-
47
- return [...recent, ...items.filter(item => !rank.has(idOf(item)))]
48
- }