@oalo-ai/cli 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/man/oalo.1 +152 -4
- package/package.json +5 -3
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/skills/oalo/SKILL.md +39 -1
- package/src/commands/coord-bin.js +103 -0
- package/src/commands/db.js +336 -4
- package/src/commands/migrate.js +324 -0
- package/src/coord-release.json +25 -0
- package/src/help.js +77 -21
- package/src/index.js +18 -6
- package/src/migrate/plan.js +478 -0
- package/src/migrate/toml.js +242 -0
- package/src/migrate/yaml.js +179 -0
package/src/commands/db.js
CHANGED
|
@@ -1,7 +1,24 @@
|
|
|
1
|
-
import { createWriteStream, existsSync, rmSync, statSync } from "node:fs";
|
|
1
|
+
import { createReadStream, createWriteStream, existsSync, rmSync, statSync } from "node:fs";
|
|
2
|
+
import { Readable, Transform } from "node:stream";
|
|
3
|
+
import http from "node:http";
|
|
4
|
+
import https from "node:https";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
2
6
|
import { resolve as resolveConfig, controlPlane, HOW_TO_CONNECT } from "../config.js";
|
|
3
7
|
import { dim } from "../events.js";
|
|
4
8
|
|
|
9
|
+
const USAGE =
|
|
10
|
+
"usage: oalo db dump [--env dev|prod] [--out <file.sql>]\n" +
|
|
11
|
+
" oalo db restore <file> --env dev|prod [--schema <name>] [--check] [--yes]\n" +
|
|
12
|
+
" oalo db restore --from-env <VAR> --env dev|prod [--schema <name>] [--check] [--yes]";
|
|
13
|
+
|
|
14
|
+
/** `oalo db dump` and `oalo db restore`. */
|
|
15
|
+
export async function db(flags, rest, opts = {}) {
|
|
16
|
+
const sub = rest[1];
|
|
17
|
+
if (sub === "dump") return dump(flags, opts);
|
|
18
|
+
if (sub === "restore") return restore(flags, rest, opts);
|
|
19
|
+
return fail(USAGE, 2);
|
|
20
|
+
}
|
|
21
|
+
|
|
5
22
|
/**
|
|
6
23
|
* `oalo db dump [--env prod] [--out file.sql]`: all of an env's data as plain
|
|
7
24
|
* SQL (every app's own tables and the Oalo models, with their rows), so it can
|
|
@@ -9,9 +26,7 @@ import { dim } from "../events.js";
|
|
|
9
26
|
* with pg_dump's own "dump complete" line; a dump without it is cut off, and
|
|
10
27
|
* the file is removed rather than left looking whole.
|
|
11
28
|
*/
|
|
12
|
-
|
|
13
|
-
const sub = rest[1];
|
|
14
|
-
if (sub !== "dump") return fail("usage: oalo db dump [--env dev|prod] [--out <file.sql>]", 2);
|
|
29
|
+
async function dump(flags, opts) {
|
|
15
30
|
const env = flags.env === "dev" ? "dev" : "prod";
|
|
16
31
|
const { url, token } = controlPlane(resolveConfig(flags));
|
|
17
32
|
if (!url || !token) return fail(`oalo db dump needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2);
|
|
@@ -52,6 +67,323 @@ export async function db(flags, rest, opts = {}) {
|
|
|
52
67
|
console.log(`${out} ${dim(`${mb} MB, the ${env} data as SQL. Restore it with: psql "$DATABASE_URL" -f ${out}`)}`);
|
|
53
68
|
}
|
|
54
69
|
|
|
70
|
+
export const RESTORE_LIMIT = 10 * 1024 ** 3;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* `oalo db restore <file> --env dev|prod` or `--from-env VAR`: load an
|
|
74
|
+
* existing Postgres database (a dump file, or a URL the Base copies from) into
|
|
75
|
+
* one env of this Base. The reverse of dump. The URL comes from an environment
|
|
76
|
+
* variable, never a flag (shell history), and is never printed: only its host
|
|
77
|
+
* is named. A live restore asks first at a terminal and needs --yes without
|
|
78
|
+
* one; --check writes nothing, so it never asks.
|
|
79
|
+
*
|
|
80
|
+
* opts (for tests): fetch, env (the environment variables), isTTY (stdin is a
|
|
81
|
+
* terminal), confirm(question) -> answer, progress (stderr is a terminal).
|
|
82
|
+
*/
|
|
83
|
+
async function restore(flags, rest, opts) {
|
|
84
|
+
const vars = opts.env || process.env;
|
|
85
|
+
const env = flags.env;
|
|
86
|
+
if (env !== "dev" && env !== "prod") return fail("oalo db restore needs --env dev or --env prod: which env the data goes into.", 2);
|
|
87
|
+
|
|
88
|
+
const file = rest[2];
|
|
89
|
+
const fromEnv = flags["from-env"];
|
|
90
|
+
if (file && fromEnv !== undefined) return fail("pick one: a dump file, or --from-env VAR for a database URL.", 2);
|
|
91
|
+
if (!file && fromEnv === undefined) return fail(USAGE, 2);
|
|
92
|
+
if (flags.schema !== undefined && (typeof flags.schema !== "string" || !flags.schema)) return fail("--schema needs the source schema's name, like --schema public", 2);
|
|
93
|
+
const check = !!flags.check;
|
|
94
|
+
|
|
95
|
+
let source;
|
|
96
|
+
if (file) {
|
|
97
|
+
let st;
|
|
98
|
+
try {
|
|
99
|
+
st = statSync(file);
|
|
100
|
+
} catch {
|
|
101
|
+
return fail(`${file} doesn't exist.`, 2);
|
|
102
|
+
}
|
|
103
|
+
if (!st.isFile()) return fail(`${file} isn't a file. Give the dump file's path.`, 2);
|
|
104
|
+
if (st.size > RESTORE_LIMIT) return fail(`${file} is ${size(st.size)}, over the 10 GB a restore can take.`, 1);
|
|
105
|
+
source = { file, bytes: st.size };
|
|
106
|
+
} else {
|
|
107
|
+
const name = typeof fromEnv === "string" ? fromEnv : "";
|
|
108
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) return fail("--from-env takes the name of the environment variable that holds the database URL, like --from-env SOURCE_DATABASE_URL", 2);
|
|
109
|
+
const value = (vars[name] || "").trim();
|
|
110
|
+
if (!value) return fail(`${name} is empty or not set. Put the database URL in it, then run this again.`, 2);
|
|
111
|
+
const host = pgHost(value);
|
|
112
|
+
if (!host) return fail(`${name} doesn't hold a database URL. It needs one that starts with postgres:// or postgresql:// and names a host.`, 2);
|
|
113
|
+
source = { url: value, host };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const { url, token } = controlPlane(resolveConfig(flags));
|
|
117
|
+
if (!url || !token) return fail(`oalo db restore needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2);
|
|
118
|
+
|
|
119
|
+
// A live restore asks first. --check writes nothing, so it never does.
|
|
120
|
+
if (env === "prod" && !check && !flags.yes) {
|
|
121
|
+
const tty = opts.isTTY ?? process.stdin.isTTY;
|
|
122
|
+
if (!tty) return fail("restoring into prod needs --yes when there's no terminal to ask at. Run it with --check first, then add --yes.", 2);
|
|
123
|
+
const question = source.file ? `Restore ${size(source.bytes)} into prod? [y/N] ` : `Restore the database at ${source.host} into prod? [y/N] `;
|
|
124
|
+
const answer = await (opts.confirm || ask)(question);
|
|
125
|
+
if (!/^(y|yes)$/i.test(String(answer || "").trim())) return fail("Nothing was restored.", 1);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const scrub = scrubber(source.url);
|
|
129
|
+
const q = new URLSearchParams({ env, ...(typeof flags.schema === "string" ? { schema: flags.schema } : {}), ...(check ? { check: "true" } : {}) });
|
|
130
|
+
const endpoint = `${url.replace(/\/$/, "")}/api/cli/v1/db/restore?${q}`;
|
|
131
|
+
console.error(dim(`${check ? "checking" : "restoring"} ${source.file ? `${source.file} (${size(source.bytes)})` : `the database at ${source.host}`} ${check ? "against" : "into"} ${env} on ${url}`));
|
|
132
|
+
|
|
133
|
+
let res;
|
|
134
|
+
let upload = null;
|
|
135
|
+
try {
|
|
136
|
+
if (source.file) {
|
|
137
|
+
upload = uploadBody(source, opts.progress ?? process.stderr.isTTY);
|
|
138
|
+
const headers = { authorization: `Bearer ${token}`, "content-type": "application/octet-stream", "content-length": String(source.bytes) };
|
|
139
|
+
res = opts.fetch
|
|
140
|
+
? await opts.fetch(endpoint, { method: "POST", headers, body: upload.web(), duplex: "half" })
|
|
141
|
+
: await sendFile(endpoint, headers, upload.stream);
|
|
142
|
+
} else {
|
|
143
|
+
res = await (opts.fetch || fetch)(endpoint, {
|
|
144
|
+
method: "POST",
|
|
145
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
|
146
|
+
body: JSON.stringify({ secret_url: source.url }),
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
} catch (e) {
|
|
150
|
+
upload?.stop();
|
|
151
|
+
const why = scrub(e.cause?.message || e.message);
|
|
152
|
+
return fail(`${upload ? `the upload to ${url} didn't go through` : `could not reach ${url}`} (${why}). Nothing was restored.`, 1);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// A refusal can come before the upload is done: read it, then stop sending.
|
|
156
|
+
if (!res.ok) {
|
|
157
|
+
upload?.pause();
|
|
158
|
+
const body = await res.json().catch(() => ({}));
|
|
159
|
+
upload?.stop();
|
|
160
|
+
res.close?.();
|
|
161
|
+
return fail(scrub(body?.error?.message || `the restore was refused (HTTP ${res.status})`), 1);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
let last = null;
|
|
165
|
+
try {
|
|
166
|
+
last = await follow(res, (m) => (upload ? upload.note(() => console.error(dim(` ${scrub(m)}`))) : console.error(dim(` ${scrub(m)}`))));
|
|
167
|
+
} catch {
|
|
168
|
+
last = null;
|
|
169
|
+
} finally {
|
|
170
|
+
upload?.stop();
|
|
171
|
+
res.close?.();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (!last) {
|
|
175
|
+
return fail("the connection closed before the restore finished. A restore that fails leaves the env as it was; run it again with --check to see where it stands.", 1);
|
|
176
|
+
}
|
|
177
|
+
if (last.error) {
|
|
178
|
+
console.error(`restore failed: ${scrub(last.error.message || last.error.code || "unknown error")}`);
|
|
179
|
+
const names = last.error.conflicts || [];
|
|
180
|
+
if (names.length) console.error(dim(` already in ${env}: ${names.join(", ")}`));
|
|
181
|
+
process.exitCode = 1;
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
summary(last, env, scrub);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The summary of a finished restore, or of a check. */
|
|
188
|
+
function summary(r, env, scrub) {
|
|
189
|
+
if (r.message) console.log(scrub(r.message));
|
|
190
|
+
const tables = r.tables || [];
|
|
191
|
+
const w = Math.max(0, ...tables.map((t) => String(t.name).length));
|
|
192
|
+
for (const t of tables) {
|
|
193
|
+
const rows = `${Number(t.rows || 0).toLocaleString("en-US")} ${t.rows === 1 ? "row" : "rows"}`;
|
|
194
|
+
console.log(` ${String(t.name).padEnd(w)} ${dim(`${rows}, ${size(t.bytes || 0)}`)}`);
|
|
195
|
+
}
|
|
196
|
+
if (r.extensions?.length) console.log(dim(`extensions: ${r.extensions.join(", ")}`));
|
|
197
|
+
if (r.skipped?.length) console.log(dim(`skipped: ${r.skipped.join(", ")}`));
|
|
198
|
+
for (const x of r.warnings || []) console.log(`warning: ${scrub(x)}`);
|
|
199
|
+
if (r.owner) console.log(dim(`owner: ${r.owner}, the app's database login, so its release: migrations can alter them`));
|
|
200
|
+
if (r.check) {
|
|
201
|
+
const names = r.conflicts || [];
|
|
202
|
+
if (names.length) {
|
|
203
|
+
console.log(`already in ${env}, so the restore would be refused: ${names.join(", ")}`);
|
|
204
|
+
process.exitCode = 1;
|
|
205
|
+
}
|
|
206
|
+
console.log(dim("Nothing was written."));
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Print each progress message; return the final line (done or error), or null. */
|
|
211
|
+
async function follow(res, print) {
|
|
212
|
+
const decoder = new TextDecoder();
|
|
213
|
+
let buf = "";
|
|
214
|
+
let last = null;
|
|
215
|
+
const take = (raw) => {
|
|
216
|
+
raw = raw.trim();
|
|
217
|
+
if (!raw) return;
|
|
218
|
+
let msg;
|
|
219
|
+
try {
|
|
220
|
+
msg = JSON.parse(raw);
|
|
221
|
+
} catch {
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
if (msg.done || msg.error) last = msg;
|
|
225
|
+
else if (msg.phase !== "waiting" && msg.message) print(msg.message);
|
|
226
|
+
};
|
|
227
|
+
for await (const part of res.body) {
|
|
228
|
+
buf += decoder.decode(part, { stream: true });
|
|
229
|
+
let i;
|
|
230
|
+
while ((i = buf.indexOf("\n")) >= 0) {
|
|
231
|
+
take(buf.slice(0, i));
|
|
232
|
+
buf = buf.slice(i + 1);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
take(buf + decoder.decode());
|
|
236
|
+
return last;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* The file as a request body, read as it's sent and counted. At a terminal one
|
|
241
|
+
* stderr line shows how far it got; progress messages print above it.
|
|
242
|
+
*/
|
|
243
|
+
function uploadBody({ file, bytes }, tty) {
|
|
244
|
+
const total = size(bytes);
|
|
245
|
+
let sent = 0;
|
|
246
|
+
let shown = "";
|
|
247
|
+
let active = false;
|
|
248
|
+
let done = false;
|
|
249
|
+
const clear = () => active && !done && process.stderr.write("\r\x1b[K");
|
|
250
|
+
const draw = (force) => {
|
|
251
|
+
if (!tty || done) return;
|
|
252
|
+
const line = `uploading ${size(sent)} of ${total}`;
|
|
253
|
+
if (line === shown && !force) return;
|
|
254
|
+
shown = line;
|
|
255
|
+
active = true;
|
|
256
|
+
process.stderr.write(`\r\x1b[K${dim(line)}`);
|
|
257
|
+
};
|
|
258
|
+
const src = createReadStream(file);
|
|
259
|
+
const stream = new Transform({
|
|
260
|
+
transform(chunk, _enc, cb) {
|
|
261
|
+
sent += chunk.length;
|
|
262
|
+
draw();
|
|
263
|
+
cb(null, chunk);
|
|
264
|
+
},
|
|
265
|
+
flush(cb) {
|
|
266
|
+
if (active && !done) process.stderr.write(`\r\x1b[K${dim(`uploaded ${total}`)}\n`);
|
|
267
|
+
done = true;
|
|
268
|
+
cb();
|
|
269
|
+
},
|
|
270
|
+
});
|
|
271
|
+
src.on("error", (e) => stream.destroy(e));
|
|
272
|
+
src.pipe(stream);
|
|
273
|
+
if (!tty) console.error(dim(`uploading ${total}`));
|
|
274
|
+
return {
|
|
275
|
+
stream,
|
|
276
|
+
web: () => Readable.toWeb(stream),
|
|
277
|
+
/** Print a line without breaking the progress line. */
|
|
278
|
+
note(print) {
|
|
279
|
+
clear();
|
|
280
|
+
print();
|
|
281
|
+
if (active) draw(true);
|
|
282
|
+
},
|
|
283
|
+
pause: () => src.unpipe(stream),
|
|
284
|
+
/** Stop reading the file (a refusal, an error, or the end). */
|
|
285
|
+
stop() {
|
|
286
|
+
clear();
|
|
287
|
+
done = true;
|
|
288
|
+
src.destroy();
|
|
289
|
+
stream.destroy();
|
|
290
|
+
},
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* POST the file with node:http and `expect: 100-continue`: the body goes once
|
|
296
|
+
* the server says to (or after CONTINUE_WAIT_MS, for one that never does), so
|
|
297
|
+
* a refusal made from the headers (too big, not enough disk) arrives before
|
|
298
|
+
* any bytes are sent. fetch can't wait like this, and when a server refuses
|
|
299
|
+
* mid-upload and closes, it fails with EPIPE and the server's message is lost.
|
|
300
|
+
* The reply is returned as a web Response; `close()` ends the request.
|
|
301
|
+
*/
|
|
302
|
+
export const CONTINUE_WAIT_MS = 3000;
|
|
303
|
+
|
|
304
|
+
function sendFile(endpoint, headers, body) {
|
|
305
|
+
return new Promise((resolve, reject) => {
|
|
306
|
+
const u = new URL(endpoint);
|
|
307
|
+
let replied = false;
|
|
308
|
+
let started = false;
|
|
309
|
+
const req = (u.protocol === "https:" ? https : http).request(u, { method: "POST", headers: { ...headers, expect: "100-continue" } });
|
|
310
|
+
const start = () => {
|
|
311
|
+
if (started || replied) return;
|
|
312
|
+
started = true;
|
|
313
|
+
body.pipe(req);
|
|
314
|
+
};
|
|
315
|
+
const timer = setTimeout(start, CONTINUE_WAIT_MS);
|
|
316
|
+
req.on("continue", () => (clearTimeout(timer), start()));
|
|
317
|
+
req.on("response", (incoming) => {
|
|
318
|
+
replied = true;
|
|
319
|
+
clearTimeout(timer);
|
|
320
|
+
const h = new Headers();
|
|
321
|
+
for (const [k, v] of Object.entries(incoming.headers)) h.set(k, Array.isArray(v) ? v.join(", ") : String(v));
|
|
322
|
+
const res = new Response(Readable.toWeb(incoming), { status: incoming.statusCode, headers: h });
|
|
323
|
+
res.close = () => req.destroy();
|
|
324
|
+
resolve(res);
|
|
325
|
+
});
|
|
326
|
+
// After the reply has come, a write error (the server stopped reading) is expected.
|
|
327
|
+
req.on("error", (e) => {
|
|
328
|
+
clearTimeout(timer);
|
|
329
|
+
if (!replied) reject(e);
|
|
330
|
+
});
|
|
331
|
+
body.on("error", (e) => req.destroy(e));
|
|
332
|
+
req.flushHeaders();
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** The host of a postgres:// or postgresql:// URL, or null when it isn't one. */
|
|
337
|
+
export function pgHost(value) {
|
|
338
|
+
if (!/^postgres(ql)?:\/\//i.test(value)) return null;
|
|
339
|
+
try {
|
|
340
|
+
return new URL(value).hostname || null;
|
|
341
|
+
} catch {
|
|
342
|
+
return null;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Removes a database URL's credentials from text the server or the network
|
|
348
|
+
* stack wrote, before it's printed: the URL itself, its password, and the
|
|
349
|
+
* user:password part of any postgres URL.
|
|
350
|
+
*/
|
|
351
|
+
function scrubber(secret) {
|
|
352
|
+
let password = "";
|
|
353
|
+
let host = "";
|
|
354
|
+
if (secret) {
|
|
355
|
+
try {
|
|
356
|
+
const u = new URL(secret);
|
|
357
|
+
password = decodeURIComponent(u.password || "");
|
|
358
|
+
host = u.hostname;
|
|
359
|
+
} catch {}
|
|
360
|
+
}
|
|
361
|
+
return (text) => {
|
|
362
|
+
let s = String(text ?? "");
|
|
363
|
+
if (secret) s = s.split(secret).join(`the database at ${host}`);
|
|
364
|
+
s = s.replace(/(postgres(?:ql)?:\/\/)[^\s@/"']*@/gi, "$1***@");
|
|
365
|
+
if (password.length >= 4) s = s.split(password).join("***");
|
|
366
|
+
return s;
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** Bytes as people read them: 1.2 GB, 340 MB, 12 KB. */
|
|
371
|
+
export function size(n) {
|
|
372
|
+
if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(1)} GB`;
|
|
373
|
+
if (n >= 1024 ** 2) return `${n >= 10 * 1024 ** 2 ? Math.round(n / 1024 ** 2) : (n / 1024 ** 2).toFixed(1)} MB`;
|
|
374
|
+
if (n >= 1024) return `${Math.round(n / 1024)} KB`;
|
|
375
|
+
return `${n} B`;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
async function ask(question) {
|
|
379
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
380
|
+
try {
|
|
381
|
+
return await rl.question(question);
|
|
382
|
+
} finally {
|
|
383
|
+
rl.close();
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
55
387
|
function fail(message, code) {
|
|
56
388
|
console.error(message);
|
|
57
389
|
process.exitCode = code;
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { OaloChannel } from "../channel.js";
|
|
5
|
+
import { resolve as resolveConfig, controlPlane, HOW_TO_CONNECT } from "../config.js";
|
|
6
|
+
import { requireFeature } from "../server.js";
|
|
7
|
+
import { dim } from "../events.js";
|
|
8
|
+
import { buildPlan, PLATFORMS } from "../migrate/plan.js";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* `oalo migrate <heroku|railway|render|fly|primcloud>`: what an app on another
|
|
12
|
+
* platform becomes on Oalo, from the repo's files and that platform's own CLI.
|
|
13
|
+
*
|
|
14
|
+
* oalo migrate heroku [--from-app shop] the plan; nothing changes
|
|
15
|
+
* oalo migrate heroku --apply write the Procfile and .oalo/app.json,
|
|
16
|
+
* and set the variables on the live app
|
|
17
|
+
*
|
|
18
|
+
* It reads fly.toml, railway.json/railway.toml, render.yaml, app.json and the
|
|
19
|
+
* Procfile; asks the platform's CLI for variables (Heroku, Railway) or secret
|
|
20
|
+
* names (Fly) and dyno sizes (Heroku); drops what Oalo or the old platform
|
|
21
|
+
* sets, renames DATABASE_URL to EXTERNAL_DATABASE_URL, and says what doesn't
|
|
22
|
+
* carry over. Values are never printed or written to a file: they go straight
|
|
23
|
+
* to the app's prod variables. An existing Procfile is never overwritten, and
|
|
24
|
+
* .oalo/app.json only gains keys it lacks.
|
|
25
|
+
*/
|
|
26
|
+
export async function migrate(flags, rest, opts = {}) {
|
|
27
|
+
const platform = rest[1];
|
|
28
|
+
if (!platform || !PLATFORMS[platform]) {
|
|
29
|
+
return fail(`usage: oalo migrate <${Object.keys(PLATFORMS).join("|")}> [--from-app <name>] [--env-file <file>] [--apply]`, 2);
|
|
30
|
+
}
|
|
31
|
+
const dir = opts.cwd || process.cwd();
|
|
32
|
+
const run = opts.exec || execCli;
|
|
33
|
+
const connect = opts.channel || ((o) => new OaloChannel(o));
|
|
34
|
+
const fromApp = typeof flags["from-app"] === "string" ? flags["from-app"] : null;
|
|
35
|
+
|
|
36
|
+
let envFile = null;
|
|
37
|
+
if (typeof flags["env-file"] === "string") {
|
|
38
|
+
try {
|
|
39
|
+
envFile = readFileSync(flags["env-file"], "utf8");
|
|
40
|
+
} catch (e) {
|
|
41
|
+
return fail(`can't read ${flags["env-file"]}: ${e.code || e.message}`, 2);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const files = readFiles(dir);
|
|
46
|
+
const remote = flags["no-cli"] ? { notes: [] } : await askPlatform(platform, fromApp, files, run);
|
|
47
|
+
|
|
48
|
+
let plan;
|
|
49
|
+
try {
|
|
50
|
+
plan = buildPlan(platform, { files, remote, envFile, fromApp });
|
|
51
|
+
} catch (e) {
|
|
52
|
+
return fail(e.message, 1);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const cfg = resolveConfig(flags, dir);
|
|
56
|
+
const app = typeof flags.app === "string" ? flags.app : cfg.appId;
|
|
57
|
+
|
|
58
|
+
if (!flags.apply) {
|
|
59
|
+
if (flags.json) return void console.log(JSON.stringify(publicPlan(plan, app), null, 2));
|
|
60
|
+
printPlan(plan, app, dir);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// --apply: files first (never overwriting), then the variables.
|
|
65
|
+
const wrote = [];
|
|
66
|
+
if (plan.procfile.action === "write" && !existsSync(join(dir, "Procfile"))) {
|
|
67
|
+
writeFileSync(join(dir, "Procfile"), plan.procfile.text);
|
|
68
|
+
wrote.push("Procfile");
|
|
69
|
+
}
|
|
70
|
+
if (plan.manifest.action === "write" || plan.manifest.action === "merge") {
|
|
71
|
+
mkdirSync(join(dir, ".oalo"), { recursive: true });
|
|
72
|
+
writeFileSync(join(dir, ".oalo", "app.json"), plan.manifest.text);
|
|
73
|
+
wrote.push(".oalo/app.json");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let varsResult = null;
|
|
77
|
+
if (plan.vars.set.length) {
|
|
78
|
+
if (!app) {
|
|
79
|
+
varsResult = { skipped: "no app" };
|
|
80
|
+
} else {
|
|
81
|
+
const { url, token } = controlPlane(cfg);
|
|
82
|
+
if (!url || !token) return fail(`setting the variables needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2);
|
|
83
|
+
try {
|
|
84
|
+
await requireFeature(url, "env", "oalo migrate");
|
|
85
|
+
} catch (e) {
|
|
86
|
+
return fail(e.message, 1);
|
|
87
|
+
}
|
|
88
|
+
const ch = connect({ url, token });
|
|
89
|
+
try {
|
|
90
|
+
await ch.connect();
|
|
91
|
+
const r = await ch.call("env:set", {
|
|
92
|
+
app,
|
|
93
|
+
env: "prod",
|
|
94
|
+
vars: plan.vars.set.map(({ name, value }) => ({ name, value })),
|
|
95
|
+
restart: false,
|
|
96
|
+
});
|
|
97
|
+
varsResult = { app: r.app, saved: r.saved.length, relaunch: !!(r.relaunching || r.next_release) };
|
|
98
|
+
} catch (e) {
|
|
99
|
+
return fail(`the files are written, but the variables weren't set: ${e.message}`, 1);
|
|
100
|
+
} finally {
|
|
101
|
+
ch.close();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (flags.json) return void console.log(JSON.stringify({ ...publicPlan(plan, app), wrote, variables: varsResult }, null, 2));
|
|
107
|
+
|
|
108
|
+
console.log(`Moving from ${plan.label}.`);
|
|
109
|
+
if (wrote.length) console.log(`wrote ${wrote.join(" and ")}: review them, then commit`);
|
|
110
|
+
else console.log(dim("no files to write"));
|
|
111
|
+
if (varsResult?.saved != null) {
|
|
112
|
+
console.log(`set ${varsResult.saved} variable${varsResult.saved === 1 ? "" : "s"} on ${varsResult.app} (prod)`);
|
|
113
|
+
if (varsResult.relaunch) console.log(dim("the live app gets them at its next release"));
|
|
114
|
+
} else if (varsResult?.skipped) {
|
|
115
|
+
console.log(`variables not set yet: this folder isn't linked to an Oalo app. After \`oalo deploy --new\`, run \`oalo migrate ${platform} --apply\` again${fromApp ? ` --from-app ${fromApp}` : ""}${flags["env-file"] ? ` --env-file ${flags["env-file"]}` : ""}.`);
|
|
116
|
+
}
|
|
117
|
+
printNeeds(plan);
|
|
118
|
+
printNext(plan, app, platform, true);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// ── reading ───────────────────────────────────────────────────────────
|
|
122
|
+
|
|
123
|
+
const LOCKFILES = ["package-lock.json", "yarn.lock", "pnpm-lock.yaml", "bun.lock", "bun.lockb", "npm-shrinkwrap.json"];
|
|
124
|
+
|
|
125
|
+
export function readFiles(dir) {
|
|
126
|
+
const read = (name) => {
|
|
127
|
+
try {
|
|
128
|
+
return readFileSync(join(dir, name), "utf8");
|
|
129
|
+
} catch {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
return {
|
|
134
|
+
procfile: read("Procfile"),
|
|
135
|
+
appJson: read("app.json"),
|
|
136
|
+
flyToml: read("fly.toml"),
|
|
137
|
+
railwayJson: read("railway.json"),
|
|
138
|
+
railwayToml: read("railway.toml"),
|
|
139
|
+
renderYaml: read("render.yaml"),
|
|
140
|
+
dockerfile: read("Dockerfile"),
|
|
141
|
+
aptfile: existsSync(join(dir, "Aptfile")),
|
|
142
|
+
packageJson: existsSync(join(dir, "package.json")),
|
|
143
|
+
lockfile: LOCKFILES.some((f) => existsSync(join(dir, f))),
|
|
144
|
+
oaloAppJson: read(join(".oalo", "app.json")),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** What the platform's own CLI can tell: variables, secret names, dyno sizes. */
|
|
149
|
+
async function askPlatform(platform, fromApp, files, run) {
|
|
150
|
+
const notes = [];
|
|
151
|
+
const out = { notes, vars: null, secretNames: null, dynos: null };
|
|
152
|
+
const flyApp = () => {
|
|
153
|
+
if (fromApp) return fromApp;
|
|
154
|
+
const m = files.flyToml?.match(/^\s*app\s*=\s*["']([^"']+)["']/m);
|
|
155
|
+
return m ? m[1] : null;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
if (platform === "heroku") {
|
|
159
|
+
const a = fromApp ? ["-a", fromApp] : [];
|
|
160
|
+
const cfg = await run("heroku", ["config", "--json", ...a]);
|
|
161
|
+
if (cfg.ok) out.vars = asObject(cfg.stdout);
|
|
162
|
+
else notes.push(cliNote("heroku", cfg, "config vars", "heroku config --shell"));
|
|
163
|
+
const ps = await run("heroku", ["ps", "--json", ...a]);
|
|
164
|
+
if (ps.ok) out.dynos = asArray(ps.stdout).map((d) => ({ type: d.type, size: d.size }));
|
|
165
|
+
} else if (platform === "railway") {
|
|
166
|
+
const a = fromApp ? ["--service", fromApp] : [];
|
|
167
|
+
const r = await run("railway", ["variable", "list", "--json", ...a]);
|
|
168
|
+
if (r.ok) out.vars = asObject(r.stdout);
|
|
169
|
+
else notes.push(cliNote("railway", r, "variables", "railway variable list --kv"));
|
|
170
|
+
} else if (platform === "fly") {
|
|
171
|
+
const name = flyApp();
|
|
172
|
+
const a = name ? ["-a", name] : [];
|
|
173
|
+
let r = await run("fly", ["secrets", "list", "--json", ...a]);
|
|
174
|
+
if (!r.ok && r.missing) r = await run("flyctl", ["secrets", "list", "--json", ...a]);
|
|
175
|
+
if (r.ok) out.secretNames = asArray(r.stdout).map((s) => s.Name || s.name).filter(Boolean);
|
|
176
|
+
else notes.push(cliNote("fly", r, "secret names", "fly secrets list"));
|
|
177
|
+
}
|
|
178
|
+
return out;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function cliNote(cli, r, what, manual) {
|
|
182
|
+
if (r.missing) return `The ${cli} CLI isn't installed here, so its ${what} weren't read. Install it and sign in, or run \`${manual}\` elsewhere, save the values to a .env file and pass --env-file.`;
|
|
183
|
+
const why = firstLine(r.stderr) || "it failed";
|
|
184
|
+
return `\`${cli}\` couldn't list the ${what} (${why}). Sign in and link the project, or pass --from-app, or put them in a .env file and pass --env-file.`;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function execCli(cmd, args) {
|
|
188
|
+
return new Promise((resolve) => {
|
|
189
|
+
execFile(cmd, args, { timeout: 30_000, maxBuffer: 8 * 1024 * 1024, env: process.env }, (err, stdout, stderr) => {
|
|
190
|
+
if (err && err.code === "ENOENT") return resolve({ ok: false, missing: true, stdout: "", stderr: "" });
|
|
191
|
+
resolve({ ok: !err, missing: false, stdout: String(stdout || ""), stderr: String(stderr || "") });
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function asObject(text) {
|
|
197
|
+
try {
|
|
198
|
+
const j = JSON.parse(text);
|
|
199
|
+
if (Array.isArray(j)) return Object.fromEntries(j.map((x) => [x.name ?? x.key, x.value]).filter(([k]) => k));
|
|
200
|
+
return j && typeof j === "object" ? j : {};
|
|
201
|
+
} catch {
|
|
202
|
+
return {};
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function asArray(text) {
|
|
207
|
+
try {
|
|
208
|
+
const j = JSON.parse(text);
|
|
209
|
+
return Array.isArray(j) ? j : [];
|
|
210
|
+
} catch {
|
|
211
|
+
return [];
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Only a short reason, and never anything that looks like a URL with a password.
|
|
216
|
+
function firstLine(s) {
|
|
217
|
+
const line = String(s || "").split(/\r?\n/).map((x) => x.trim()).find(Boolean) || "";
|
|
218
|
+
return line.replace(/\/\/[^\s/@]+@/g, "//***@").slice(0, 160);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ── printing ──────────────────────────────────────────────────────────
|
|
222
|
+
|
|
223
|
+
/** The plan without any values: what --json prints. */
|
|
224
|
+
function publicPlan(plan, app) {
|
|
225
|
+
return {
|
|
226
|
+
platform: plan.platform,
|
|
227
|
+
app: app || null,
|
|
228
|
+
procfile: { action: plan.procfile.action, lines: plan.procfile.lines.map(([name, command]) => ({ name, command })) },
|
|
229
|
+
manifest: { action: plan.manifest.action, sizes: plan.manifest.sizes, health: plan.manifest.health },
|
|
230
|
+
variables: {
|
|
231
|
+
set: plan.vars.set.map((v) => ({ name: v.name, from: v.from })),
|
|
232
|
+
renamed: plan.vars.renamed,
|
|
233
|
+
dropped: plan.vars.dropped,
|
|
234
|
+
missing: plan.vars.missing,
|
|
235
|
+
},
|
|
236
|
+
needs: plan.warnings,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function printPlan(plan, app, dir) {
|
|
241
|
+
console.log(`Moving from ${plan.label}. Nothing changes until you add --apply.\n`);
|
|
242
|
+
|
|
243
|
+
const pf = plan.procfile;
|
|
244
|
+
if (pf.action === "keep") console.log(`Procfile keep yours (${pf.lines.map(([n]) => n).join(", ") || "no lines"})`);
|
|
245
|
+
else if (pf.action === "write") {
|
|
246
|
+
console.log("Procfile write:");
|
|
247
|
+
for (const [n, c] of pf.lines) console.log(` ${n}: ${c}`);
|
|
248
|
+
} else console.log(`Procfile none ${dim("(web starts the usual way for its language, or from the Dockerfile)")}`);
|
|
249
|
+
|
|
250
|
+
const m = plan.manifest;
|
|
251
|
+
if (m.action === "write" || m.action === "merge") {
|
|
252
|
+
const parts = Object.entries(m.sizes).map(([p, s]) => `${p} ${s.size} (${s.from})`);
|
|
253
|
+
if (m.health) parts.push(`health ${m.health}`);
|
|
254
|
+
console.log(`.oalo/app.json ${m.action === "merge" ? "add" : "write"}: ${parts.join(", ")}`);
|
|
255
|
+
} else {
|
|
256
|
+
console.log(`.oalo/app.json ${m.action === "keep" ? "keep yours" : "none"} ${dim("(every process gets small)")}`);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const v = plan.vars;
|
|
260
|
+
console.log("");
|
|
261
|
+
if (v.set.length) {
|
|
262
|
+
console.log(`Variables ${v.set.length} to set on the live app${app ? ` (${app})` : ""}, values not shown:`);
|
|
263
|
+
console.log(wrap(v.set.map((x) => x.name).join(", "), 18, 0));
|
|
264
|
+
} else {
|
|
265
|
+
console.log("Variables none read");
|
|
266
|
+
}
|
|
267
|
+
for (const r of v.renamed) console.log(` ${r.to} from ${r.from} ${dim("(on Oalo, DATABASE_URL is your Base's own Postgres)")}`);
|
|
268
|
+
if (v.dropped.length) console.log(dim(` left out: ${v.dropped.map((d) => `${d.name} (${d.why})`).join(", ")}`));
|
|
269
|
+
if (v.missing.length) {
|
|
270
|
+
console.log(" still needed, values not available here:");
|
|
271
|
+
for (const x of v.missing) console.log(` ${x.name}: ${x.why}`);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
printNeeds(plan);
|
|
275
|
+
printNext(plan, app, plan.platform, false);
|
|
276
|
+
if (!existsSync(join(dir, ".git"))) console.log(dim("\nThis folder isn't a git repo: oalo deploy --new sends commits, so run this in the app's repo."));
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function printNeeds(plan) {
|
|
280
|
+
if (!plan.warnings.length) return;
|
|
281
|
+
console.log("\nNeeds you");
|
|
282
|
+
for (const w of plan.warnings) console.log(wrap(`- ${w}`, 2, 2));
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function printNext(plan, app, platform, applied) {
|
|
286
|
+
console.log("\nNext");
|
|
287
|
+
const steps = [];
|
|
288
|
+
const files = [
|
|
289
|
+
...(plan.procfile.action === "write" ? ["Procfile"] : []),
|
|
290
|
+
...(["write", "merge"].includes(plan.manifest.action) ? [".oalo/app.json"] : []),
|
|
291
|
+
];
|
|
292
|
+
const later = !app && plan.vars.set.length;
|
|
293
|
+
if (!applied) steps.push(`oalo migrate ${platform} --apply${later ? " (writes the files; the variables wait until the app exists)" : ""}`);
|
|
294
|
+
if (files.length) steps.push(`git add ${files.join(" ")} && git commit -m "Move to Oalo"`);
|
|
295
|
+
if (!app) steps.push("oalo deploy --new");
|
|
296
|
+
if (later) steps.push(`oalo migrate ${platform} --apply (now it sets the variables)`);
|
|
297
|
+
if (plan.vars.missing.length) steps.push("oalo env set NAME --secret --env prod (for each one still needed)");
|
|
298
|
+
steps.push("oalo env set NAME --env dev (test values for the preview)");
|
|
299
|
+
steps.push("your data: keep the database and set EXTERNAL_DATABASE_URL, or copy it in with oalo db restore");
|
|
300
|
+
steps.push("oalo deploy --env prod");
|
|
301
|
+
steps.push("move the domain: the app's Custom Domain panel in the dashboard");
|
|
302
|
+
steps.forEach((s, i) => console.log(` ${i + 1}. ${s}`));
|
|
303
|
+
console.log(dim(`\nThe whole walk-through: oalo docs migrating-from-${platform}`));
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function wrap(text, indent, hang = indent) {
|
|
307
|
+
const width = Math.max(40, (process.stdout.columns || 100) - 2);
|
|
308
|
+
const words = text.split(" ");
|
|
309
|
+
const lines = [];
|
|
310
|
+
let line = " ".repeat(indent);
|
|
311
|
+
for (const w of words) {
|
|
312
|
+
if (line.trim() && line.length + 1 + w.length > width) {
|
|
313
|
+
lines.push(line);
|
|
314
|
+
line = " ".repeat(indent + hang) + w;
|
|
315
|
+
} else line += (line.trim() ? " " : "") + w;
|
|
316
|
+
}
|
|
317
|
+
if (line.trim()) lines.push(line);
|
|
318
|
+
return lines.join("\n");
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function fail(message, code) {
|
|
322
|
+
console.error(message);
|
|
323
|
+
process.exitCode = code;
|
|
324
|
+
}
|