@foliwake/cli 0.10.2 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +196 -14
  3. package/config/docker/compose.varnish.yaml +44 -0
  4. package/config/docker/compose.yaml +165 -0
  5. package/dist/commands/dev.d.ts +3 -0
  6. package/dist/commands/dev.js +58 -21
  7. package/dist/commands/docker/backup.d.ts +12 -0
  8. package/dist/commands/docker/backup.js +29 -0
  9. package/dist/commands/docker/configure.d.ts +23 -0
  10. package/dist/commands/docker/configure.js +73 -0
  11. package/dist/commands/docker/exec.d.ts +8 -0
  12. package/dist/commands/docker/exec.js +26 -0
  13. package/dist/commands/docker/install.d.ts +33 -0
  14. package/dist/commands/docker/install.js +126 -0
  15. package/dist/commands/docker/link.d.ts +12 -0
  16. package/dist/commands/docker/link.js +24 -0
  17. package/dist/commands/docker/list.d.ts +7 -0
  18. package/dist/commands/docker/list.js +16 -0
  19. package/dist/commands/docker/logs.d.ts +15 -0
  20. package/dist/commands/docker/logs.js +33 -0
  21. package/dist/commands/docker/remove.d.ts +13 -0
  22. package/dist/commands/docker/remove.js +35 -0
  23. package/dist/commands/docker/restart.d.ts +9 -0
  24. package/dist/commands/docker/restart.js +18 -0
  25. package/dist/commands/docker/restore.d.ts +14 -0
  26. package/dist/commands/docker/restore.js +34 -0
  27. package/dist/commands/docker/start.d.ts +9 -0
  28. package/dist/commands/docker/start.js +18 -0
  29. package/dist/commands/docker/status.d.ts +10 -0
  30. package/dist/commands/docker/status.js +22 -0
  31. package/dist/commands/docker/stop.d.ts +9 -0
  32. package/dist/commands/docker/stop.js +18 -0
  33. package/dist/commands/docker/update.d.ts +14 -0
  34. package/dist/commands/docker/update.js +42 -0
  35. package/dist/commands/project/publish.d.ts +1 -0
  36. package/dist/commands/project/publish.js +9 -2
  37. package/dist/core-command.d.ts +4 -1
  38. package/dist/core-command.js +6 -2
  39. package/dist/core-types.d.ts +1 -0
  40. package/dist/dev/container.d.ts +45 -0
  41. package/dist/dev/container.js +128 -0
  42. package/dist/dev/remote-html.js +2 -2
  43. package/dist/docker/asker.d.ts +4 -0
  44. package/dist/docker/asker.js +34 -0
  45. package/dist/docker/backup.d.ts +21 -0
  46. package/dist/docker/backup.js +114 -0
  47. package/dist/docker/cache-plan.d.ts +17 -0
  48. package/dist/docker/cache-plan.js +58 -0
  49. package/dist/docker/compose-file.d.ts +18 -0
  50. package/dist/docker/compose-file.js +58 -0
  51. package/dist/docker/context.d.ts +55 -0
  52. package/dist/docker/context.js +12 -0
  53. package/dist/docker/engine.d.ts +8 -0
  54. package/dist/docker/engine.js +51 -0
  55. package/dist/docker/env-block.d.ts +19 -0
  56. package/dist/docker/env-block.js +117 -0
  57. package/dist/docker/env-keys.d.ts +4 -0
  58. package/dist/docker/env-keys.js +33 -0
  59. package/dist/docker/env-verify.d.ts +17 -0
  60. package/dist/docker/env-verify.js +62 -0
  61. package/dist/docker/install-plan.d.ts +81 -0
  62. package/dist/docker/install-plan.js +332 -0
  63. package/dist/docker/install.d.ts +22 -0
  64. package/dist/docker/install.js +118 -0
  65. package/dist/docker/instance.d.ts +105 -0
  66. package/dist/docker/instance.js +184 -0
  67. package/dist/docker/lifecycle.d.ts +19 -0
  68. package/dist/docker/lifecycle.js +70 -0
  69. package/dist/docker/ports.d.ts +14 -0
  70. package/dist/docker/ports.js +50 -0
  71. package/dist/docker/process-context.d.ts +8 -0
  72. package/dist/docker/process-context.js +26 -0
  73. package/dist/docker/remove.d.ts +7 -0
  74. package/dist/docker/remove.js +82 -0
  75. package/dist/docker/report.d.ts +32 -0
  76. package/dist/docker/report.js +109 -0
  77. package/dist/docker/runner.d.ts +28 -0
  78. package/dist/docker/runner.js +55 -0
  79. package/dist/docker/settings-files.d.ts +40 -0
  80. package/dist/docker/settings-files.js +125 -0
  81. package/dist/docker/trace-url.d.ts +5 -0
  82. package/dist/docker/trace-url.js +36 -0
  83. package/dist/docker/update.d.ts +29 -0
  84. package/dist/docker/update.js +317 -0
  85. package/dist/docker-command.d.ts +17 -0
  86. package/dist/docker-command.js +37 -0
  87. package/dist/project-preview.d.ts +8 -0
  88. package/dist/project-preview.js +27 -5
  89. package/dist/project-publish.d.ts +8 -7
  90. package/dist/project-publish.js +124 -57
  91. package/dist/publish-code.d.ts +75 -0
  92. package/dist/publish-code.js +223 -0
  93. package/dist/render/site-status.js +2 -2
  94. package/package.json +13 -8
@@ -0,0 +1,317 @@
1
+ // `update` (pull and recreate; the data volume stays) and `configure` (change answers of
2
+ // `install`, then recreate). Both need the instance's files on this computer; both regenerate
3
+ // compose.yaml from the template of this CLI, so a newer CLI brings its template along.
4
+ import { traceUrlTemplateProblem } from './trace-url.js';
5
+ import { askerOf } from './asker.js';
6
+ import { backupInstance } from './backup.js';
7
+ import { applyCache, cacheOf, chooseCache } from './cache-plan.js';
8
+ import { composeFile } from './compose-file.js';
9
+ import { DockerFailure, DockerUsageError } from './context.js';
10
+ import { jaegerTraceUrl, originProblem, proxyTrustOf } from './install-plan.js';
11
+ import { pullImage } from './install.js';
12
+ import { TRACES_MODES, containerOf } from './instance.js';
13
+ import { translatePortError } from './lifecycle.js';
14
+ import { parsePort, portProblem, portsInUse, firstFreePort, DEFAULT_JAEGER_PORT } from './ports.js';
15
+ import { discoverInstances, foreignUse } from './instance.js';
16
+ import { failureText } from './runner.js';
17
+ import { writeVerified } from './env-verify.js';
18
+ import { composeArgs, composeEnv, instanceDir, readEnvFile, undoWrite } from './settings-files.js';
19
+ async function filesOf(ctx, instance) {
20
+ const files = await readEnvFile(ctx.env, instance.name);
21
+ if (!files) {
22
+ throw new DockerUsageError(`The settings of ${instance.name} are not on this computer (${instanceDir(ctx.env, instance.name)}); ` +
23
+ `\`update\` and \`configure\` need them. start, stop, restart, logs, link and remove work without ` +
24
+ `them.`);
25
+ }
26
+ return files;
27
+ }
28
+ const tracesOf = (files, instance) => {
29
+ const value = files.values.FOLIWAKE_TRACES ?? containerOf(instance, 'server')?.traces ?? 'none';
30
+ return TRACES_MODES.includes(value) ? value : 'none';
31
+ };
32
+ /** The compose.yaml of the instance's settings (its traces and its cache). */
33
+ function composeFileOf(ctx, instance, files) {
34
+ const traces = tracesOf(files, instance);
35
+ return composeFile({ name: instance.name, traces, cliVersion: ctx.cliVersion, cache: cacheOf(files.values) });
36
+ }
37
+ async function writeAndUp(ctx, instance, files) {
38
+ const compose = await composeFileOf(ctx, instance, files);
39
+ await writeVerified(ctx, instance.name, { compose, env: files });
40
+ const upArgs = composeArgs(ctx.env, instance.name, [
41
+ 'up',
42
+ '-d',
43
+ '--wait',
44
+ '--wait-timeout',
45
+ '180',
46
+ '--remove-orphans',
47
+ ]);
48
+ const up = await ctx.docker.run(upArgs, { env: composeEnv(ctx.env) });
49
+ if (up.code !== 0) {
50
+ throw new DockerFailure(`${instance.name} did not start: ${translatePortError(failureText(up), instance.name)}\nSee \`foliwake ` +
51
+ `docker logs ${instance.name}\`.`);
52
+ }
53
+ }
54
+ async function imageFacts(ctx, ref) {
55
+ const result = await ctx.docker.run(['image', 'inspect', '--format', 'json', ref]);
56
+ if (result.code !== 0)
57
+ return null;
58
+ const [image] = JSON.parse(result.stdout);
59
+ return image ? { id: image.Id, digest: image.RepoDigests?.[0] ?? null } : null;
60
+ }
61
+ const short = (id) => id.replace(/^sha256:/, '').slice(0, 12);
62
+ /**
63
+ * Before the switch: a backup of the data volume (./backup.ts), unless the caller skips it. It runs in the
64
+ * image the instance switches to (`image`, an id): a backup the old image cannot take still precedes the update.
65
+ */
66
+ async function backupBeforeSwitch(ctx, instance, image, backup) {
67
+ if (!containerOf(instance, 'server'))
68
+ return;
69
+ if (!backup) {
70
+ ctx.err(`No backup was taken (--no-backup).`);
71
+ return;
72
+ }
73
+ const file = await backupInstance(ctx, instance, undefined, image);
74
+ ctx.out(`Backed up the data of ${instance.name} to ${file} before the update.`);
75
+ }
76
+ /**
77
+ * After the switch: every site's caches drop their HTML, which the old engine composed
78
+ * (`foliwake data refresh-caches` in the new server). A failure is reported; the update stands.
79
+ */
80
+ async function refreshCaches(ctx, instance) {
81
+ const exec = ['exec', '-T', 'foliwake', 'foliwake', 'data', 'refresh-caches'];
82
+ const ran = await ctx.docker.run(composeArgs(ctx.env, instance.name, exec), { env: composeEnv(ctx.env) });
83
+ for (const line of ran.stdout.trim().split('\n').filter(Boolean))
84
+ ctx.out(` cache refresh ${line}`);
85
+ if (ran.code !== 0) {
86
+ ctx.err(`Some caches were not refreshed: ${failureText(ran)}`);
87
+ ctx.err(`Run it again: foliwake docker exec ${instance.name} -- data refresh-caches`);
88
+ }
89
+ }
90
+ /**
91
+ * `update [--image REF] [--pull missing] [--no-backup]`: pull, compare; when the image changed, back up the
92
+ * data volume, recreate, then refresh every site's cached HTML. A failed pull fails; `--pull missing`
93
+ * (explicit) uses an image already on this engine, e.g. to roll back to a local build by its id.
94
+ */
95
+ export async function runUpdate(ctx, instance, image, pull = 'always', { backup = true } = {}) {
96
+ const files = await filesOf(ctx, instance);
97
+ const server = containerOf(instance, 'server');
98
+ if (image !== undefined)
99
+ files.values.FOLIWAKE_IMAGE = image;
100
+ const ref = files.values.FOLIWAKE_IMAGE;
101
+ const compose = await composeFileOf(ctx, instance, files);
102
+ const written = await writeVerified(ctx, instance.name, { compose, env: files });
103
+ try {
104
+ await pullImage(ctx, instance.name, ref, pull);
105
+ }
106
+ catch (error) {
107
+ // A failed pull changes nothing: both files go back exactly as they were (an --image is not kept).
108
+ await undoWrite(ctx.env, instance.name, written.previous);
109
+ throw error;
110
+ }
111
+ const now = await imageFacts(ctx, ref);
112
+ if (!now)
113
+ throw new DockerFailure(`The image ${ref} is not on this engine after the pull.`);
114
+ if (server && server.imageId === now.id && server.image === ref) {
115
+ // Compose recreates the container only if its settings changed (a line added to .env).
116
+ await writeAndUp(ctx, instance, files);
117
+ ctx.out(`${instance.name} is already up to date (${ref} @${short(now.id)}); its settings are applied.`);
118
+ return 0;
119
+ }
120
+ const before = server ? await imageFacts(ctx, server.imageId) : null;
121
+ // A registry image rolls back by its digest (pulled again if need be); a local build only by its
122
+ // id, which no registry has: that takes --pull missing.
123
+ const previous = before?.digest ?? (server ? server.imageId : null);
124
+ const rollbackPull = before?.digest ? '' : ' --pull missing';
125
+ if (previous)
126
+ files.values.FOLIWAKE_PREVIOUS_IMAGE = previous;
127
+ await backupBeforeSwitch(ctx, instance, now.id, backup);
128
+ await writeAndUp(ctx, instance, files);
129
+ await refreshCaches(ctx, instance);
130
+ ctx.out(`Updated ${instance.name}: ${server ? `${server.image} @${short(server.imageId)}` : '(no container)'} ` +
131
+ `→ ${ref} @${short(now.id)}. The data volume is unchanged.`);
132
+ if (previous)
133
+ ctx.out(`Roll back: foliwake docker update ${instance.name} --image ${previous}${rollbackPull}`);
134
+ return 0;
135
+ }
136
+ /** --trace-url-template: set the collector's trace page, or remove it with ''. */
137
+ function applyTraceUrl(values, template) {
138
+ if (template === undefined)
139
+ return;
140
+ if (template === '') {
141
+ delete values.FOLIWAKE_TRACE_URL_TEMPLATE;
142
+ return;
143
+ }
144
+ const problem = traceUrlTemplateProblem(template);
145
+ if (problem)
146
+ throw new DockerUsageError(`--trace-url-template: ${problem}`);
147
+ values.FOLIWAKE_TRACE_URL_TEMPLATE = template;
148
+ }
149
+ async function applyTraces(ctx, instance, values, request, used) {
150
+ const traces = request.traces;
151
+ if (!TRACES_MODES.includes(traces))
152
+ throw new DockerUsageError(`--traces must be none, jaeger or external; got ${JSON.stringify(request.traces)}.`);
153
+ const was = values.FOLIWAKE_TRACES;
154
+ const previous = {
155
+ store: values.JAEGER_CONFIG,
156
+ port: values.JAEGER_UI_PORT ? parsePort(values.JAEGER_UI_PORT) : null,
157
+ };
158
+ values.FOLIWAKE_TRACES = traces;
159
+ delete values.JAEGER_CONFIG;
160
+ delete values.JAEGER_UI_PORT;
161
+ if (traces === 'none') {
162
+ const traceKeys = [
163
+ 'OTEL_EXPORTER_OTLP_ENDPOINT',
164
+ 'OTEL_EXPORTER_OTLP_HEADERS',
165
+ 'FOLIWAKE_ENVIRONMENT',
166
+ 'FOLIWAKE_TRACE_URL_TEMPLATE',
167
+ ];
168
+ for (const key of traceKeys) {
169
+ delete values[key];
170
+ }
171
+ return;
172
+ }
173
+ // The link to this instance's Jaeger goes with it; a collector's template stays unless replaced.
174
+ if (was === 'jaeger')
175
+ delete values.FOLIWAKE_TRACE_URL_TEMPLATE;
176
+ values.FOLIWAKE_ENVIRONMENT = instance.name;
177
+ if (traces === 'external') {
178
+ const endpoint = request.otlpEndpoint ?? (was === 'external' ? values.OTEL_EXPORTER_OTLP_ENDPOINT : undefined);
179
+ if (!endpoint || !/^https?:\/\/\S+$/.test(endpoint))
180
+ throw new DockerUsageError('--traces external needs --otlp-endpoint (an http(s) address).');
181
+ values.OTEL_EXPORTER_OTLP_ENDPOINT = endpoint;
182
+ let headers = ctx.env.OTEL_EXPORTER_OTLP_HEADERS ?? '';
183
+ if (!headers && ctx.interactive) {
184
+ headers = await askerOf(ctx).secret('OTLP headers (key=value,…; Enter to keep or leave none)', {
185
+ optional: true,
186
+ });
187
+ }
188
+ if (headers)
189
+ values.OTEL_EXPORTER_OTLP_HEADERS = headers;
190
+ else if (was !== 'external')
191
+ delete values.OTEL_EXPORTER_OTLP_HEADERS;
192
+ applyTraceUrl(values, request.traceUrlTemplate);
193
+ return;
194
+ }
195
+ // Jaeger already there: what is not given stays as it is (its store, its UI port).
196
+ const keep = was === 'jaeger';
197
+ if (!keep) {
198
+ const foreign = await foreignUse(ctx, instance.name);
199
+ if (foreign) {
200
+ throw new DockerUsageError(`Jaeger is not added: ${foreign} has a name of this instance but is not part of it, and Compose would ` +
201
+ `use it. It is left alone.`);
202
+ }
203
+ }
204
+ const store = request.jaegerStore ?? (keep ? previous.store : undefined) ?? 'memory';
205
+ if (store !== 'memory' && store !== 'badger')
206
+ throw new DockerUsageError(`--jaeger-store must be memory or badger; got ${JSON.stringify(store)}.`);
207
+ // The server's own port is taken too: the UI never gets it.
208
+ const reserved = new Map(used);
209
+ reserved.set(Number(values.FOLIWAKE_HOST_PORT), `${instance.name} (its server)`);
210
+ const ownUi = containerOf(instance, 'jaeger')?.ports.find((published) => published.containerPort === 16686)?.port;
211
+ let port;
212
+ if (request.jaegerPort !== undefined) {
213
+ port = parsePort(request.jaegerPort);
214
+ if (port === null)
215
+ throw new DockerUsageError(`--jaeger-port must be a port number; got ${JSON.stringify(request.jaegerPort)}.`);
216
+ const problem = port === ownUi ? null : await portProblem(ctx, reserved, '127.0.0.1', port);
217
+ if (problem)
218
+ throw new DockerUsageError(`Jaeger UI port ${problem}.`);
219
+ }
220
+ else if (keep && previous.port !== null)
221
+ port = previous.port;
222
+ else
223
+ port = await firstFreePort(ctx, reserved, '127.0.0.1', DEFAULT_JAEGER_PORT);
224
+ if (port === null)
225
+ throw new DockerUsageError('No usable port for the Jaeger UI: choose one with --jaeger-port.');
226
+ values.OTEL_EXPORTER_OTLP_ENDPOINT = 'http://jaeger:4318';
227
+ delete values.OTEL_EXPORTER_OTLP_HEADERS;
228
+ values.JAEGER_CONFIG = store;
229
+ values.JAEGER_UI_PORT = String(port);
230
+ values.FOLIWAKE_TRACE_URL_TEMPLATE = jaegerTraceUrl(port);
231
+ }
232
+ /** --cache / --cache-port; the port the instance's own Varnish publishes now stays its own. */
233
+ async function configureCache(ctx, instance, values, request, used) {
234
+ const own = containerOf(instance, 'cache')?.ports[0]?.port ?? null;
235
+ const cache = request.cache ?? cacheOf(values);
236
+ const typed = request.cachePort === undefined ? null : parsePort(request.cachePort);
237
+ if (cache === 'varnish' && own !== null && (request.cachePort === undefined || typed === own)) {
238
+ return applyCache(values, { cache: 'varnish', cachePort: own });
239
+ }
240
+ const reserved = new Map(used);
241
+ reserved.set(Number(values.FOLIWAKE_HOST_PORT), `${instance.name} (its server)`);
242
+ const bind = values.FOLIWAKE_BIND ?? '127.0.0.1';
243
+ applyCache(values, await chooseCache(ctx, { cache, cachePort: request.cachePort }, reserved, bind));
244
+ }
245
+ /** `configure`: change the given settings, then recreate (the data volume stays). */
246
+ export async function runConfigure(ctx, instance, request) {
247
+ if (Object.values(request).every((value) => value === undefined)) {
248
+ throw new DockerUsageError('Nothing to change: pass --traces, --port, --bind, --public-origin, --domain, --image, --jaeger-store, ' +
249
+ '--jaeger-port, --otlp-endpoint, --trace-url-template, --cache or --cache-port. The storage is fixed at ' +
250
+ 'the first start ' +
251
+ '(see the Docker guide).');
252
+ }
253
+ if (request.traceUrlTemplate !== undefined && request.traces !== undefined && request.traces !== 'external') {
254
+ throw new DockerUsageError('--trace-url-template goes with --traces external (with Jaeger the CLI sets it).');
255
+ }
256
+ if (request.traces === undefined &&
257
+ (request.jaegerStore !== undefined || request.jaegerPort !== undefined || request.otlpEndpoint !== undefined)) {
258
+ throw new DockerUsageError('--jaeger-store, --jaeger-port and --otlp-endpoint go with --traces.');
259
+ }
260
+ const files = await filesOf(ctx, instance);
261
+ const values = files.values;
262
+ const others = (await discoverInstances(ctx)).filter((other) => other.name !== instance.name);
263
+ const used = portsInUse(others);
264
+ if (request.bind !== undefined)
265
+ values.FOLIWAKE_BIND = request.bind;
266
+ if (request.port !== undefined) {
267
+ const port = parsePort(request.port);
268
+ if (port === null)
269
+ throw new DockerUsageError(`--port must be a port number (1–65535); got ${JSON.stringify(request.port)}.`);
270
+ const own = containerOf(instance, 'server')?.ports.some((published) => published.port === port) ?? false;
271
+ const problem = own ? null : await portProblem(ctx, used, values.FOLIWAKE_BIND ?? '127.0.0.1', port);
272
+ if (problem)
273
+ throw new DockerUsageError(`Port ${problem}.`);
274
+ const defaultOrigin = values.FOLIWAKE_PUBLIC_ORIGIN === `http://localhost:${values.FOLIWAKE_HOST_PORT}`;
275
+ if (request.publicOrigin === undefined && defaultOrigin) {
276
+ values.FOLIWAKE_PUBLIC_ORIGIN = `http://localhost:${port}`;
277
+ }
278
+ else if (request.publicOrigin === undefined) {
279
+ ctx.err(`The public address stays ${values.FOLIWAKE_PUBLIC_ORIGIN}; change it with --public-origin if it ` +
280
+ `named the old port.`);
281
+ }
282
+ values.FOLIWAKE_HOST_PORT = String(port);
283
+ }
284
+ if (request.publicOrigin !== undefined) {
285
+ const problem = originProblem(request.publicOrigin);
286
+ if (problem)
287
+ throw new DockerUsageError(problem);
288
+ values.FOLIWAKE_PUBLIC_ORIGIN = request.publicOrigin;
289
+ }
290
+ // The proxy trust follows the public address and the bind, as at install (whichever way they changed).
291
+ const bind = values.FOLIWAKE_BIND ?? '127.0.0.1';
292
+ if (values.FOLIWAKE_PUBLIC_ORIGIN)
293
+ values.FOLIWAKE_TRUST_PROXY = proxyTrustOf(ctx, values.FOLIWAKE_PUBLIC_ORIGIN, bind);
294
+ if (request.domain !== undefined)
295
+ values.FOLIWAKE_DOMAIN = request.domain;
296
+ if (request.image !== undefined)
297
+ values.FOLIWAKE_IMAGE = request.image;
298
+ if (request.traces !== undefined)
299
+ await applyTraces(ctx, instance, values, request, used);
300
+ if (request.cache !== undefined || request.cachePort !== undefined) {
301
+ await configureCache(ctx, instance, values, request, used);
302
+ }
303
+ else if (request.traceUrlTemplate !== undefined) {
304
+ if (values.FOLIWAKE_TRACES !== 'external') {
305
+ throw new DockerUsageError('--trace-url-template is for traces sent to your own collector (--traces external); with Jaeger the ' +
306
+ 'CLI sets it.');
307
+ }
308
+ applyTraceUrl(values, request.traceUrlTemplate);
309
+ }
310
+ await writeAndUp(ctx, instance, files);
311
+ const changed = Object.entries(request)
312
+ .filter(([, value]) => value !== undefined)
313
+ .map(([key]) => key);
314
+ ctx.out(`Reconfigured ${instance.name} (${changed.join(', ')}); the data volume is unchanged. ` +
315
+ `\`foliwake docker status ${instance.name}\` shows the result.`);
316
+ return 0;
317
+ }
@@ -0,0 +1,17 @@
1
+ import { Command } from '@oclif/core';
2
+ import type { DockerContext } from './docker/context.js';
3
+ import type { Instance } from './docker/instance.js';
4
+ export declare abstract class DockerCommand extends Command {
5
+ static baseFlags: {
6
+ interactive: import("@oclif/core/interfaces").BooleanFlag<boolean>;
7
+ };
8
+ /** The context of this run; the engine is checked (exit 2 when it does not answer or Compose is too old). */
9
+ protected dockerContext(interactive: boolean | undefined): Promise<DockerContext>;
10
+ /** The named instance, the only one, or the one chosen in a terminal. */
11
+ protected instance(ctx: DockerContext, name: string | undefined, options?: {
12
+ allowDataOnly?: boolean;
13
+ }): Promise<Instance>;
14
+ protected catch(error: Error & {
15
+ exitCode?: number;
16
+ }): Promise<unknown>;
17
+ }
@@ -0,0 +1,37 @@
1
+ // Base class of `foliwake docker …` (src/docker/): builds the context from this process (the real
2
+ // docker CLI, stdin/stdout, the environment), checks the engine and Compose first, and maps the
3
+ // errors to exit codes: a refusal 2, a Docker failure 1, a cancelled question 130.
4
+ // The commands drive this computer's own `docker` and `docker compose`; they need no engine checkout.
5
+ import { Command, Errors, Flags } from '@oclif/core';
6
+ export class DockerCommand extends Command {
7
+ static baseFlags = {
8
+ interactive: Flags.boolean({
9
+ allowNo: true,
10
+ description: 'ask for missing values (default: only when stdin and stdout are a terminal)',
11
+ helpGroup: 'GLOBAL',
12
+ }),
13
+ };
14
+ /** The context of this run; the engine is checked (exit 2 when it does not answer or Compose is too old). */
15
+ async dockerContext(interactive) {
16
+ const { processDockerContext } = await import('./docker/process-context.js');
17
+ const { checkEngine } = await import('./docker/engine.js');
18
+ const ctx = processDockerContext(interactive);
19
+ await checkEngine(ctx);
20
+ return ctx;
21
+ }
22
+ /** The named instance, the only one, or the one chosen in a terminal. */
23
+ async instance(ctx, name, options = {}) {
24
+ const { chooseInstance } = await import('./docker/instance.js');
25
+ return chooseInstance(ctx, name, options);
26
+ }
27
+ async catch(error) {
28
+ if (error instanceof Errors.CLIError || error instanceof Errors.ExitError)
29
+ return super.catch(error);
30
+ const { dockerExit } = await import('./docker/process-context.js');
31
+ const exit = dockerExit(error);
32
+ if (!exit)
33
+ throw error;
34
+ this.logToStderr(exit.message);
35
+ return this.exit(exit.code);
36
+ }
37
+ }
@@ -1,3 +1,4 @@
1
+ import type { SiteStatus } from './core-types.js';
1
2
  import { type ConnectIO } from './connect.js';
2
3
  export interface Connection {
3
4
  server: string;
@@ -14,6 +15,13 @@ export interface LastPreview {
14
15
  export declare const connectionFile: (cwd: string) => string;
15
16
  export declare const lastPreviewFile: (cwd: string) => string;
16
17
  export declare function readConnection(cwd: string): Promise<Connection | null>;
18
+ /** Remembers the preview `publish` takes when it is given none. */
19
+ export declare function saveLastPreview(cwd: string, last: LastPreview): Promise<void>;
20
+ /**
21
+ * How to publish the preview just built. With new site code (its code is not live), publishing also releases
22
+ * that code; `publish` asks for both, so no `--expect` command is offered that the server would refuse.
23
+ */
24
+ export declare function publishAdvice(status: SiteStatus, siteRelease: string, commit: string): string[];
17
25
  /** Pushes the pages and code, previews them, prints the address. Exit 0 previewed, 1 refused or failed. */
18
26
  export declare function previewProject({ cwd, env }: {
19
27
  cwd: string;
@@ -6,6 +6,7 @@ import { lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
6
6
  import path from 'node:path';
7
7
  import { COMMAND } from './settings.js';
8
8
  import { ConnectRefused, projectCommit, signedInTo } from './connect.js';
9
+ import { newCodeOf } from './publish-code.js';
9
10
  const C = COMMAND;
10
11
  const CONTENT = 'content';
11
12
  const PUSHED_FILE = /\.(md|png|jpe?g|gif|webp|avif)$/i;
@@ -63,6 +64,27 @@ async function waitFor(core, operation) {
63
64
  const { waitInSlices } = await import('./remote/wait-slices.js');
64
65
  return waitInSlices((sliceMs) => core.operations.wait({ site: operation.site, id: operation.id, until: 'commit', timeoutMs: sliceMs }), { until: 'commit', timeoutMs: WAIT_MS });
65
66
  }
67
+ /** Remembers the preview `publish` takes when it is given none. */
68
+ export async function saveLastPreview(cwd, last) {
69
+ await mkdir(path.dirname(lastPreviewFile(cwd)), { recursive: true });
70
+ await writeFile(lastPreviewFile(cwd), `${JSON.stringify(last, null, 2)}\n`);
71
+ }
72
+ /**
73
+ * How to publish the preview just built. With new site code (its code is not live), publishing also releases
74
+ * that code; `publish` asks for both, so no `--expect` command is offered that the server would refuse.
75
+ */
76
+ export function publishAdvice(status, siteRelease, commit) {
77
+ const newCode = newCodeOf(status, siteRelease, commit);
78
+ if (!newCode)
79
+ return [
80
+ `Publish it with \`${C} publish --expect ${siteRelease} <page-id>…\` on the server, or in the admin.`,
81
+ ];
82
+ return [
83
+ `This preview uses new site code (${newCode.code}, commit ${commit.slice(0, 7)}). Publishing it also ` +
84
+ 'releases that code, which changes every page of the site.',
85
+ `Publish both with \`${C} publish\` (it asks first), or in scripts \`${C} publish --yes --with-code\`.`,
86
+ ];
87
+ }
66
88
  const failure = (what, operation) => new ConnectRefused(`${what} did not succeed ` +
67
89
  `(${operation.state}${operation.error ? `: ${operation.error.code}: ${operation.error.message}` : ''}).`);
68
90
  /** Pushes the pages and code, previews them, prints the address. Exit 0 previewed, 1 refused or failed. */
@@ -108,17 +130,17 @@ export async function previewProject({ cwd, env }, io) {
108
130
  if (previewed.state !== 'succeeded' || !result?.siteRelease)
109
131
  throw failure('The preview', previewed);
110
132
  const previewUrl = (await core.sites.list()).sites.find((candidate) => candidate.id === connection.site)?.previewUrl ?? null;
111
- const last = {
133
+ await saveLastPreview(cwd, {
112
134
  server: connection.server,
113
135
  site: connection.site,
114
136
  siteRelease: result.siteRelease,
115
137
  commit: commit.commit,
116
138
  at: new Date().toISOString(),
117
- };
118
- await mkdir(path.dirname(lastPreviewFile(cwd)), { recursive: true });
119
- await writeFile(lastPreviewFile(cwd), `${JSON.stringify(last, null, 2)}\n`);
139
+ });
120
140
  io.out(`Preview ${result.siteRelease} is ready${previewUrl && previewUrl !== '-' ? `: ${previewUrl}` : ''}.`);
121
- io.out(`Publish it with \`${C} publish --expect ${result.siteRelease} <page-id>…\` on the server, or in the admin.`);
141
+ const built = await core.sites.status({ site: connection.site });
142
+ for (const line of publishAdvice(built, result.siteRelease, commit.commit))
143
+ io.out(line);
122
144
  return { exit: 0, siteRelease: result.siteRelease, previewUrl: previewUrl === '-' ? null : previewUrl };
123
145
  }
124
146
  catch (error) {
@@ -7,19 +7,20 @@ export interface PublishRequest {
7
7
  paths: string[];
8
8
  expect?: string | undefined;
9
9
  yes: boolean;
10
+ /** With `yes`: also release the new site code the preview was built with (never without it). */
11
+ withCode?: boolean;
10
12
  /** Asks the question in a terminal; null: no terminal. */
11
13
  confirm: ((question: string) => Promise<boolean>) | null;
12
14
  }
13
- export declare function publishProject(request: PublishRequest, io: ConnectIO): Promise<{
15
+ export interface PublishOutcome {
14
16
  exit: number;
15
17
  pages: string[];
16
18
  operation: Operation | null;
17
- }>;
18
- export declare function unpublishProject(request: PublishRequest, io: ConnectIO): Promise<{
19
- exit: number;
20
- pages: string[];
21
- operation: Operation | null;
22
- }>;
19
+ /** The code release that went live with the pages (`--with-code` or a yes to the question), if any. */
20
+ code: string | null;
21
+ }
22
+ export declare function publishProject(request: PublishRequest, io: ConnectIO): Promise<PublishOutcome>;
23
+ export declare function unpublishProject(request: PublishRequest, io: ConnectIO): Promise<PublishOutcome>;
23
24
  /** A yes/no question in a terminal (null when stdin or stdout is not one). */
24
25
  export declare function terminalConfirm(stdin: Readable & {
25
26
  isTTY?: boolean;