Skip to content

g1t/scripts/deploy.mjs

550 lines24,937 bytesCodeBlame
1#!/usr/bin/env node
2// Deploys g1t to Cloudflare from deploy/stack.jsonc: only what changed since
3// each Worker's live commit, migrations first, then stage by stage.
4// docs/DEPLOYING.md is the guide.
5//
6// node scripts/deploy.mjs plan what would deploy, and why (read-only)
7// node scripts/deploy.mjs deploy migrations, then every changed unit
8// node scripts/deploy.mjs deploy --only web,api just these (if changed; --force: anyway)
9// node scripts/deploy.mjs build --only events build as a deploy would, upload nothing
10// node scripts/deploy.mjs migrate pending D1 migrations only
11// node scripts/deploy.mjs manifest [--check] the resolved manifest, or its problems
12// node scripts/deploy.mjs doctor which units lack their secrets
13// node scripts/deploy.mjs install --only a,b npm ci of just what those units need (CI)
14// node scripts/deploy.mjs build-base build and push the runner's base image (Docker)
15// node scripts/deploy.mjs image build and push the runner's image for this checkout (Docker)
16//
17// Flags: --all (every unit, changed or not), --only a,b, --skip a,b,
18// --force, --concurrency N (default 4), --stage core (one stage),
19// --json (plan), --out FILE (plan), --no-migrations, --allow-dirty,
20// --rebuild-image, --rebuild-base, --since REV (Workers with no recorded
21// commit are taken to run REV); for build-base and image, --no-push, and
22// for build-base, --no-cache.
23
24import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
25import { tmpdir } from "node:os";
26import { join } from "node:path";
27
28import { OUT_DIR } from "./build-runner.mjs";
29import { ensureWorkerBuild } from "./build-rust-worker.mjs";
30import {
31 annotation,
32 applyMigrations,
33 dockerAvailable,
34 exec,
35 jsonFrom,
36 lastLines,
37 pendingMigrations,
38 readLive,
39 versionFrom,
40 wrangler,
41 wranglerEnv,
42} from "./deploy/cloudflare.mjs";
43import {
44 baseInputs,
45 baseState,
46 baseTag,
47 baseVersions,
48 buildBase,
49 buildRunnerImage,
50 dockerHas,
51 dockerLogin,
52 imageSize,
53 pushImage,
54 readBaseLock,
55 registryHas,
56 removeDeployConfig,
57 runnerRef,
58 writeBaseLock,
59 writeDeployConfig,
60} from "./deploy/image.mjs";
61import { decide, git, planJson, pool, table } from "./deploy/plan.mjs";
62import { reportDeployment } from "./deploy/report.mjs";
63import { ROOT, byStage, codeStages, findWranglerConfigs, npmCiArgs, npmWorkspace, pick, problems, resolvedStack } from "./deploy/stack.mjs";
64
65const USAGE = "usage: node scripts/deploy.mjs plan|deploy|build|migrate|manifest|doctor|install|build-base|image [--all] [--only a,b] [--skip a,b] [--force] [--rollback] [--concurrency N] [--stage S] [--json]";
66
67function parseArgs(argv) {
68 const opts = { command: argv[0], only: [], skip: [], concurrency: 4, force: false, all: false, json: false };
69 for (let i = 1; i < argv.length; i++) {
70 const arg = argv[i];
71 const [flag, inline] = arg.split(/=(.*)/s);
72 const value = () => inline ?? argv[++i];
73 if (flag === "--only") opts.only.push(value());
74 else if (flag === "--skip") opts.skip.push(value());
75 else if (flag === "--concurrency") opts.concurrency = Number(value());
76 else if (flag === "--stage") opts.stage = value();
77 else if (flag === "--all") opts.all = true;
78 else if (flag === "--force") opts.force = true;
79 else if (flag === "--rollback") opts.rollback = true;
80 else if (flag === "--json") opts.json = true;
81 else if (flag === "--check") opts.check = true;
82 else if (flag === "--no-migrations") opts.noMigrations = true;
83 else if (flag === "--allow-dirty") opts.allowDirty = true;
84 else if (flag === "--rebuild-image") opts.rebuildImage = true;
85 else if (flag === "--rebuild-base") opts.rebuildBase = true;
86 else if (flag === "--no-push") opts.noPush = true;
87 else if (flag === "--no-cache") opts.noCache = true;
88 else if (flag === "--out") opts.out = value();
89 else if (flag === "--since") opts.since = value();
90 else if (flag === "--github-output") opts.githubOutput = true;
91 else throw new Error(`unknown flag ${arg}\n${USAGE}`);
92 }
93 if (!Number.isInteger(opts.concurrency) || opts.concurrency < 1) throw new Error("--concurrency is a whole number, 1 or more");
94 return opts;
95}
96
97/** The units a command works on: --only (or all), less --skip, in --stage. */
98function selected(stack, opts) {
99 let units = opts.only.length ? pick(stack, opts.only) : [...stack.units];
100 const skipped = pick(stack, opts.skip);
101 units = units.filter((u) => !skipped.includes(u));
102 if (opts.stage) {
103 if (!codeStages(stack).includes(opts.stage)) throw new Error(`--stage is one of ${codeStages(stack).join(", ")}`);
104 units = units.filter((u) => u.stage === opts.stage);
105 }
106 // Manifest order, whatever order they were named in.
107 return stack.units.filter((u) => units.includes(u));
108}
109
110const log = (...args) => console.error(...args);
111
112/**
113 * The plan for a workflow (.g1t/workflows/deploy.yml): job outputs in
114 * $GITHUB_OUTPUT, and the plan as a table in $GITHUB_STEP_SUMMARY.
115 */
116function writeGithubOutputs(data, p) {
117 const lines = [
118 `commit=${data.commit}`,
119 `migrate=${data.migrations.length > 0}`,
120 `migrate_units=${data.migrations.map((m) => m.unit).join(",")}`,
121 `deploying=${data.units.filter((u) => u.deploy).map((u) => u.unit).join(",")}`,
122 ];
123 for (const [stage, { jobs }] of Object.entries(data.stages)) {
124 // A matrix needs one entry; an empty stage's job is skipped by its `if`.
125 const include = jobs.length ? jobs : [{ group: "none", units: "" }];
126 lines.push(`has_${stage}=${jobs.length > 0}`, `${stage}=${JSON.stringify({ include })}`);
127 }
128 if (data.migration_errors.length) {
129 // The units, then why for the first: one cause (a token, say) is usually all of them.
130 throw new Error(`Could not read pending migrations: ${data.migration_errors.map((e) => e.unit).join(", ")}
131${data.migration_errors[0].error}`);
132 }
133 if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `${lines.join("\n")}\n`);
134 else console.log(lines.join("\n"));
135 if (process.env.GITHUB_STEP_SUMMARY) {
136 const rows = p.decisions.map((d) => `| ${d.unit.id} | ${d.unit.stage} | ${d.deploy ? "deploy" : ""} | ${d.since ? d.since.slice(0, 12) : "?"} | ${d.reason.replaceAll("|", "\\|")} |`);
137 const pending = data.migrations.map((m) => `- ${m.database}: ${m.pending.join(", ")}`);
138 appendFileSync(
139 process.env.GITHUB_STEP_SUMMARY,
140 [`## Deploy plan for ${data.commit.slice(0, 12)}`, "", "| unit | stage | action | live | why |", "| --- | --- | --- | --- | --- |", ...rows, "", pending.length ? "### Pending migrations" : "", ...pending, ""].join("\n"),
141 );
142 }
143}
144
145const seconds = (ms) => `${(ms / 1000).toFixed(1)}s`;
146
147/** Reads what each unit runs and what its database is waiting for. */
148async function survey(units, opts) {
149 const live = {};
150 const migrations = {};
151 const tasks = [
152 ...(opts.noLive ? [] : units).map((unit) => async () => {
153 live[unit.id] = await readLive(unit);
154 }),
155 ...(opts.noMigrations ? [] : units.filter((u) => u.d1)).map((unit) => async () => {
156 migrations[unit.id] = await pendingMigrations(unit);
157 }),
158 ];
159 await pool(tasks, Math.max(8, opts.concurrency * 2), (task) => task());
160 return { live, migrations };
161}
162
163async function plan(stack, opts) {
164 const units = selected(stack, opts);
165 const head = git.head();
166 const { live, migrations } = await survey(units, opts);
167 // --since: what a Worker with no recorded commit is taken to run (once,
168 // to adopt Workers deployed before this tool), for example --since HEAD~3.
169 if (opts.since) {
170 const since = git.resolve(opts.since);
171 for (const unit of units) {
172 const found = live[unit.id];
173 if (found && !found.sha && !found.missing && !found.error) live[unit.id] = { ...found, sha: since, assumed: true };
174 }
175 }
176 const decisions = decide(units, { live, head, force: opts.force || opts.all, rollback: opts.rollback });
177 return { head, units, live, migrations, decisions };
178}
179
180function buildPlan(stack, opts) {
181 const units = selected(stack, opts);
182 return {
183 head: git.head(),
184 units,
185 live: {},
186 migrations: {},
187 decisions: units.map((unit) => ({ unit, deploy: true, reason: "build", since: null, files: [], image: false })),
188 };
189}
190
191function printPlan(stack, { head, decisions, migrations, live }) {
192 console.log(`Deploying ${head.slice(0, 12)} (${git.subject()})\n`);
193 const rows = decisions.map((d) => [
194 d.unit.id,
195 d.unit.stage,
196 d.deploy ? "deploy" : "-",
197 d.since ? d.since.slice(0, 12) + (live[d.unit.id]?.assumed ? "*" : "") : "?",
198 d.unit.d1 ? (migrations[d.unit.id]?.error ? "error" : String(migrations[d.unit.id]?.pending?.length ?? "-")) : "",
199 d.reason + (d.image ? "; image rebuilds" : ""),
200 ]);
201 console.log(table(rows, ["unit", "stage", "action", "live", "migrations", "why"]));
202 if (decisions.some((d) => live[d.unit.id]?.assumed)) console.log("* taken from --since: no commit was recorded for it");
203 const pending = Object.entries(migrations).filter(([, m]) => m.pending?.length);
204 if (pending.length) {
205 console.log("\nPending migrations:");
206 for (const [id, m] of pending) console.log(` ${stack.units.find((u) => u.id === id).d1.database}: ${m.pending.join(", ")}`);
207 }
208 for (const [id, m] of Object.entries(migrations).filter(([, m]) => m.error)) {
209 console.log(`\nCould not list ${id}'s migrations:\n${m.error}`);
210 }
211 const deploying = decisions.filter((d) => d.deploy).map((d) => d.unit);
212 console.log(
213 deploying.length
214 ? `\n${deploying.length} to deploy: ${byStage(stack, deploying).map((g) => `${g.stage} (${g.units.map((u) => u.id).join(", ")})`).join(" -> ")}`
215 : "\nNothing to deploy.",
216 );
217}
218
219/** Output of one unit, prefixed, to the terminal and a log file. */
220function unitLogger(id) {
221 const dir = join(tmpdir(), "g1t-deploy");
222 mkdirSync(dir, { recursive: true });
223 const file = join(dir, `${id}.log`);
224 const lines = [];
225 return {
226 file,
227 line: (text) => {
228 lines.push(text);
229 if (text.trim()) log(`[${id}] ${text}`);
230 },
231 save: () => writeFileSync(file, `${lines.join("\n")}\n`),
232 };
233}
234
235/**
236 * The runner's image for this checkout, by registry reference: already in
237 * the registry (built by an earlier deploy, `deploy.mjs image`, or on
238 * another machine), or built and pushed here, which needs Docker. A dry
239 * run builds it locally and pushes nothing. Returns { ref, note }.
240 */
241async function runnerImage(unit, { dryRun, docker, rebuildImage, rebuildBase }, out) {
242 let base = baseState(unit);
243 if (!base.current || rebuildBase) {
244 if (!rebuildBase) {
245 throw new Error(
246 `${unit.image.base.context} has changed since ${unit.image.base.lock} was written${base.lock ? "" : " (the base has never been built)"}. Build and push the base, and commit ${unit.image.base.lock}: node scripts/deploy.mjs build-base`,
247 );
248 }
249 if (!docker) throw new Error("--rebuild-base needs Docker.");
250 await newBase(unit, { push: !dryRun, onLine: out.line });
251 base = baseState(unit);
252 }
253 if (!base.pushed && !dryRun) throw new Error(`${unit.image.base.lock} records a base that was never pushed: node scripts/deploy.mjs build-base`);
254 const ref = runnerRef(unit);
255 const tag = ref.split(":").pop();
256 if (!rebuildImage) {
257 if (dryRun && docker && (await dockerHas(ref))) return { ref, note: `image ${tag} already built here` };
258 if (!dryRun) {
259 try {
260 if (await registryHas(ref)) return { ref, note: `image ${tag} already in the registry` };
261 } catch (error) {
262 out.line(`could not ask the registry for ${tag}: ${error.message ?? error}`);
263 }
264 }
265 }
266 if (!docker) {
267 throw new Error(
268 `its image ${tag} is not in the registry, and Docker is not available here. Build and push it from a machine with Docker (node scripts/deploy.mjs image), then run this again.`,
269 );
270 }
271 const started = Date.now();
272 const binary = await exec(process.execPath, [join(ROOT, "scripts/build-runner.mjs")], { onLine: out.line });
273 if (binary.code !== 0) throw new Error(`the runner binary did not build:\n${lastLines(binary.out)}`);
274 if (!dryRun) await dockerLogin({ push: true });
275 await buildRunnerImage(unit, { ref, base: base.ref, binaryDir: OUT_DIR, onLine: out.line });
276 if (!dryRun) await pushImage(ref, { onLine: out.line });
277 return { ref, note: `image ${tag} ${dryRun ? "built" : "built and pushed"} in ${seconds(Date.now() - started)}` };
278}
279
280/** Builds the base (and pushes it unless `push` is false), and writes its lock. */
281async function newBase(unit, { push = true, noCache = false, onLine = log } = {}) {
282 const started = Date.now();
283 const inputs = baseInputs(unit);
284 const tag = baseTag(inputs);
285 const previous = readBaseLock(unit);
286 // Logged in, the base it replaces is pulled as cache.
287 if (push || previous?.pushed) {
288 try {
289 await dockerLogin({ push });
290 } catch (error) {
291 if (push) throw error;
292 onLine(`not logged in to the registry, so no cache from it: ${error.message ?? error}`);
293 }
294 }
295 const ref = await buildBase(unit, { tag, previous: previous?.pushed ? previous.image : null, onLine, noCache });
296 const built = Date.now();
297 const [size, versions] = await Promise.all([imageSize(ref), baseVersions(ref)]);
298 const digest = push ? await pushImage(ref, { onLine }) : null;
299 const lock = { image: ref, digest, pushed: push, inputs, built_at: new Date().toISOString(), size_bytes: size, versions };
300 writeBaseLock(unit, lock);
301 onLine(`base ${tag}: built in ${seconds(built - started)}${push ? `, pushed in ${seconds(Date.now() - built)}` : ""}, ${(size / 1e9).toFixed(2)} GB unpacked`);
302 return lock;
303}
304
305/** Builds (and unless `dryRun`, deploys) one unit. */
306async function ship(unit, decision, { head, subject, dirty, dryRun, docker, rebuildImage, rebuildBase }) {
307 const started = Date.now();
308 const out = unitLogger(unit.id);
309 const cwd = join(ROOT, unit.path);
310 const result = { unit: unit.id, stage: unit.stage, ok: false, version: null, ms: 0, note: "" };
311 try {
312 if (unit.kind === "react-router" || unit.kind === "astro") {
313 // One command string: Node warns about arguments passed beside shell: true.
314 const built = await exec("npm run build", [], { cwd, onLine: out.line, shell: true, env: wranglerEnv() });
315 if (built.code !== 0) throw new Error(`npm run build failed:\n${lastLines(built.out)}`);
316 }
317 const args = ["deploy"];
318 if (dryRun) {
319 args.push("--dry-run", "--outdir", join(tmpdir(), "g1t-deploy", "dist", unit.id));
320 } else {
321 const { message, tag } = annotation(head, subject);
322 args.push("--message", dirty ? message.replace(/^g1t-deploy/, "g1t-deploy-dirty") : message, "--tag", tag);
323 }
324 if (unit.image) {
325 // Wrangler is given the image by reference, so it builds nothing.
326 const image = await runnerImage(unit, { dryRun, docker, rebuildImage, rebuildBase }, out);
327 args.push("--config", writeDeployConfig(unit, image.ref));
328 // Nothing the image is built from changed: the running sandboxes
329 // keep going, and new ones start from the same image.
330 if (!rebuildImage && !rebuildBase && !decision.image) args.push("--containers-rollout", "none");
331 result.note = image.note;
332 }
333 const deployed = await wrangler(args, { cwd, onLine: out.line });
334 if (deployed.code !== 0) throw new Error(`wrangler deploy failed:\n${lastLines(deployed.out)}`);
335 result.version = dryRun ? "(dry run)" : versionFrom(deployed.out);
336 result.ok = true;
337 } catch (error) {
338 result.note = String(error.message ?? error);
339 } finally {
340 if (unit.image) removeDeployConfig(unit);
341 }
342 result.ms = Date.now() - started;
343 out.save();
344 if (!result.ok) result.note += `\n full log: ${out.file}`;
345 return result;
346}
347
348async function migrate(stack, units, migrations, opts) {
349 const due = units.filter((u) => migrations[u.id]?.pending?.length);
350 const broken = units.filter((u) => migrations[u.id]?.error);
351 if (broken.length) {
352 throw new Error(`Could not read pending migrations for ${broken.map((u) => u.id).join(", ")}; nothing was deployed.`);
353 }
354 if (!due.length) return [];
355 log(`== migrations: ${due.map((u) => `${u.d1.database} (${migrations[u.id].pending.length})`).join(", ")}`);
356 const results = await pool(due, opts.concurrency, async (unit) => {
357 const started = Date.now();
358 const out = unitLogger(`${unit.id}-migrations`);
359 const applied = await applyMigrations(unit, out.line);
360 out.save();
361 return {
362 unit: `${unit.id} (D1 ${unit.d1.database})`,
363 stage: "migrations",
364 ok: applied.code === 0,
365 version: `${migrations[unit.id].pending.length} applied`,
366 ms: Date.now() - started,
367 note: applied.code === 0 ? "" : `${lastLines(applied.out)}\n full log: ${out.file}`,
368 };
369 });
370 return results;
371}
372
373function summary(results) {
374 const rows = results.map((r) => [r.unit, r.stage, r.ok ? "ok" : r.skipped ? "not started" : "FAILED", r.version ?? "", r.ms ? seconds(r.ms) : "", r.note.split("\n")[0]]);
375 console.log(`\n${table(rows, ["unit", "stage", "result", "version", "time", "note"])}`);
376 for (const r of results.filter((r) => !r.ok && !r.skipped)) console.log(`\n${r.unit}: ${r.note}`);
377}
378
379async function deploy(stack, opts, { dryRun = false } = {}) {
380 const started = Date.now();
381 // A build reads nothing from Cloudflare: it builds what it is given.
382 const p = dryRun ? buildPlan(stack, opts) : await plan(stack, opts);
383 if (!dryRun) printPlan(stack, p);
384 const deploying = p.decisions.filter((d) => d.deploy);
385 const touched = deploying.map((d) => d.unit);
386 const head = p.head;
387
388 // A deploy names the commit it came from, so a dirty tree would be
389 // recorded as something it is not.
390 const dirtyFiles = git.dirty();
391 const dirty = deploying.some((d) => dirtyFiles.some((file) => file.startsWith(`${d.unit.path}/`) || d.unit.dependsOn.some((dir) => file.startsWith(`${dir}/`)) || d.unit.inputs.includes(file)));
392 if (dirty && !dryRun && !opts.allowDirty) {
393 throw new Error("Uncommitted changes touch what would deploy. Commit them, or pass --allow-dirty (the deploy then records no commit, and the next plan deploys it again).");
394 }
395
396 const results = [];
397 if (!dryRun && !opts.noMigrations) {
398 const migrated = await migrate(stack, p.units, p.migrations, opts);
399 results.push(...migrated);
400 if (migrated.some((r) => !r.ok)) {
401 summary(results);
402 return false;
403 }
404 }
405 if (!touched.length) {
406 if (results.length) summary(results);
407 return true;
408 }
409
410 if (touched.some((u) => u.kind === "rust-worker")) ensureWorkerBuild();
411 const docker = touched.some((u) => u.image) ? await dockerAvailable() : false;
412 const context = { head, subject: git.subject(), dirty, dryRun, docker, rebuildImage: opts.rebuildImage, rebuildBase: opts.rebuildBase };
413 // A deploy run by hand shows on the repository's Deployments page; a
414 // dirty tree is not a commit anyone can look at, so it is left out.
415 const settle = dryRun || dirty ? null : await reportDeployment({ head, subject: context.subject, units: touched.map((u) => u.id), log });
416
417 let failed = false;
418 for (const { stage, units } of byStage(stack, touched)) {
419 if (failed) {
420 for (const unit of units) results.push({ unit: unit.id, stage, ok: false, skipped: true, ms: 0, note: "an earlier stage failed" });
421 continue;
422 }
423 log(`== ${stage}: ${units.map((u) => u.id).join(", ")}`);
424 const shipped = await pool(units, opts.concurrency, (unit) => ship(unit, deploying.find((d) => d.unit === unit), context));
425 results.push(...shipped);
426 failed = shipped.some((r) => !r.ok);
427 }
428 summary(results);
429 await settle?.(!failed);
430 console.log(`\n${failed ? "Failed" : dryRun ? "Built" : "Deployed"} in ${seconds(Date.now() - started)}.`);
431 return !failed;
432}
433
434async function doctor(stack, opts) {
435 const units = selected(stack, opts);
436 const rows = await pool(units, 8, async (unit) => {
437 if (!unit.secrets.length) return [unit.id, "", "", ""];
438 const found = await wrangler(["secret", "list", "--name", unit.worker, "--format", "json"], { cwd: join(ROOT, unit.path) });
439 if (found.code !== 0) return [unit.id, unit.secrets.join(" "), "?", "could not read"];
440 const have = new Set(jsonFrom(found.out).map((s) => s.name));
441 const missing = unit.secrets.filter((name) => !have.has(name));
442 return [unit.id, unit.secrets.join(" "), missing.join(" "), missing.length ? "missing" : "ok"];
443 });
444 console.log(table(rows, ["unit", "secrets", "missing", "result"]));
445 return rows.every((r) => r[3] !== "missing");
446}
447
448async function install(stack, opts) {
449 const units = selected(stack, opts);
450 const args = npmCiArgs(units, npmWorkspace());
451 log(`npm ${args.join(" ")}`);
452 const done = await exec(`npm ${args.join(" ")}`, [], { cwd: ROOT, shell: true, onLine: (line) => log(line) });
453 return done.code === 0;
454}
455
456function manifest(stack, opts) {
457 const found = problems(stack, findWranglerConfigs());
458 if (opts.check) {
459 for (const problem of found) console.log(`- ${problem}`);
460 console.log(found.length ? `\n${found.length} problems in deploy/stack.jsonc.` : "deploy/stack.jsonc is consistent with every wrangler.jsonc.");
461 return !found.length;
462 }
463 const out = stack.units.map(({ config, ...unit }) => ({
464 ...unit,
465 queues: { produces: (config?.queues?.producers ?? []).map((q) => q.queue), consumes: (config?.queues?.consumers ?? []).map((q) => q.queue) },
466 kv: (config?.kv_namespaces ?? []).map((kv) => stack.resources.kv?.[kv.id] ?? kv.id),
467 r2: (config?.r2_buckets ?? []).map((b) => b.bucket_name),
468 vectorize: (config?.vectorize ?? []).map((v) => v.index_name),
469 dispatch_namespaces: (config?.dispatch_namespaces ?? []).map((d) => d.namespace),
470 routes: (config?.routes ?? []).map((r) => r.pattern),
471 }));
472 if (opts.json) console.log(JSON.stringify({ stages: stack.stages, units: out }, null, 2));
473 else
474 console.log(
475 table(
476 out.map((u) => [u.id, u.stage, u.kind, u.worker, u.d1?.database ?? "", u.dependsOn.join(" ")]),
477 ["unit", "stage", "kind", "worker", "d1", "built from (besides its folder)"],
478 ),
479 );
480 return true;
481}
482
483/** The unit with a Containers image (the runner), or the one named. */
484function imageUnit(stack, opts) {
485 const units = (opts.only.length ? pick(stack, opts.only) : stack.units).filter((u) => u.image?.base);
486 if (units.length !== 1) throw new Error("Name the unit with a Containers image: --only runner");
487 return units[0];
488}
489
490async function main() {
491 const opts = parseArgs(process.argv.slice(2));
492 const stack = resolvedStack();
493 switch (opts.command) {
494 case "plan": {
495 const p = await plan(stack, opts);
496 const data = planJson(stack, p.decisions, p.migrations, p.head);
497 if (opts.out) writeFileSync(opts.out, `${JSON.stringify(data)}\n`);
498 if (opts.githubOutput) writeGithubOutputs(data, p);
499 if (opts.json) console.log(JSON.stringify(data, null, 2));
500 else if (!opts.githubOutput || process.env.GITHUB_OUTPUT) printPlan(stack, p);
501 return true;
502 }
503 case "deploy":
504 return deploy(stack, opts);
505 case "build":
506 return deploy(stack, { ...opts, force: true }, { dryRun: true });
507 case "migrate": {
508 const units = selected(stack, opts);
509 const { migrations } = await survey(units.filter((u) => u.d1), { ...opts, noMigrations: false, noLive: true });
510 const results = await migrate(stack, units, migrations, opts);
511 if (results.length) summary(results);
512 else console.log("No migrations to apply.");
513 return results.every((r) => r.ok);
514 }
515 case "manifest":
516 return manifest(stack, opts);
517 case "doctor":
518 return doctor(stack, opts);
519 case "install":
520 return install(stack, opts);
521 case "build-base": {
522 const unit = imageUnit(stack, opts);
523 if (!(await dockerAvailable())) throw new Error("build-base needs Docker.");
524 const lock = await newBase(unit, { push: !opts.noPush, noCache: opts.noCache });
525 console.log(JSON.stringify(lock, null, 2));
526 if (lock.pushed) console.log(`\nCommit ${unit.image.base.lock}: the next deploy builds the runner's image on this base.`);
527 return true;
528 }
529 case "image": {
530 const unit = imageUnit(stack, opts);
531 const out = unitLogger(`${unit.id}-image`);
532 const docker = await dockerAvailable();
533 const image = await runnerImage(unit, { dryRun: Boolean(opts.noPush), docker, rebuildImage: opts.rebuildImage, rebuildBase: opts.rebuildBase }, out);
534 out.save();
535 console.log(`${image.ref}\n${image.note}`);
536 return true;
537 }
538 default:
539 console.error(USAGE);
540 return false;
541 }
542}
543
544main().then(
545 (ok) => process.exit(ok ? 0 : 1),
546 (error) => {
547 console.error(`\n${error.message ?? error}`);
548 process.exit(1);
549 },
550);