@yunuseon/kayra 0.14.0 → 0.16.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.
@@ -1,13 +1,20 @@
1
1
  import { appManifestSchema, secretsSchema, settings } from "../settings.js";
2
- const problem = (text) => ({ problem: true, text });
3
- const skipped = (text) => ({ problem: false, text });
2
+ import { active, bad, muted, ok, strong } from "../ui/line.js";
3
+ import { closest } from "../validate.js";
4
+ const finding = (result, text, hint) => ({ result, text, ...(hint === undefined ? {} : { hint }) });
5
+ const problem = (text, hint) => finding("problem", text, hint);
6
+ const unchecked = (text, hint) => finding("unchecked", text, hint);
7
+ const passed = (text) => finding("passed", text);
8
+ /** A check's findings, or one line saying it holds when it found nothing to say. */
9
+ const holds = (found, text) => (found.length === 0 ? [passed(text)] : found);
10
+ const count = (n, noun) => `${String(n)} ${noun}${n === 1 ? "" : "s"}`;
4
11
  const mapping = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : {};
5
12
  const strings = (value) => Array.isArray(value) ? value.filter((each) => typeof each === "string") : [];
6
13
  const secretSettingNames = (kind) => settings.filter((each) => each.secret && each.kinds.includes(kind)).map((each) => each.name);
7
14
  /** secrets.yml: known secrets typed; anything else must be a helper vars.yml uses. */
8
15
  const secretsFindings = (facts) => {
9
16
  if (facts.secrets.kind === "locked")
10
- return [skipped(`secrets.yml not checked: ${facts.secrets.reason}`)];
17
+ return [unchecked(`secrets.yml not checked: ${facts.secrets.reason}`, facts.secrets.hint)];
11
18
  const values = facts.secrets.values;
12
19
  const typed = secretsSchema(facts.server.kind).safeParse(values);
13
20
  const typeProblems = typed.success
@@ -17,68 +24,122 @@ const secretsFindings = (facts) => {
17
24
  const unused = Object.keys(values)
18
25
  .filter((key) => !known.includes(key) && !key.startsWith("ansible_"))
19
26
  .filter((key) => !new RegExp(`\\b${key}\\b`).test(facts.varsText))
20
- .map((key) => problem(`secrets.yml: '${key}' is no secret of a ${facts.server.kind} server, and vars.yml does not use it`));
21
- return [...typeProblems, ...unused];
27
+ .map((key) => {
28
+ const meant = closest(key, known);
29
+ return problem(`secrets.yml: '${key}' is no secret of ${/^[aeiou]/.test(facts.server.kind) ? "an" : "a"} ${facts.server.kind} server, and vars.yml does not use it`, meant === undefined ? "remove it, or use it in vars.yml" : `did you mean '${meant}'?`);
30
+ });
31
+ return holds([...typeProblems, ...unused], `secrets.yml: ${count(Object.keys(values).length, "secret")}, each a setting or used by vars.yml`);
22
32
  };
23
33
  /** compose_stacks.stacks and stacks/ name the same stacks. */
24
34
  const stackFindings = (facts) => {
25
35
  const listed = strings(mapping(facts.vars["compose_stacks"])["stacks"]);
26
- return [
36
+ if (listed.length === 0 && facts.stackDirs.length === 0)
37
+ return [];
38
+ return holds([
27
39
  ...listed
28
40
  .filter((name) => !facts.stackDirs.includes(name))
29
- .map((name) => problem(`compose_stacks.stacks: '${name}' has no stacks/${name}/compose.yaml`)),
41
+ .map((name) => problem(`compose_stacks.stacks: '${name}' has no stacks/${name}/compose.yaml`, `add stacks/${name}/compose.yaml, or take '${name}' off the list`)),
30
42
  ...facts.stackDirs
31
43
  .filter((name) => !listed.includes(name))
32
- .map((name) => problem(`stacks/${name} is not in compose_stacks.stacks, so it never runs`)),
33
- ];
44
+ .map((name) => problem(`stacks/${name} is not in compose_stacks.stacks, so it never runs`, "list it in compose_stacks.stacks in vars.yml, or remove the folder")),
45
+ ], `stacks: ${count(listed.length, "stack")}, each listed in compose_stacks.stacks and in stacks/`);
34
46
  };
35
47
  /** edge_routes: subdomains and an upstream host:port. */
36
48
  const routeFindings = (facts) => {
37
49
  const routes = Array.isArray(facts.vars["edge_routes"]) ? facts.vars["edge_routes"] : [];
38
- return routes.flatMap((route, index) => {
50
+ if (routes.length === 0)
51
+ return [];
52
+ return holds(routes.flatMap((route, index) => {
39
53
  const fields = mapping(route);
40
54
  const upstream = fields["upstream"];
41
55
  return [
42
56
  ...strings(fields["subdomains"])
43
57
  .filter((sub) => !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(sub))
44
- .map((sub) => problem(`edge_routes[${String(index)}]: '${sub}' is not a subdomain`)),
58
+ .map((sub) => problem(`edge_routes[${String(index)}]: '${sub}' is not a subdomain`, "lowercase letters, digits and dashes")),
45
59
  ...(typeof upstream === "string" && /^[^\s:]+:\d+$/.test(upstream)
46
60
  ? []
47
- : [problem(`edge_routes[${String(index)}]: upstream must be host:port`)]),
61
+ : [problem(`edge_routes[${String(index)}]: upstream must be host:port`, "a host and its port, e.g. 192.168.1.10:8080")]),
48
62
  ];
49
- });
63
+ }), `edge_routes: ${count(routes.length, "route")}, each with subdomains and a host:port upstream`);
50
64
  };
51
65
  /** Each app's contract against the fleet's values for it. */
52
66
  const appFindings = (facts) => facts.server.apps.flatMap((app) => {
53
67
  const manifest = facts.manifests[app.name];
54
68
  if (manifest === undefined)
55
- return [skipped(`app ${app.name} not checked: not cloned yet (kayra apps clones it)`)];
69
+ return [unchecked(`app ${app.name} not checked: not cloned yet`, `kayra apps ${facts.server.name} clones it`)];
56
70
  const parsed = appManifestSchema.safeParse(manifest);
57
71
  if (!parsed.success)
58
72
  return [problem(`app ${app.name}: its app.yml: ${parsed.error.issues.at(0)?.message ?? "invalid"}`)];
59
73
  if (parsed.data.name !== app.name)
60
- return [problem(`app ${app.name}: its app.yml says name ${parsed.data.name}`)];
74
+ return [problem(`app ${app.name}: its app.yml says name ${parsed.data.name}`, "server.yml and app.yml must name it alike")];
75
+ const configKeys = parsed.data.config ?? [];
76
+ const secretKeys = parsed.data.secrets ?? [];
61
77
  const config = facts.appConfig[app.name] ?? {};
62
- const missingConfig = (parsed.data.config ?? [])
78
+ const valuesFile = `apps/${app.name}.yml`;
79
+ const secretsFile = `apps/${app.name}.secrets.yml`;
80
+ const missingConfig = configKeys
63
81
  .filter((key) => !(key in config))
64
- .map((key) => problem(`apps/${app.name}.yml: no value for ${key}, which app.yml asks for`));
65
- const secrets = facts.appSecrets[app.name];
66
- const missingSecrets = secrets === undefined || secrets.kind === "locked"
67
- ? (parsed.data.secrets ?? []).length === 0
82
+ .map((key) => problem(`${valuesFile}: no value for ${key}, which app.yml asks for`, `add ${key}: … to servers/${facts.server.name}/${valuesFile}`));
83
+ const secrets = facts.appSecrets[app.name] ?? { kind: "readable", values: {} };
84
+ const edit = facts.server.target === "multipass" ? "add it to" : "ansible-vault edit";
85
+ const missingSecrets = secrets.kind === "locked"
86
+ ? secretKeys.length === 0
68
87
  ? []
69
- : [skipped(`apps/${app.name}.secrets.yml not checked: ${secrets?.reason ?? "missing"}`)]
70
- : (parsed.data.secrets ?? [])
88
+ : [unchecked(`${secretsFile} not checked: ${secrets.reason}`, secrets.hint)]
89
+ : secretKeys
71
90
  .filter((key) => !(key in secrets.values))
72
- .map((key) => problem(`apps/${app.name}.secrets.yml: no value for ${key}, which app.yml asks for`));
73
- return [...missingConfig, ...missingSecrets];
91
+ .map((key) => problem(`${secretsFile}: no value for ${key}, which app.yml asks for`, `${edit} servers/${facts.server.name}/${secretsFile}`));
92
+ return holds([...missingConfig, ...missingSecrets], `app ${app.name}: ${count(configKeys.length, "config value")} and ${count(secretKeys.length, "secret")}, as its app.yml asks`);
74
93
  });
75
- /** Everything validate finds for one server, problems first. */
76
- export const findings = (facts) => [...secretsFindings(facts), ...stackFindings(facts), ...routeFindings(facts), ...appFindings(facts)].toSorted((a, b) => Number(b.problem) - Number(a.problem));
77
- /** One server's report: a line saying whether it holds, then each finding. */
78
- export const report = (name, found) => {
79
- const problems = found.filter((each) => each.problem);
94
+ const rank = { problem: 0, unchecked: 1, passed: 2 };
95
+ /** Everything validate finds for one server: problems first, then what it could not check, then what holds. */
96
+ export const findings = (facts) => [...secretsFindings(facts), ...stackFindings(facts), ...routeFindings(facts), ...appFindings(facts)].toSorted((a, b) => rank[a.result] - rank[b.result]);
97
+ /** How a set of findings went as a whole: its worst. */
98
+ export const overall = (found) => found.some((each) => each.result === "problem") ? "problem" : found.some((each) => each.result === "unchecked") ? "unchecked" : "passed";
99
+ const marks = { problem: bad("✗"), unchecked: muted("·"), passed: ok("✓") };
100
+ const tally = (reports) => {
101
+ const all = reports.flatMap((report) => report.findings);
102
+ return {
103
+ problems: all.filter((each) => each.result === "problem").length,
104
+ unchecked: all.filter((each) => each.result === "unchecked").length,
105
+ };
106
+ };
107
+ /** "✗ 3 servers · 1 problem · 2 not checked" */
108
+ export const summary = (reports) => {
109
+ const { problems, unchecked: notChecked } = tally(reports);
80
110
  return [
81
- `${problems.length === 0 ? "ok " : "FAIL"} ${name}`,
82
- ...found.map((each) => ` ${each.problem ? "✗" : "·"} ${each.text}`),
111
+ marks[overall(reports.flatMap((report) => report.findings))],
112
+ " ",
113
+ count(reports.length, "server"),
114
+ muted(" · "),
115
+ problems === 0 ? ok("no problems") : bad(count(problems, "problem")),
116
+ ...(notChecked === 0 ? [] : [muted(" · "), `${String(notChecked)} not checked`]),
83
117
  ];
84
118
  };
119
+ /** Each server with its mark, its findings under it with what to do about them, then the summary. */
120
+ export const validateView = (reports) => {
121
+ const names = Math.max(0, ...reports.map((report) => report.server.name.length));
122
+ return [
123
+ ...reports.flatMap((report) => [
124
+ [marks[overall(report.findings)], " ", strong(report.server.name.padEnd(names)), muted(` ${report.server.kind} on ${report.server.target}`)],
125
+ ...report.findings.flatMap((each) => [
126
+ [" ", marks[each.result], " ", each.result === "passed" ? muted(each.text) : each.text],
127
+ ...(each.hint === undefined ? [] : [[" ", active("→"), " ", each.hint]]),
128
+ ]),
129
+ [],
130
+ ]),
131
+ summary(reports),
132
+ ];
133
+ };
134
+ /** `kayra validate --json`: the shape cli.md documents. */
135
+ export const validateJson = (reports) => ({
136
+ result: overall(reports.flatMap((report) => report.findings)),
137
+ ...tally(reports),
138
+ servers: reports.map((report) => ({
139
+ name: report.server.name,
140
+ kind: report.server.kind,
141
+ target: report.server.target,
142
+ result: overall(report.findings),
143
+ findings: report.findings.map((each) => ({ result: each.result, text: each.text, hint: each.hint ?? null })),
144
+ })),
145
+ });
@@ -0,0 +1,21 @@
1
+ /** A release record's compact UTC time, 20261018T101500Z, as ISO 8601. */
2
+ const iso = (compact) => compact.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/, "$1-$2-$3T$4:$5:$6Z");
3
+ const deployed = (release) => ({ sha: release.sha, time: iso(release.time) });
4
+ const answer = (run) => ({
5
+ id: run.id,
6
+ state: run.state,
7
+ why: run.why,
8
+ what: run.what,
9
+ ...(run.sha === undefined ? {} : { sha: run.sha }),
10
+ started: run.started,
11
+ ...(run.finished === undefined ? {} : { finished: run.finished }),
12
+ });
13
+ export const runsAnswer = (app, runs, live) => ({
14
+ app,
15
+ ...(live === undefined ? {} : { live: deployed(live) }),
16
+ runs: runs.map(answer),
17
+ });
18
+ export const releasesAnswer = (app, releases) => ({
19
+ app,
20
+ releases: releases.map((release, index) => ({ ...deployed(release), live: index === 0 })),
21
+ });
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { releasesAnswer, runsAnswer } from "./answers.js";
3
4
  import { appOwner, appName, owner as mintOwner, runId } from "./brand.js";
4
5
  import { releases } from "./records.js";
5
6
  import { log, runsOf } from "./store.js";
@@ -7,7 +8,8 @@ import { log, runsOf } from "./store.js";
7
8
  * The operator's side, run inside the deployer container by `kayra app …` and
8
9
  * `kayra job …` over SSH. Reads runs/ and releases/ directly; anything that
9
10
  * starts a run goes through the daemon's control port, so the queue stays the
10
- * only place runs begin.
11
+ * only place runs begin. `--json` makes `runs` and rollback's list answer as
12
+ * data (answers.ts), which kayra draws.
11
13
  */
12
14
  const platformDir = process.env["PLATFORM_DIR"] ?? "/opt/platform";
13
15
  const runs = join(platformDir, "runs");
@@ -27,11 +29,16 @@ const releasesOf = (app) => {
27
29
  return releases(existsSync(dir) ? readdirSync(dir) : []);
28
30
  };
29
31
  const commands = {
30
- runs: ([app]) => {
32
+ runs: ([app], json) => {
31
33
  const name = appName(app ?? "");
32
34
  if (!name.ok)
33
35
  return fail(name.error);
34
- runsOf(runs, appOwner(name.value)).slice(0, 20).forEach((run) => {
36
+ const latest = runsOf(runs, appOwner(name.value)).slice(0, 20);
37
+ if (json) {
38
+ console.log(JSON.stringify(runsAnswer(name.value, latest, releasesOf(name.value)[0])));
39
+ return 0;
40
+ }
41
+ latest.forEach((run) => {
35
42
  console.log([run.id, run.state.padEnd(8), (run.sha ?? "").slice(0, 12).padEnd(12), run.why.padEnd(8), run.what].join(" "));
36
43
  });
37
44
  return 0;
@@ -49,13 +56,18 @@ const commands = {
49
56
  return 0;
50
57
  },
51
58
  deploy: ([app, ref]) => post("/deploy", { app, ref: ref ?? "", why: "deploy" }),
52
- rollback: ([app, commit]) => {
59
+ rollback: ([app, commit], json) => {
53
60
  const name = appName(app ?? "");
54
61
  if (!name.ok)
55
62
  return fail(name.error);
56
- const [live, ...earlier] = releasesOf(name.value);
63
+ const all = releasesOf(name.value);
64
+ const [live, ...earlier] = all;
57
65
  if (live === undefined)
58
66
  return fail(`${name.value} has not been deployed yet`);
67
+ if (commit === undefined && json) {
68
+ console.log(JSON.stringify(releasesAnswer(name.value, all)));
69
+ return earlier.length === 0 ? 1 : 0;
70
+ }
59
71
  if (commit === undefined) {
60
72
  console.log(`${name.value} runs ${live.sha} (since ${live.time}). Earlier releases:`);
61
73
  earlier.forEach((release) => {
@@ -73,5 +85,7 @@ const commands = {
73
85
  export const ctl = async (args) => {
74
86
  const [name, ...rest] = args;
75
87
  const command = name === undefined ? undefined : commands[name];
76
- return command === undefined ? fail(`usage: ctl ${Object.keys(commands).join("|")} …`) : command(rest);
88
+ return command === undefined
89
+ ? fail(`usage: ctl ${Object.keys(commands).join("|")} … [--json]`)
90
+ : command(rest.filter((word) => word !== "--json"), rest.includes("--json"));
77
91
  };
@@ -1,4 +1,5 @@
1
1
  import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
2
3
  import { join } from "node:path";
3
4
  import { yamlOf } from "./fleet.js";
4
5
  import { capture } from "./interpret.js";
@@ -12,19 +13,22 @@ const mappingOf = (source) => {
12
13
  : {};
13
14
  };
14
15
  const vaulted = (source) => source.startsWith("$ANSIBLE_VAULT");
15
- /** A secrets file's values: plaintext as is, a vault only with the server's password file. */
16
+ /** A secrets file's values: plaintext as is, a vault only with the server's password file; a missing file has none. */
16
17
  const secretsOf = async (server, path) => {
17
18
  const source = text(path);
18
19
  if (source === undefined)
19
- return { kind: "locked", reason: "missing" };
20
+ return { kind: "readable", values: {} };
20
21
  if (!vaulted(source))
21
22
  return { kind: "readable", values: mappingOf(source) };
22
- if (server.vault.kind !== "file" || !existsSync(server.vault.file))
23
- return { kind: "locked", reason: "vaulted, and no vault password file here" };
23
+ if (server.vault.kind !== "file")
24
+ return { kind: "locked", reason: "vaulted, and server.yml names no vault_password_file", hint: "vault_password_file in server.yml lets kayra open it" };
25
+ const file = server.vault.file.replace(homedir(), "~");
26
+ if (!existsSync(server.vault.file))
27
+ return { kind: "locked", reason: `vaulted, and there is no ${file} here`, hint: "put the vault's password there" };
24
28
  const opened = await capture(["ansible-vault", "view", "--vault-password-file", server.vault.file, path], "capture");
25
29
  return opened.code === 0
26
30
  ? { kind: "readable", values: mappingOf(opened.stdout) }
27
- : { kind: "locked", reason: "the vault password does not open it" };
31
+ : { kind: "locked", reason: `${file} does not open it`, hint: "is it this vault's password?" };
28
32
  };
29
33
  const appPath = (entry) => {
30
34
  const parsed = JSON.parse(entry);
@@ -1,98 +1,141 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { text } from "node:stream/consumers";
3
- const spawned = async (argv, streams, env = {}) => {
3
+ import { all, err, flatMap, ok } from "./result.js";
4
+ import { active, bad, muted, ok as fine, strong } from "./ui/line.js";
5
+ import { position, silent } from "./ui/progress.js";
6
+ import { draw } from "./ui/views.js";
7
+ const terminal = {};
8
+ /** A program that ignores SIGINT this long gets SIGTERM. */
9
+ const patience = 10_000;
10
+ const spawned = async (argv, streams, env = {}, plumbing = terminal) => {
4
11
  const [program, ...args] = argv;
12
+ const { output, signal } = plumbing;
13
+ if (signal?.aborted === true)
14
+ return { code: 130, stdout: "", stderr: "", started: false };
15
+ const shown = (stream) => stream === "show" ? (output === undefined ? "inherit" : "pipe") : stream === "capture" ? "pipe" : "ignore";
5
16
  const child = spawn(program, args, {
6
17
  env: { ...process.env, ...env },
7
- stdio: [
8
- "inherit",
9
- streams.stdout === "show" ? "inherit" : streams.stdout === "capture" ? "pipe" : "ignore",
10
- streams.stderr === "show" ? "inherit" : "pipe",
11
- ],
18
+ stdio: [output === undefined ? "inherit" : "ignore", shown(streams.stdout), shown(streams.stderr)],
12
19
  });
13
- const stdout = child.stdout === null ? Promise.resolve("") : text(child.stdout);
14
- const stderr = child.stderr === null ? Promise.resolve("") : text(child.stderr);
20
+ const forward = (from, sink) => {
21
+ child[from]?.setEncoding("utf8").on("data", (chunk) => {
22
+ sink(chunk, from);
23
+ });
24
+ };
25
+ if (output !== undefined && streams.stdout === "show")
26
+ forward("stdout", output);
27
+ if (output !== undefined && streams.stderr === "show")
28
+ forward("stderr", output);
29
+ const read = (from, stream) => {
30
+ const piped = child[from];
31
+ return piped === null || stream !== "capture" ? Promise.resolve("") : text(piped);
32
+ };
33
+ const stdout = read("stdout", streams.stdout);
34
+ const stderr = read("stderr", streams.stderr);
35
+ const stop = () => {
36
+ child.kill("SIGINT");
37
+ setTimeout(() => child.kill("SIGTERM"), patience).unref();
38
+ };
39
+ signal?.addEventListener("abort", stop, { once: true });
15
40
  const exit = await new Promise((resolve) => {
16
41
  child.on("error", resolve);
17
42
  child.on("close", (code) => {
18
43
  resolve(code ?? 1);
19
44
  });
20
45
  });
46
+ signal?.removeEventListener("abort", stop);
21
47
  return exit instanceof Error
22
- ? { code: 127, stdout: "", stderr: exit.message }
23
- : { code: exit, stdout: await stdout, stderr: await stderr };
48
+ ? { code: 127, stdout: "", stderr: exit.message, started: false }
49
+ : { code: exit, stdout: await stdout, stderr: await stderr, started: true };
24
50
  };
25
51
  /** A command's stdout, for kayra to read; its stderr reaches the operator unless captured too. */
26
- export const capture = (argv, stderr = "show", env = {}) => spawned(argv, { stdout: "capture", stderr }, env);
27
- const answer = (probe) => spawned(probe.kind === "on-path" ? ["sh", "-c", 'command -v "$1"', "sh", probe.program] : probe.argv, { stdout: "discard", stderr: "capture" }, probe.kind === "exits-zero" ? probe.env : {});
28
- /** Each query's answer in place of it, as `$(…)` would: one word, or split into many. Undefined if one failed. */
29
- const resolve = async (argv, io) => {
52
+ export const capture = (argv, stderr = "show", env = {}, plumbing = terminal) => spawned(argv, { stdout: "capture", stderr }, env, plumbing);
53
+ const answer = (probe, plumbing) => spawned(probe.kind === "on-path" ? ["sh", "-c", 'command -v "$1"', "sh", probe.program] : probe.argv, { stdout: "discard", stderr: "capture" }, probe.kind === "exits-zero" ? probe.env : {}, plumbing);
54
+ /** Each query's answer in place of it, as `$(…)` would: one word, or split into many. */
55
+ const resolve = async (argv, plumbing) => {
30
56
  const words = await Promise.all(argv.map(async (value) => {
31
57
  if (typeof value === "string")
32
- return [value];
33
- const exit = await capture(value.argv, "show", value.env);
34
- if (exit.code !== 0) {
35
- io.err(`kayra: ${value.argv.join(" ")} failed (exit ${String(exit.code)})`);
36
- return undefined;
37
- }
58
+ return ok([value]);
59
+ const exit = await capture(value.argv, "show", value.env, plumbing);
60
+ if (exit.code !== 0)
61
+ return err(`$(${value.argv.join(" ")}) failed: exit ${String(exit.code)}`);
38
62
  const output = exit.stdout.replace(/\n+$/, "");
39
- return value.words === "one" ? [output] : output.split(/\s+/).filter((word) => word !== "");
63
+ return ok(value.words === "one" ? [output] : output.split(/\s+/).filter((word) => word !== ""));
40
64
  }));
41
- const [program, ...rest] = words.flatMap((word) => word ?? []);
42
- return words.includes(undefined) || program === undefined ? undefined : [program, ...rest];
65
+ return flatMap(all(words), (lists) => {
66
+ const [program, ...rest] = lists.flat();
67
+ return program === undefined ? err("the command is empty") : ok([program, ...rest]);
68
+ });
43
69
  };
44
70
  const lines = (text) => text
45
71
  .trimEnd()
46
72
  .split("\n")
47
73
  .filter((line) => line !== "");
48
- const goOn = { failed: false, stopped: false };
49
- const check = async (step, io) => {
50
- const exit = await answer(step.probe);
51
- const hint = step.hint === undefined ? [] : [` → ${step.hint}`];
52
- if (step.onFailure === "stop") {
53
- if (exit.code === 0)
54
- return goOn;
55
- [...lines(exit.stderr), ...hint].forEach(io.err);
56
- return { failed: true, stopped: true };
57
- }
58
- if (exit.code === 0) {
59
- io.out(`ok ${step.label}`);
60
- return goOn;
61
- }
62
- [`FAIL ${step.label}`, ...lines(exit.stderr).map((line) => ` ${line}`), ...hint].forEach(io.out);
63
- return { failed: true, stopped: false };
74
+ /** Under the step's own line. */
75
+ const detail = (line) => [" ", line];
76
+ const aside = (line) => [" ", muted(line)];
77
+ const hint = (text) => (text === undefined ? [] : [[" ", active("→"), " ", text]]);
78
+ const goOn = { failed: false, stopped: false, out: [], err: [] };
79
+ const check = async (step, plumbing) => {
80
+ const exit = await answer(step.probe, plumbing);
81
+ const said = [...lines(exit.stderr).map(detail), ...hint(step.hint)];
82
+ if (step.onFailure === "stop")
83
+ return exit.code === 0 ? goOn : { failed: true, stopped: true, out: [], err: said };
84
+ return exit.code === 0
85
+ ? { ...goOn, out: [[fine("✓"), " ", step.label]] }
86
+ : { failed: true, stopped: false, out: [[bad("✗"), " ", step.label], ...said], err: [] };
87
+ };
88
+ const runStep = async (step, plumbing) => {
89
+ const argv = await resolve(step.argv, plumbing);
90
+ if (!argv.ok)
91
+ return { failed: true, stopped: true, why: "a query failed", out: [], err: [detail(argv.error)] };
92
+ const { stdout } = step;
93
+ // A quiet step's stderr waits until it is done, so it cannot tear through a spinner.
94
+ const quiet = stdout === "discard";
95
+ const exit = await spawned(argv.value, { stdout: typeof stdout === "string" ? stdout : "capture", stderr: quiet ? "capture" : "show" }, step.env, plumbing);
96
+ if (!exit.started)
97
+ return { failed: true, stopped: true, why: "not started", out: [], err: [detail(`${argv.value[0]}: ${exit.stderr}`)] };
98
+ // Whatever it answered is shown, even when it failed: it may say why.
99
+ const out = typeof stdout === "string" ? [] : draw(stdout, exit.stdout, Date.now());
100
+ if (exit.code === 0)
101
+ return { ...goOn, out, err: lines(exit.stderr).map(aside) };
102
+ return { failed: true, stopped: true, why: `exit ${String(exit.code)}`, out, err: lines(exit.stderr).map(detail) };
64
103
  };
65
104
  const perform = async (step, io) => {
66
105
  switch (step.kind) {
67
- case "run": {
68
- const argv = await resolve(step.argv, io);
69
- if (argv === undefined)
70
- return { failed: true, stopped: true };
71
- const exit = await spawned(argv, { stdout: step.stdout, stderr: "show" }, step.env);
72
- return exit.code === 0 ? goOn : { failed: true, stopped: true };
73
- }
106
+ case "run":
107
+ return runStep(step, io);
74
108
  case "check":
75
109
  return check(step, io);
76
110
  case "confirm": {
77
- const typed = await io.ask(step.prompt);
78
- if (typed === step.expect)
79
- return goOn;
80
- io.out("Aborted.");
81
- return { failed: false, stopped: true };
111
+ io.err("");
112
+ io.err([" ", bad("▲"), " ", strong(step.warning)]);
113
+ const typed = await io.ask([" Type ", strong(step.expect), " to confirm: "]);
114
+ return typed === step.expect ? goOn : { failed: false, stopped: true, out: ["Aborted."], err: [] };
82
115
  }
83
116
  case "note":
84
- io.out(step.text);
85
- return goOn;
117
+ return { ...goOn, out: [step.text] };
86
118
  }
87
119
  };
88
- /** Runs a plan step by step, until it ends or a step stops it. True if nothing failed. */
89
- export const interpret = async (plan, io) => {
90
- const outcome = await plan.reduce(async (previous, step) => {
120
+ /**
121
+ * Runs a plan step by step, until it ends or a step stops it, shown by `progress`.
122
+ * True if nothing failed and the operator did not interrupt it.
123
+ */
124
+ export const interpret = async (plan, io, progress = silent, interrupted = () => false) => {
125
+ const ended = await progress.plan(plan, () => plan.reduce(async (previous, step, index) => {
91
126
  const so = await previous;
92
- if (so.stopped)
127
+ if (so.stop !== undefined)
93
128
  return so;
94
- const next = await perform(step, io);
95
- return { failures: so.failures + (next.failed ? 1 : 0), stopped: next.stopped };
96
- }, Promise.resolve({ failures: 0, stopped: false }));
97
- return outcome.failures === 0;
129
+ const done = await progress.step(step, position(plan, index), () => perform(step, io));
130
+ // Ctrl-C reached the step's program too: how it ended says nothing about the server.
131
+ if (interrupted())
132
+ return { failures: so.failures, stop: { index, step, why: "interrupted" } };
133
+ done.out.forEach(io.out);
134
+ done.err.forEach(io.err);
135
+ const failures = so.failures + (done.failed ? 1 : 0);
136
+ if (done.stopped)
137
+ return { failures, stop: { index, step, why: done.failed ? "failed" : "declined" } };
138
+ return { failures };
139
+ }, Promise.resolve({ failures: 0 })));
140
+ return ended.failures === 0 && ended.stop?.why !== "interrupted";
98
141
  };