@sixb/cli 0.1.13 → 0.1.15

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.
@@ -0,0 +1,403 @@
1
+ import { mkdir } from "node:fs/promises"
2
+ import { dirname, join, relative } from "node:path"
3
+ import { writeJson } from "@sixb/cli-core"
4
+ import type {
5
+ DeployAccessKey,
6
+ DeployCheck,
7
+ DeployConfig,
8
+ DeployControlAction,
9
+ DeployEvent,
10
+ DeployRelease,
11
+ } from "@sixb/core/deploy"
12
+ import { loadDeployConfig } from "../lib/deploy-config"
13
+ import { buildDeployRelease } from "../lib/deploy-release"
14
+ import {
15
+ deployer,
16
+ packSource,
17
+ projectPathOf,
18
+ repoRootOf,
19
+ resolveBunVersion,
20
+ } from "../lib/deploy-source"
21
+ import { SixbCliError } from "../lib/errors"
22
+ import {
23
+ bunVersionFile,
24
+ CI_ENVIRONMENT,
25
+ currentRepo,
26
+ ensureEnvironment,
27
+ hasSecret,
28
+ isPrivate,
29
+ readSubmodules,
30
+ renderWorkflow,
31
+ SUBMODULE_TOKEN_SECRET,
32
+ secretName,
33
+ setSecret,
34
+ workflowPath,
35
+ } from "../lib/github-ci"
36
+ import {
37
+ DeployAccessView,
38
+ DeployChecksView,
39
+ DeployCiView,
40
+ DeployCompleteView,
41
+ type DeployProgressState,
42
+ DeployProgressView,
43
+ DeployReleaseView,
44
+ DeployStatusView,
45
+ renderCliError,
46
+ renderPersistent,
47
+ renderStatic,
48
+ } from "../ui"
49
+
50
+ export interface DeployOptions {
51
+ readonly dryRun?: boolean
52
+ readonly json?: boolean
53
+ readonly ref?: string
54
+ readonly cwd?: string
55
+ }
56
+
57
+ export async function runDeploy(options: DeployOptions = {}): Promise<void> {
58
+ const cwd = options.cwd ?? process.cwd()
59
+ const { path, config } = await loadDeployConfig(cwd)
60
+
61
+ if (options.dryRun) {
62
+ const release = buildDeployRelease(config, { bunVersion: await resolveBunVersion(cwd) })
63
+ if (options.json) return writeJson(release)
64
+ await renderStatic(
65
+ <DeployReleaseView release={release} configPath={relative(cwd, path) || path} />
66
+ )
67
+ return
68
+ }
69
+
70
+ const source = await packSource(cwd, options.ref)
71
+ const release = buildDeployRelease(config, { bunVersion: await resolveBunVersion(cwd, source) })
72
+
73
+ // Stop before uploading anything when the target already says the deploy cannot work.
74
+ const checks = await config.target.check(release, {
75
+ name: config.name,
76
+ projectPath: source.projectPath,
77
+ })
78
+ if (checks.some(blocksDeploy)) {
79
+ await renderStatic(
80
+ <DeployChecksView name={config.name} location={location(config)} checks={checks} />
81
+ )
82
+ process.exit(1)
83
+ }
84
+ const progress = createProgress(release, {
85
+ commit: source.commit,
86
+ ref: source.ref,
87
+ dirty: source.dirty,
88
+ })
89
+ try {
90
+ await config.target.deploy(release, source, {
91
+ name: config.name,
92
+ deployedBy: await deployer(cwd),
93
+ report: progress.report,
94
+ })
95
+ } catch (error) {
96
+ progress.fail()
97
+ const failed = progress.state.labels[progress.state.current ?? -1]
98
+ await renderCliError(error, {
99
+ title: failed ? `Deploy failed at "${failed}"` : "Deploy failed",
100
+ details: progress.state.output,
101
+ })
102
+ process.exit(1)
103
+ }
104
+ progress.finish()
105
+ await renderStatic(
106
+ <DeployCompleteView release={release} commit={source.commit} ref={source.ref} />
107
+ )
108
+ }
109
+
110
+ export async function runDeployCheck(options: { readonly json?: boolean; readonly cwd?: string }) {
111
+ const cwd = options.cwd ?? process.cwd()
112
+ const { config } = await loadDeployConfig(cwd)
113
+ const release = buildDeployRelease(config, { bunVersion: await resolveBunVersion(cwd) })
114
+ const checks = await config.target.check(release, {
115
+ name: config.name,
116
+ projectPath: await projectPathOf(cwd),
117
+ })
118
+ if (options.json) writeJson(checks)
119
+ else
120
+ await renderStatic(
121
+ <DeployChecksView name={config.name} location={location(config)} checks={checks} />
122
+ )
123
+ if (checks.some(blocksDeploy)) process.exitCode = 1
124
+ }
125
+
126
+ export async function runDeploySetup(options: {
127
+ readonly admin?: string
128
+ readonly key?: string
129
+ readonly cwd?: string
130
+ }) {
131
+ const cwd = options.cwd ?? process.cwd()
132
+ const { config } = await loadDeployConfig(cwd)
133
+ const release = buildDeployRelease(config, { bunVersion: await resolveBunVersion(cwd) })
134
+ const context = { name: config.name, projectPath: await projectPathOf(cwd) }
135
+
136
+ if (!config.target.setup) {
137
+ console.log(`A ${config.target.kind} target needs no setup.`)
138
+ } else {
139
+ await config.target.setup(release, {
140
+ ...context,
141
+ ...(options.admin ? { admin: options.admin } : {}),
142
+ ...(options.key ? { key: options.key } : {}),
143
+ write: (line) => console.log(line),
144
+ })
145
+ }
146
+ const checks = await config.target.check(release, context)
147
+ await renderStatic(
148
+ <DeployChecksView name={config.name} location={location(config)} checks={checks} />
149
+ )
150
+ }
151
+
152
+ export async function runDeployAccess(options: {
153
+ readonly action: "list" | "add" | "remove"
154
+ readonly value?: string
155
+ readonly json?: boolean
156
+ readonly cwd?: string
157
+ }) {
158
+ const { config } = await loadDeployConfig(options.cwd)
159
+ const access = config.target.access
160
+ if (!access) {
161
+ throw new SixbCliError(`[SixbDeploy] A ${config.target.kind} target has no keys to manage.`)
162
+ }
163
+ const context = { name: config.name }
164
+
165
+ if (options.action === "list") {
166
+ const keys = await access.list(context)
167
+ if (options.json) return writeJson(keys)
168
+ return renderStatic(<DeployAccessView title={`Keys for ${location(config)}`} keys={keys} />)
169
+ }
170
+ if (options.action === "add") {
171
+ const added: DeployAccessKey[] = []
172
+ for (const key of await publicKeys(options.value ?? ""))
173
+ added.push(await access.add(key, context))
174
+ return renderStatic(<DeployAccessView title="Authorized" keys={added} />)
175
+ }
176
+ const removed = await access.remove(options.value ?? "", context)
177
+ return renderStatic(<DeployAccessView title="Revoked" keys={removed} />)
178
+ }
179
+
180
+ /**
181
+ * Sets up deploys from GitHub Actions: a key for the job, authorized on the target and stored as
182
+ * secrets of the repository's `production` environment, and the workflow that uses it. Running it
183
+ * again rotates the key: the new one is stored before the old one is revoked.
184
+ */
185
+ export async function runDeployCi(options: { readonly branch?: string; readonly cwd?: string }) {
186
+ const cwd = options.cwd ?? process.cwd()
187
+ const { config } = await loadDeployConfig(cwd)
188
+ const ci = config.target.ci
189
+ if (!ci) {
190
+ throw new SixbCliError(`[SixbDeploy] A ${config.target.kind} target cannot deploy from CI.`)
191
+ }
192
+
193
+ const repo = await currentRepo(cwd)
194
+ const projectPath = await projectPathOf(cwd)
195
+ const repoRoot = await repoRootOf(cwd)
196
+ const submodules = await readSubmodules(repoRoot, repo)
197
+ const privateSubmodules = []
198
+ for (const submodule of submodules) {
199
+ if (!submodule.repo || (await isPrivate(submodule.repo))) privateSubmodules.push(submodule)
200
+ }
201
+
202
+ const credential = await ci.create(`github:${repo.name}`, { name: config.name })
203
+ const secrets = Object.fromEntries(
204
+ Object.keys(credential.secrets).map((variable) => [variable, secretName(config.name, variable)])
205
+ )
206
+ try {
207
+ await ensureEnvironment(repo)
208
+ for (const [variable, value] of Object.entries(credential.secrets)) {
209
+ await setSecret(repo, secrets[variable] ?? variable, value)
210
+ }
211
+ } catch (error) {
212
+ // CI never got the new key, so it must not stay authorized.
213
+ await credential.revoke()
214
+ throw error
215
+ }
216
+ const retired = await credential.retireOthers()
217
+
218
+ const branch = options.branch ?? repo.defaultBranch
219
+ const workflow = renderWorkflow({
220
+ name: config.name,
221
+ branch,
222
+ projectPath,
223
+ bunVersionFile: await bunVersionFile(join(repoRoot, projectPath), repoRoot),
224
+ secrets,
225
+ install: credential.install,
226
+ submodules:
227
+ privateSubmodules.length > 0 ? "private" : submodules.length > 0 ? "public" : "none",
228
+ })
229
+ const path = workflowPath(config.name)
230
+ const file = Bun.file(join(repoRoot, path))
231
+ // A workflow already there may have been edited, and rotating the key must not undo that.
232
+ const existing = (await file.exists()) ? await file.text() : null
233
+ if (existing === null) {
234
+ await mkdir(dirname(join(repoRoot, path)), { recursive: true })
235
+ await Bun.write(file, workflow)
236
+ }
237
+
238
+ await renderStatic(
239
+ <DeployCiView
240
+ name={config.name}
241
+ repo={repo.name}
242
+ environment={CI_ENVIRONMENT}
243
+ branch={branch}
244
+ credential={credential.description}
245
+ secrets={Object.values(secrets)}
246
+ retired={retired}
247
+ workflow={{
248
+ path,
249
+ state: existing === null ? "written" : existing === workflow ? "unchanged" : "kept",
250
+ }}
251
+ token={
252
+ privateSubmodules.length > 0 && !(await hasSecret(repo, SUBMODULE_TOKEN_SECRET))
253
+ ? { name: SUBMODULE_TOKEN_SECRET, submodules: privateSubmodules }
254
+ : null
255
+ }
256
+ />
257
+ )
258
+ }
259
+
260
+ /**
261
+ * The public keys a value names: `github:<user>` for the keys on that GitHub account, a path to a
262
+ * `.pub` file, or the key's own text.
263
+ */
264
+ async function publicKeys(value: string): Promise<string[]> {
265
+ if (value.startsWith("github:")) {
266
+ const user = value.slice("github:".length)
267
+ const response = await fetch(`https://github.com/${encodeURIComponent(user)}.keys`)
268
+ if (!response.ok) {
269
+ throw new SixbCliError(`[SixbDeploy] GitHub has no public keys for '${user}'.`)
270
+ }
271
+ const keys = (await response.text()).split("\n").filter((line) => line.trim())
272
+ if (keys.length === 0) throw new SixbCliError(`[SixbDeploy] '${user}' has no keys on GitHub.`)
273
+ return keys.map((key) => `${key.trim()} ${user}@github`)
274
+ }
275
+ const file = Bun.file(value)
276
+ if (await file.exists()) return [(await file.text()).trim()]
277
+ return [value]
278
+ }
279
+
280
+ function blocksDeploy(check: DeployCheck): boolean {
281
+ return check.status === "fixable" || check.status === "manual"
282
+ }
283
+
284
+ function location(config: DeployConfig): string {
285
+ return `${config.target.kind} ${config.target.location}`
286
+ }
287
+
288
+ export async function runDeployStatus(options: { readonly json?: boolean; readonly cwd?: string }) {
289
+ const { config } = await loadDeployConfig(options.cwd)
290
+ const status = await config.target.status({ name: config.name })
291
+ if (options.json) return writeJson(status)
292
+ await renderStatic(
293
+ <DeployStatusView name={config.name} location={config.target.location} status={status} />
294
+ )
295
+ }
296
+
297
+ export async function runDeployLogs(options: {
298
+ readonly service?: string
299
+ readonly follow?: boolean
300
+ readonly tail?: string
301
+ readonly cwd?: string
302
+ }) {
303
+ const tail = options.tail === undefined ? 100 : Number(options.tail)
304
+ if (!Number.isInteger(tail) || tail < 1) {
305
+ throw new SixbCliError("[SixbDeploy] --tail must be a positive number of lines.")
306
+ }
307
+ const { config } = await loadDeployConfig(options.cwd)
308
+ await config.target.logs(
309
+ {
310
+ ...(options.service ? { service: options.service } : {}),
311
+ tail,
312
+ follow: options.follow === true,
313
+ write: (line) => console.log(line),
314
+ },
315
+ { name: config.name }
316
+ )
317
+ }
318
+
319
+ export async function runDeployControl(options: {
320
+ readonly action: DeployControlAction
321
+ readonly service?: string
322
+ readonly cwd?: string
323
+ }) {
324
+ const { config } = await loadDeployConfig(options.cwd)
325
+ await config.target.control(options.action, options.service, { name: config.name })
326
+ await renderStatic(
327
+ <DeployStatusView
328
+ name={config.name}
329
+ location={config.target.location}
330
+ status={await config.target.status({ name: config.name })}
331
+ />
332
+ )
333
+ }
334
+
335
+ /**
336
+ * Follows the target's progress: a live view in a terminal, one line per step and output line
337
+ * elsewhere, so CI logs read top to bottom.
338
+ */
339
+ function createProgress(
340
+ release: DeployRelease,
341
+ source: { readonly commit: string; readonly ref: string; readonly dirty: boolean }
342
+ ) {
343
+ const state: { -readonly [Key in keyof DeployProgressState]: DeployProgressState[Key] } = {
344
+ name: release.name,
345
+ location: `${release.target.kind} ${release.target.location}`,
346
+ commit: source.commit,
347
+ ref: source.ref,
348
+ dirty: source.dirty,
349
+ labels: [],
350
+ done: 0,
351
+ current: null,
352
+ output: [],
353
+ outcome: "running",
354
+ }
355
+ const live = process.stdout.isTTY && !process.env.CI
356
+ const app = live ? renderPersistent(<DeployProgressView state={{ ...state }} />) : null
357
+ const started = new Map<number, number>()
358
+ const render = () => app?.rerender(<DeployProgressView state={{ ...state }} />)
359
+
360
+ if (!live) {
361
+ console.log(`Deploying ${release.name} ${source.commit.slice(0, 12)} to ${state.location}`)
362
+ if (source.dirty) console.log("Uncommitted changes are not deployed.")
363
+ }
364
+
365
+ return {
366
+ state,
367
+ report(event: DeployEvent) {
368
+ if (event.type === "steps") state.labels = [...event.labels]
369
+ if (event.type === "step" && event.status === "running") {
370
+ // A step's output is what explains its failure; earlier steps' would bury it.
371
+ state.output = []
372
+ state.current = event.index
373
+ started.set(event.index, Date.now())
374
+ if (!live) console.log(`▸ ${state.labels[event.index]}`)
375
+ }
376
+ if (event.type === "step" && event.status === "done") {
377
+ state.done = event.index + 1
378
+ if (!live) {
379
+ const seconds = ((Date.now() - (started.get(event.index) ?? Date.now())) / 1000).toFixed(
380
+ 1
381
+ )
382
+ console.log(`✓ ${state.labels[event.index]} (${seconds}s)`)
383
+ }
384
+ }
385
+ if (event.type === "output") {
386
+ state.output = [...state.output, event.line].slice(-12)
387
+ if (!live) console.log(` ${event.line}`)
388
+ }
389
+ render()
390
+ },
391
+ fail() {
392
+ state.outcome = "failed"
393
+ render()
394
+ app?.unmount()
395
+ },
396
+ finish() {
397
+ state.outcome = "done"
398
+ state.current = null
399
+ render()
400
+ app?.unmount()
401
+ },
402
+ }
403
+ }
package/src/index.tsx CHANGED
@@ -321,6 +321,69 @@ async function main(): Promise<void> {
321
321
  break
322
322
  }
323
323
 
324
+ case "deploy": {
325
+ const { runDeploy } = await import("./commands/deploy")
326
+ await runDeploy({ dryRun: hasFlag("dry-run"), json: hasFlag("json"), ref: getFlag("ref") })
327
+ break
328
+ }
329
+
330
+ case "deploy:status": {
331
+ const { runDeployStatus } = await import("./commands/deploy")
332
+ await runDeployStatus({ json: hasFlag("json") })
333
+ break
334
+ }
335
+
336
+ case "deploy:logs": {
337
+ const { runDeployLogs } = await import("./commands/deploy")
338
+ await runDeployLogs({
339
+ service: positionals[0],
340
+ follow: hasFlag("follow"),
341
+ tail: getFlag("tail"),
342
+ })
343
+ break
344
+ }
345
+
346
+ case "deploy:setup": {
347
+ const { runDeploySetup } = await import("./commands/deploy")
348
+ await runDeploySetup({ admin: getFlag("admin"), key: getFlag("key") })
349
+ break
350
+ }
351
+
352
+ case "deploy:check": {
353
+ const { runDeployCheck } = await import("./commands/deploy")
354
+ await runDeployCheck({ json: hasFlag("json") })
355
+ break
356
+ }
357
+
358
+ case "deploy:ci": {
359
+ const { runDeployCi } = await import("./commands/deploy")
360
+ await runDeployCi({ branch: getFlag("branch") })
361
+ break
362
+ }
363
+
364
+ case "deploy:access:list":
365
+ case "deploy:access:add":
366
+ case "deploy:access:remove": {
367
+ const { runDeployAccess } = await import("./commands/deploy")
368
+ await runDeployAccess({
369
+ action: parsed.id.slice("deploy:access:".length) as "list" | "add" | "remove",
370
+ value: positionals[0],
371
+ json: hasFlag("json"),
372
+ })
373
+ break
374
+ }
375
+
376
+ case "deploy:restart":
377
+ case "deploy:start":
378
+ case "deploy:stop": {
379
+ const { runDeployControl } = await import("./commands/deploy")
380
+ await runDeployControl({
381
+ action: parsed.id.slice("deploy:".length) as "restart" | "start" | "stop",
382
+ service: positionals[0],
383
+ })
384
+ break
385
+ }
386
+
324
387
  case "init": {
325
388
  const { runInit } = await import("./commands/init")
326
389
  await runInit(positionals[0])
@@ -8,8 +8,15 @@ export function resolveAgentTurnTimeoutMs(value: string | undefined): number | u
8
8
  const configured = nonblank(value) ?? nonblank(process.env.SIXB_AGENT_TURN_TIMEOUT)
9
9
  if (configured === undefined) return undefined
10
10
 
11
- const match = configured.match(/^(\d+)(ms|s|m|h)$/)
12
- if (!match) throw invalidAgentTurnTimeout(configured)
11
+ const timeoutMs = parseAgentTurnTimeoutMs(configured)
12
+ if (timeoutMs === null) throw invalidAgentTurnTimeout(configured)
13
+ return timeoutMs
14
+ }
15
+
16
+ /** A duration such as `30s`, `10m`, or `1h` in milliseconds, or `null` when it is not one. */
17
+ export function parseAgentTurnTimeoutMs(value: string): number | null {
18
+ const match = value.match(/^(\d+)(ms|s|m|h)$/)
19
+ if (!match) return null
13
20
 
14
21
  const amount = Number(match[1])
15
22
  const unit = match[2] as "ms" | "s" | "m" | "h"
@@ -22,9 +29,8 @@ export function resolveAgentTurnTimeoutMs(value: string | undefined): number | u
22
29
  const timeoutMs = amount * multipliers[unit]
23
30
 
24
31
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_DURATION_MS) {
25
- throw invalidAgentTurnTimeout(configured)
32
+ return null
26
33
  }
27
-
28
34
  return timeoutMs
29
35
  }
30
36
 
@@ -93,11 +93,37 @@ export const CLI_OPTION_DEFINITIONS = {
93
93
  kind: "string",
94
94
  },
95
95
  group: { syntax: "--group <id>", summary: "Assignable token group; may repeat", kind: "string" },
96
- json: { syntax: "--json", summary: "Print JSON for management commands", kind: "boolean" },
96
+ json: { syntax: "--json", summary: "Print JSON instead of formatted output", kind: "boolean" },
97
97
  outdir: { syntax: "--outdir <path>", summary: "Build output directory", kind: "string" },
98
+ ref: {
99
+ syntax: "--ref <ref>",
100
+ summary: "Branch, tag, or commit to deploy (default: HEAD)",
101
+ kind: "string",
102
+ },
103
+ follow: { syntax: "--follow", summary: "Keep printing new log lines", kind: "boolean" },
104
+ admin: {
105
+ syntax: "--admin <login>",
106
+ summary: "Login with sudo that prepares the server (default: root)",
107
+ kind: "string",
108
+ },
109
+ key: {
110
+ syntax: "--key <path>",
111
+ summary: "Public key to authorize for deploys (default: the one SSH uses)",
112
+ kind: "string",
113
+ },
114
+ branch: {
115
+ syntax: "--branch <name>",
116
+ summary: "Branch whose pushes deploy (default: the repository's default branch)",
117
+ kind: "string",
118
+ },
119
+ tail: {
120
+ syntax: "--tail <lines>",
121
+ summary: "Recent log lines to print (default: 100)",
122
+ kind: "string",
123
+ },
98
124
  "dry-run": {
99
125
  syntax: "--dry-run",
100
- summary: "Preview lake cleanup without changing storage",
126
+ summary: "Show what would change without changing it",
101
127
  kind: "boolean",
102
128
  },
103
129
  "expire-older-than": {
@@ -144,6 +170,18 @@ export type LocalCommandId =
144
170
  | "db:migrate"
145
171
  | "lake:check"
146
172
  | "lake:cleanup"
173
+ | "deploy"
174
+ | "deploy:status"
175
+ | "deploy:logs"
176
+ | "deploy:restart"
177
+ | "deploy:start"
178
+ | "deploy:stop"
179
+ | "deploy:setup"
180
+ | "deploy:check"
181
+ | "deploy:ci"
182
+ | "deploy:access:list"
183
+ | "deploy:access:add"
184
+ | "deploy:access:remove"
147
185
  | "init"
148
186
 
149
187
  interface CommandNode {
@@ -425,6 +463,67 @@ const commandTree: readonly CommandNode[] = [
425
463
  }),
426
464
  ],
427
465
  },
466
+ {
467
+ ...command("deploy", "Deploy the project described in sixb.deploy.ts", {
468
+ usage: "sixb deploy [--dry-run] [--ref <ref>] [--json]",
469
+ options: ["dry-run", "ref", "json"],
470
+ rootHelpLabel: "deploy ...",
471
+ }),
472
+ children: [
473
+ command("deploy:setup", "Prepare the server and project for deploys", {
474
+ path: ["deploy", "setup"],
475
+ options: ["admin", "key"],
476
+ }),
477
+ command("deploy:check", "Check what stands between you and a working deploy", {
478
+ path: ["deploy", "check"],
479
+ options: ["json"],
480
+ }),
481
+ command("deploy:ci", "Deploy from GitHub Actions on every push", {
482
+ path: ["deploy", "ci"],
483
+ options: ["branch"],
484
+ }),
485
+ command("deploy:status", "Show what the deployment runs, and which commit", {
486
+ path: ["deploy", "status"],
487
+ options: ["json"],
488
+ }),
489
+ command("deploy:logs", "Print the deployment's logs", {
490
+ path: ["deploy", "logs"],
491
+ usage: "sixb deploy logs [service] [--follow] [--tail <lines>]",
492
+ options: ["follow", "tail"],
493
+ maximumPositionals: 1,
494
+ }),
495
+ ...(["restart", "start", "stop"] as const).map((action) =>
496
+ command(`deploy:${action}`, `${capitalize(action)} one service, or every service`, {
497
+ path: ["deploy", action],
498
+ usage: `sixb deploy ${action} [service]`,
499
+ maximumPositionals: 1,
500
+ })
501
+ ),
502
+ {
503
+ name: "access",
504
+ summary: "Manage the keys that may deploy and operate the deployment",
505
+ usage: "sixb deploy access <list|add|remove>",
506
+ children: [
507
+ command("deploy:access:list", "List the authorized keys", {
508
+ path: ["deploy", "access", "list"],
509
+ options: ["json"],
510
+ }),
511
+ command("deploy:access:add", "Authorize a key: a .pub file, its text, or github:<user>", {
512
+ path: ["deploy", "access", "add"],
513
+ usage: "sixb deploy access add <key>",
514
+ minimumPositionals: 1,
515
+ maximumPositionals: 1,
516
+ }),
517
+ command("deploy:access:remove", "Revoke the keys with this fingerprint or comment", {
518
+ path: ["deploy", "access", "remove"],
519
+ usage: "sixb deploy access remove <fingerprint|comment>",
520
+ minimumPositionals: 1,
521
+ maximumPositionals: 1,
522
+ }),
523
+ ],
524
+ },
525
+ ],
526
+ },
428
527
  command("init", "Initialize sixb project in a directory", {
429
528
  usage: "sixb init [dir]",
430
529
  maximumPositionals: 1,
@@ -512,6 +611,9 @@ export const CLI_EXAMPLES = [
512
611
  "sixb db migrate",
513
612
  "sixb lake check",
514
613
  "sixb lake cleanup --dry-run",
614
+ "sixb deploy --dry-run",
615
+ "sixb deploy",
616
+ "sixb deploy logs api --follow",
515
617
  ] as const
516
618
 
517
619
  export function parseCliArgs(args: readonly string[]): ParsedCli {
@@ -550,8 +652,9 @@ export function repeatedOption(options: ParsedCliOptions, name: CliOptionName):
550
652
 
551
653
  export function wantsManagementJson(args: readonly string[]): boolean {
552
654
  return (
553
- ["login", "logout", "status", "profile", "token", "service-account"].includes(args[0] ?? "") &&
554
- args.some((argument) => argument === "--json" || argument.startsWith("--json="))
655
+ ["login", "logout", "status", "profile", "token", "service-account", "deploy"].includes(
656
+ args[0] ?? ""
657
+ ) && args.some((argument) => argument === "--json" || argument.startsWith("--json="))
555
658
  )
556
659
  }
557
660
 
@@ -609,13 +712,15 @@ function parseLocalCommand(root: CommandNode, args: readonly string[]): ParsedCl
609
712
 
610
713
  while (node.children) {
611
714
  const next = args[index]
715
+ const child = node.children.find((candidate) => candidate.name === next)
716
+ // A command that also has subcommands runs itself when no subcommand follows.
717
+ if (!child && node.id && (next === undefined || next.startsWith("-"))) break
612
718
  if (!next || next === "--help" || next === "-h") {
613
719
  return { kind: "help", help: helpFor(node, path) }
614
720
  }
615
721
  if (next.startsWith("-")) {
616
722
  throw new CliUsageError(`'${path.join(" ")}' requires a subcommand.`, helpFor(node, path))
617
723
  }
618
- const child = node.children.find((candidate) => candidate.name === next)
619
724
  if (!child) {
620
725
  throw new CliUsageError(`Unknown ${path.join(" ")} command '${next}'.`, helpFor(node, path))
621
726
  }
@@ -717,6 +822,10 @@ function parseOptions(
717
822
  return { options, positionals }
718
823
  }
719
824
 
825
+ function capitalize(value: string): string {
826
+ return `${value.charAt(0).toUpperCase()}${value.slice(1)}`
827
+ }
828
+
720
829
  function helpFor(node: CommandNode, path: readonly string[]): CliHelp {
721
830
  const prefix = `sixb ${path.join(" ")}`
722
831
  return {