@kaynooo/cli-wt 0.1.1 → 0.1.7
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/README.md +17 -10
- package/dist/cli-0gbs87r4.js +313 -0
- package/dist/cli-1nyesy1b.js +674 -0
- package/dist/cli-4g5ehhgn.js +251 -0
- package/dist/cli-6ybxw5sc.js +97 -0
- package/dist/cli-dmkfxdbr.js +153 -0
- package/dist/cli-dmzvmpge.js +106 -0
- package/dist/cli-e2h20nyy.js +36 -0
- package/dist/cli-j82fak6j.js +69 -0
- package/dist/cli-k4471y24.js +779 -0
- package/dist/cli-kek450vq.js +519 -0
- package/dist/cli-n5rt07v7.js +105 -0
- package/dist/cli-pkvw2k4x.js +37 -0
- package/dist/cli-w4w36hng.js +67 -0
- package/dist/cli.js +238 -2576
- package/dist/commands-jtnbchtb.js +222 -0
- package/dist/init-4ynjrztr.js +166 -0
- package/dist/list-js6drtvg.js +88 -0
- package/dist/print-q6qaqg22.js +77 -0
- package/dist/prompt-y71tp3f5.js +436 -0
- package/dist/prune-beweag7w.js +17 -0
- package/dist/run-7eayrqwy.js +18 -0
- package/dist/shell-xrgvqrpp.js +55 -0
- package/dist/stack-h3pgyx1e.js +20 -0
- package/dist/tools-4j56r47a.js +13 -0
- package/package.json +6 -6
- package/src/cli.ts +270 -76
- package/src/commands.ts +58 -42
- package/src/compose.ts +37 -14
- package/src/config.ts +8 -1
- package/src/errors.ts +31 -5
- package/src/files.ts +15 -23
- package/src/git.ts +53 -7
- package/src/index.ts +3 -2
- package/src/init.ts +56 -10
- package/src/jobs.ts +60 -19
- package/src/list.ts +26 -13
- package/src/print.ts +76 -0
- package/src/project.ts +134 -23
- package/src/proxy.ts +9 -9
- package/src/prune.ts +149 -0
- package/src/queue.ts +27 -3
- package/src/run.ts +82 -23
- package/src/shell.ts +34 -7
- package/src/stack.ts +41 -17
- package/src/sync.ts +28 -3
- package/src/tools.ts +91 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
U
|
|
4
|
+
} from "./cli-k4471y24.js";
|
|
5
|
+
import {
|
|
6
|
+
holdSignals,
|
|
7
|
+
failureText
|
|
8
|
+
} from "./cli-1nyesy1b.js";
|
|
9
|
+
import {
|
|
10
|
+
WtError,
|
|
11
|
+
worktreeHost
|
|
12
|
+
} from "./cli-kek450vq.js";
|
|
13
|
+
import {
|
|
14
|
+
queueDir,
|
|
15
|
+
inLine
|
|
16
|
+
} from "./cli-j82fak6j.js";
|
|
17
|
+
import {
|
|
18
|
+
baseComposeFiles
|
|
19
|
+
} from "./cli-dmkfxdbr.js";
|
|
20
|
+
|
|
21
|
+
// src/files.ts
|
|
22
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "fs";
|
|
23
|
+
import { basename, dirname, join } from "path";
|
|
24
|
+
var {$ } = globalThis.Bun;
|
|
25
|
+
var PARTIAL = ".wt-partial";
|
|
26
|
+
function writeIfChanged(path, content) {
|
|
27
|
+
if (existsSync(path) && readFileSync(path, "utf8") === content)
|
|
28
|
+
return false;
|
|
29
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
30
|
+
writeFileSync(path, content);
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
async function volumeExists(name) {
|
|
34
|
+
return (await $`docker volume inspect ${name}`.quiet().nothrow()).exitCode === 0;
|
|
35
|
+
}
|
|
36
|
+
async function copyFromMain(worktree) {
|
|
37
|
+
const warnings = [];
|
|
38
|
+
for (const entry of worktree.project.copy ?? []) {
|
|
39
|
+
const source = join(worktree.project.root, entry);
|
|
40
|
+
const target = join(worktree.dir, entry);
|
|
41
|
+
if (!existsSync(source)) {
|
|
42
|
+
warnings.push(`copy: ${entry} does not exist in main`);
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (existsSync(target))
|
|
46
|
+
continue;
|
|
47
|
+
const partial = `${target}${PARTIAL}`;
|
|
48
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
49
|
+
rmSync(partial, { recursive: true, force: true });
|
|
50
|
+
await $`cp -a --reflink=auto ${source} ${partial}`.quiet();
|
|
51
|
+
renameSync(partial, target);
|
|
52
|
+
}
|
|
53
|
+
return warnings;
|
|
54
|
+
}
|
|
55
|
+
function linkFromMain(worktree) {
|
|
56
|
+
for (const entry of worktree.project.link ?? []) {
|
|
57
|
+
const source = join(worktree.project.root, entry);
|
|
58
|
+
const target = join(worktree.dir, entry);
|
|
59
|
+
if (existsSync(source) && !existsSync(target)) {
|
|
60
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
61
|
+
symlinkSync(source, target);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
var WILDCARD_LABEL = /^\*\./;
|
|
66
|
+
function rewriteHosts(text, routes, task) {
|
|
67
|
+
const hosts = [...new Set(routes.map((route) => route.host.replace(WILDCARD_LABEL, "")))].sort((a, b) => b.length - a.length);
|
|
68
|
+
if (hosts.length === 0)
|
|
69
|
+
return text;
|
|
70
|
+
const pattern = new RegExp(`(?<![\\w.-])(\\.?)(${hosts.map(U).join("|")})(?![\\w.-])`, "g");
|
|
71
|
+
return text.replace(pattern, (_, dot, host) => `${dot}${worktreeHost(host, task)}`);
|
|
72
|
+
}
|
|
73
|
+
function setEnvValue(text, key, value) {
|
|
74
|
+
const line = `${key}=${value}`;
|
|
75
|
+
const pattern = new RegExp(`^${U(key)}=.*$`, "m");
|
|
76
|
+
if (pattern.test(text))
|
|
77
|
+
return text.replace(pattern, () => line);
|
|
78
|
+
return `${text}${text === "" || text.endsWith(`
|
|
79
|
+
`) ? "" : `
|
|
80
|
+
`}${line}
|
|
81
|
+
`;
|
|
82
|
+
}
|
|
83
|
+
function expandEnvValue(value, worktree) {
|
|
84
|
+
return value.replaceAll("{task}", worktree.task).replaceAll("{port}", String(worktree.clientPort));
|
|
85
|
+
}
|
|
86
|
+
function writeEnvFiles(worktree) {
|
|
87
|
+
const { project, task, dir } = worktree;
|
|
88
|
+
const envFiles = (project.copy ?? []).filter((entry) => basename(entry).startsWith(".env") && statSync(join(dir, entry), { throwIfNoEntry: false })?.isFile());
|
|
89
|
+
for (const entry of new Set([...envFiles, ".env"])) {
|
|
90
|
+
const file = join(dir, entry);
|
|
91
|
+
let text = existsSync(file) ? rewriteHosts(readFileSync(file, "utf8"), project.routes, task) : "";
|
|
92
|
+
for (const [key, value] of Object.entries(project.env?.[entry] ?? {}))
|
|
93
|
+
text = setEnvValue(text, key, expandEnvValue(value, worktree));
|
|
94
|
+
if (entry === ".env") {
|
|
95
|
+
text = setEnvValue(text, "COMPOSE_PROJECT_NAME", worktree.id);
|
|
96
|
+
text = setEnvValue(text, "COMPOSE_FILE", [...baseComposeFiles(dir, worktree.project.settings.overrides), worktree.files.override].join(":"));
|
|
97
|
+
}
|
|
98
|
+
writeIfChanged(file, text);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function unlinkLegacySymlink(dir, entry) {
|
|
102
|
+
let path = dir;
|
|
103
|
+
for (const part of entry.split("/")) {
|
|
104
|
+
path = join(path, part);
|
|
105
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
106
|
+
if (!stat)
|
|
107
|
+
return;
|
|
108
|
+
if (stat.isSymbolicLink())
|
|
109
|
+
return unlinkSync(path);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
async function mainContainers(main, status) {
|
|
113
|
+
return (await $`docker ps -q --filter ${`status=${status}`} --filter ${`label=com.docker.compose.project=${main.name}`}`.quiet().text()).split(`
|
|
114
|
+
`).filter(Boolean);
|
|
115
|
+
}
|
|
116
|
+
function unpause(ids) {
|
|
117
|
+
if (ids.length)
|
|
118
|
+
Bun.spawnSync(["docker", "unpause", ...ids], { stdout: "ignore", stderr: "ignore" });
|
|
119
|
+
}
|
|
120
|
+
async function whilePaused(ids, work, abort, record) {
|
|
121
|
+
const release = () => {
|
|
122
|
+
unpause(ids);
|
|
123
|
+
if (record !== undefined)
|
|
124
|
+
rmSync(record, { force: true });
|
|
125
|
+
};
|
|
126
|
+
const held = holdSignals(() => {
|
|
127
|
+
abort?.();
|
|
128
|
+
release();
|
|
129
|
+
});
|
|
130
|
+
try {
|
|
131
|
+
if (ids.length) {
|
|
132
|
+
if (record !== undefined) {
|
|
133
|
+
mkdirSync(dirname(record), { recursive: true });
|
|
134
|
+
writeFileSync(record, `${ids.join(`
|
|
135
|
+
`)}
|
|
136
|
+
`);
|
|
137
|
+
}
|
|
138
|
+
await $`docker pause ${ids}`.quiet();
|
|
139
|
+
}
|
|
140
|
+
return await work();
|
|
141
|
+
} finally {
|
|
142
|
+
held.release();
|
|
143
|
+
release();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
async function settle(copies) {
|
|
147
|
+
const results = await Promise.allSettled(copies.map(async (copy) => copy()));
|
|
148
|
+
return results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
149
|
+
}
|
|
150
|
+
var pausedRecord = (worktree) => queueDir(worktree.project.settings, `${worktree.project.name}.paused`);
|
|
151
|
+
function readPending(file) {
|
|
152
|
+
return new Set(existsSync(file) ? readFileSync(file, "utf8").split(`
|
|
153
|
+
`).filter(Boolean) : []);
|
|
154
|
+
}
|
|
155
|
+
function writePending(file, volumes) {
|
|
156
|
+
const text = [...volumes].join(`
|
|
157
|
+
`);
|
|
158
|
+
if (!text)
|
|
159
|
+
return rmSync(file, { force: true });
|
|
160
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
161
|
+
writeFileSync(file, `${text}
|
|
162
|
+
`);
|
|
163
|
+
}
|
|
164
|
+
async function cloneData(worktree, main) {
|
|
165
|
+
return inLine(queueDir(worktree.project.settings, `${worktree.project.name}.clone`), `cloning ${worktree.task}`, (_, running) => console.error(`wt: ${worktree.project.name}'s main is busy ${running || "cloning"}, waiting`), async () => {
|
|
166
|
+
const record = pausedRecord(worktree);
|
|
167
|
+
const recorded = readPending(record);
|
|
168
|
+
const leftover = recorded.size ? (await mainContainers(main, "paused")).filter((id) => recorded.has(id)) : [];
|
|
169
|
+
unpause(leftover);
|
|
170
|
+
rmSync(record, { force: true });
|
|
171
|
+
const warnings = leftover.length ? [`clone: unpaused ${leftover.length} of main's containers a clone cut short had left paused`] : [];
|
|
172
|
+
return [...warnings, ...await cloneInLine(worktree, main)];
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
async function cloneInLine(worktree, main) {
|
|
176
|
+
const warnings = [];
|
|
177
|
+
const pending = [];
|
|
178
|
+
const unfinished = readPending(worktree.files.clonesPending);
|
|
179
|
+
const copyLabel = `wt.clone=${worktree.id}`;
|
|
180
|
+
const stopCopies = () => {
|
|
181
|
+
const ids = Bun.spawnSync(["docker", "ps", "-q", "--filter", `label=${copyLabel}`]).stdout.toString().split(`
|
|
182
|
+
`).filter(Boolean);
|
|
183
|
+
if (ids.length)
|
|
184
|
+
Bun.spawnSync(["docker", "rm", "-f", ...ids], { stdout: "ignore", stderr: "ignore" });
|
|
185
|
+
};
|
|
186
|
+
for (const entry of worktree.project.clone ?? []) {
|
|
187
|
+
const source = join(worktree.project.root, entry);
|
|
188
|
+
if (existsSync(source)) {
|
|
189
|
+
unlinkLegacySymlink(worktree.dir, entry);
|
|
190
|
+
const target = join(worktree.dir, entry);
|
|
191
|
+
if (existsSync(target))
|
|
192
|
+
continue;
|
|
193
|
+
if (!statSync(source).isDirectory())
|
|
194
|
+
throw new WtError(`clone: ${entry} is not a directory`);
|
|
195
|
+
const partial = `/to/${basename(target)}${PARTIAL}`;
|
|
196
|
+
pending.push({
|
|
197
|
+
copy: async () => {
|
|
198
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
199
|
+
await $`docker run --rm --label ${copyLabel} -v ${`${source}:/from:ro`} -v ${`${dirname(target)}:/to`} alpine sh -c ${`rm -rf '${partial}' && mkdir '${partial}' && cp -a /from/. '${partial}/' && mv '${partial}' '/to/${basename(target)}'`}`.quiet();
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
const volume = main.volumes?.[entry];
|
|
205
|
+
if (!volume) {
|
|
206
|
+
warnings.push(`clone: ${entry} is neither a path in main nor a volume of its stack`);
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (volume.driver_opts?.device !== undefined && volume.driver_opts.device !== "")
|
|
210
|
+
throw new WtError(`clone: volume ${entry} is a bind to ${volume.driver_opts.device}`, "list that path in clone instead");
|
|
211
|
+
const sourceVolume = volume.name ?? `${main.name}_${entry}`;
|
|
212
|
+
const targetVolume = `${worktree.id}_${entry}`;
|
|
213
|
+
if (await volumeExists(targetVolume)) {
|
|
214
|
+
if (!unfinished.has(targetVolume))
|
|
215
|
+
continue;
|
|
216
|
+
const removed = await $`docker volume rm ${targetVolume}`.quiet().nothrow();
|
|
217
|
+
if (removed.exitCode !== 0)
|
|
218
|
+
throw new WtError(`clone: volume ${targetVolume} was cut short mid-copy and cannot be emptied (${removed.stderr.toString().trim()})`, `\`wt down ${worktree.task}\` then \`wt sync ${worktree.task}\``);
|
|
219
|
+
}
|
|
220
|
+
if (!await volumeExists(sourceVolume)) {
|
|
221
|
+
warnings.push(`clone: main has no volume ${sourceVolume} yet, the worktree starts with an empty one`);
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
pending.push({
|
|
225
|
+
volume: targetVolume,
|
|
226
|
+
copy: async () => {
|
|
227
|
+
await $`docker volume create --label ${`com.docker.compose.project=${worktree.id}`} --label ${`com.docker.compose.volume=${entry}`} ${targetVolume}`.quiet();
|
|
228
|
+
await $`docker run --rm --label ${copyLabel} -v ${`${sourceVolume}:/from:ro`} -v ${`${targetVolume}:/to`} alpine cp -a /from/. /to/`.quiet();
|
|
229
|
+
unfinished.delete(targetVolume);
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
if (!pending.length) {
|
|
234
|
+
writePending(worktree.files.clonesPending, unfinished);
|
|
235
|
+
return warnings;
|
|
236
|
+
}
|
|
237
|
+
for (const { volume } of pending) {
|
|
238
|
+
if (volume !== undefined)
|
|
239
|
+
unfinished.add(volume);
|
|
240
|
+
}
|
|
241
|
+
writePending(worktree.files.clonesPending, unfinished);
|
|
242
|
+
const failures = await whilePaused(await mainContainers(main, "running"), async () => settle(pending.map(({ copy }) => copy)), stopCopies, pausedRecord(worktree));
|
|
243
|
+
writePending(worktree.files.clonesPending, unfinished);
|
|
244
|
+
if (failures.length)
|
|
245
|
+
throw new WtError(`clone failed:
|
|
246
|
+
${failures.map(failureText).join(`
|
|
247
|
+
`)}`, `\`wt sync ${worktree.task}\` starts it again`);
|
|
248
|
+
return warnings;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export { writeIfChanged, volumeExists, copyFromMain, linkFromMain, writeEnvFiles, cloneData };
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
warn
|
|
4
|
+
} from "./cli-k4471y24.js";
|
|
5
|
+
import {
|
|
6
|
+
configPath,
|
|
7
|
+
fillTemplate,
|
|
8
|
+
WtError
|
|
9
|
+
} from "./cli-kek450vq.js";
|
|
10
|
+
import {
|
|
11
|
+
hasDevproxy,
|
|
12
|
+
devproxyUp
|
|
13
|
+
} from "./cli-pkvw2k4x.js";
|
|
14
|
+
import {
|
|
15
|
+
composeEnv
|
|
16
|
+
} from "./cli-dmkfxdbr.js";
|
|
17
|
+
|
|
18
|
+
// src/stack.ts
|
|
19
|
+
import { existsSync, mkdirSync, writeFileSync } from "fs";
|
|
20
|
+
import { homedir } from "os";
|
|
21
|
+
import { dirname } from "path";
|
|
22
|
+
var {$ } = globalThis.Bun;
|
|
23
|
+
async function spawnInherit(argv, cwd, env = process.env) {
|
|
24
|
+
return Bun.spawn(argv, { cwd, env, stdio: ["inherit", "inherit", "inherit"] }).exited;
|
|
25
|
+
}
|
|
26
|
+
async function spawnRunner(role, argv, cwd) {
|
|
27
|
+
try {
|
|
28
|
+
return await spawnInherit(argv, cwd);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
if (error.code === "ENOENT")
|
|
31
|
+
throw new WtError(`\`${argv[0]}\` is not on PATH`, `fix runner.${role} in ${configPath()}`);
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
var argvOf = (template, worktree) => fillTemplate(template, { project: worktree.project.name, task: worktree.task, dir: worktree.dir, id: worktree.id });
|
|
36
|
+
async function runTemplate(role, template, worktree) {
|
|
37
|
+
const argv = argvOf(template, worktree);
|
|
38
|
+
if (await spawnRunner(role, argv, worktree.dir) !== 0)
|
|
39
|
+
throw new WtError(`\`${argv.join(" ")}\` failed`);
|
|
40
|
+
}
|
|
41
|
+
async function runSetup(worktree, env = composeEnv()) {
|
|
42
|
+
const setup = worktree.project.setup ?? [];
|
|
43
|
+
const marker = worktree.files.setupMarker;
|
|
44
|
+
if (!setup.length || existsSync(marker))
|
|
45
|
+
return;
|
|
46
|
+
for (const command of setup) {
|
|
47
|
+
if (await spawnInherit(["sh", "-c", command], worktree.dir, env) !== 0)
|
|
48
|
+
throw new WtError(`the worktree setup failed on \`${command}\``);
|
|
49
|
+
}
|
|
50
|
+
mkdirSync(dirname(marker), { recursive: true });
|
|
51
|
+
writeFileSync(marker, "");
|
|
52
|
+
}
|
|
53
|
+
async function stackUp2(worktree) {
|
|
54
|
+
const { up } = worktree.project.settings.runner;
|
|
55
|
+
if (up)
|
|
56
|
+
return runTemplate("up", up, worktree);
|
|
57
|
+
if (hasDevproxy())
|
|
58
|
+
await devproxyUp();
|
|
59
|
+
const network = worktree.project.settings.proxyNetwork;
|
|
60
|
+
if (worktree.project.routes.length > 0 && (await $`docker network inspect ${network}`.quiet().nothrow()).exitCode !== 0)
|
|
61
|
+
throw new WtError(`the routed services join the ${network} network, which does not exist: install and configure devproxy, or set proxyNetwork in ${configPath()} to the network your proxy dials stacks on`);
|
|
62
|
+
if (await spawnInherit(["docker", "compose", "up", "-d", "--build"], worktree.dir, composeEnv()) !== 0)
|
|
63
|
+
throw new WtError(`docker compose up failed in ${worktree.dir}`);
|
|
64
|
+
await runSetup(worktree);
|
|
65
|
+
}
|
|
66
|
+
async function stackDown2(worktree) {
|
|
67
|
+
const { down } = worktree.project.settings.runner;
|
|
68
|
+
if (down && existsSync(worktree.dir))
|
|
69
|
+
return runTemplate("down", down, worktree);
|
|
70
|
+
const here = existsSync(worktree.dir);
|
|
71
|
+
const argv = here ? ["docker", "compose", "down", "--remove-orphans"] : ["docker", "compose", "-p", worktree.id, "down", "--remove-orphans"];
|
|
72
|
+
if (await spawnInherit(argv, here ? worktree.dir : homedir(), composeEnv()) !== 0)
|
|
73
|
+
throw new WtError(`docker compose down failed for ${worktree.id}`);
|
|
74
|
+
}
|
|
75
|
+
async function followLogs2(worktree) {
|
|
76
|
+
return spawnInherit(["docker", "compose", "logs", "--follow", "--tail", "100"], worktree.dir, composeEnv());
|
|
77
|
+
}
|
|
78
|
+
async function afterRemove2(worktree) {
|
|
79
|
+
const { removed } = worktree.project.settings.runner;
|
|
80
|
+
if (!removed)
|
|
81
|
+
return;
|
|
82
|
+
const argv = argvOf(removed, worktree);
|
|
83
|
+
try {
|
|
84
|
+
if (await spawnRunner("removed", argv, worktree.project.root) !== 0)
|
|
85
|
+
warn(`\`${argv.join(" ")}\` failed after removing ${worktree.id}`);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (!(error instanceof WtError))
|
|
88
|
+
throw error;
|
|
89
|
+
warn(`${error.message}, after removing ${worktree.id}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
async function hasContainers2(composeName) {
|
|
93
|
+
const found = await $`docker ps -aq --filter ${`label=com.docker.compose.project=${composeName}`}`.quiet().nothrow();
|
|
94
|
+
return found.stdout.toString().trim() !== "";
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export { stackUp2, stackDown2, followLogs2, afterRemove2, hasContainers2 };
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
compose
|
|
4
|
+
} from "./cli-1nyesy1b.js";
|
|
5
|
+
import {
|
|
6
|
+
WtError,
|
|
7
|
+
worktreeHost
|
|
8
|
+
} from "./cli-kek450vq.js";
|
|
9
|
+
|
|
10
|
+
// src/compose.ts
|
|
11
|
+
import { existsSync, readFileSync } from "fs";
|
|
12
|
+
import { join } from "path";
|
|
13
|
+
var COMPOSE_FILES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
|
|
14
|
+
var SKIP_PROFILE = "wt-skip";
|
|
15
|
+
function composeEnv(overrides = {}) {
|
|
16
|
+
return { ...process.env, COMPOSE_FILE: undefined, COMPOSE_PROJECT_NAME: undefined, ...overrides };
|
|
17
|
+
}
|
|
18
|
+
async function composeConfig(dir, env = {}) {
|
|
19
|
+
const result = await compose(["config", "--format", "json"], { cwd: dir, env: composeEnv(env) });
|
|
20
|
+
if (result.code !== 0)
|
|
21
|
+
throw new WtError(`docker compose config failed in ${dir}:
|
|
22
|
+
${result.stderr}`);
|
|
23
|
+
return JSON.parse(result.stdout);
|
|
24
|
+
}
|
|
25
|
+
var COMPOSE_FILE_LINE = /^COMPOSE_FILE=(.*)$/m;
|
|
26
|
+
var QUOTES_AROUND = /^["']|["']$/g;
|
|
27
|
+
function baseComposeFiles(dir, overrides) {
|
|
28
|
+
const envFile = join(dir, ".env");
|
|
29
|
+
const line = existsSync(envFile) ? readFileSync(envFile, "utf8").match(COMPOSE_FILE_LINE) : null;
|
|
30
|
+
const files = line ? line[1].replace(QUOTES_AROUND, "").split(":").filter(Boolean) : [];
|
|
31
|
+
const base = files.filter((file) => !file.startsWith(`${overrides}/`));
|
|
32
|
+
if (base.length)
|
|
33
|
+
return base;
|
|
34
|
+
const found = COMPOSE_FILES.find((file) => existsSync(join(dir, file)));
|
|
35
|
+
if (found === undefined)
|
|
36
|
+
throw new WtError(`no compose file in ${dir}`);
|
|
37
|
+
return [found];
|
|
38
|
+
}
|
|
39
|
+
var q = (value) => JSON.stringify(value);
|
|
40
|
+
var DEVPROXY_HOST_LABEL = /^devproxy\.[\w-]+\.host$/;
|
|
41
|
+
var SERVICE = /^[^:]*/;
|
|
42
|
+
function proxyLabels(worktree, config) {
|
|
43
|
+
const { routes, skip = [] } = worktree.project;
|
|
44
|
+
const labels = new Map;
|
|
45
|
+
const add = (service, ...entries) => labels.set(service, [...labels.get(service) ?? [], ...entries]);
|
|
46
|
+
const routed = routes.find((route) => route.to !== "client")?.to;
|
|
47
|
+
const anchor = routed === undefined ? Object.keys(config.services).find((service) => !skip.includes(service)) : SERVICE.exec(routed)[0];
|
|
48
|
+
for (const [index, route] of routes.entries()) {
|
|
49
|
+
const key = `devproxy.wt${index}`;
|
|
50
|
+
const host = [`${key}.host`, worktreeHost(route.host, worktree.task)];
|
|
51
|
+
if (route.to === "client") {
|
|
52
|
+
if (anchor !== undefined)
|
|
53
|
+
add(anchor, host, [`${key}.to`, `host:${worktree.clientPort}`]);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
const [service = "", port = ""] = route.to.split(":");
|
|
57
|
+
add(service, host, [`${key}.port`, port], ...route.passthrough ? [[`${key}.passthrough`, "true"]] : []);
|
|
58
|
+
}
|
|
59
|
+
for (const [service, settings] of Object.entries(config.services)) {
|
|
60
|
+
for (const [key, value] of Object.entries(settings.labels ?? {})) {
|
|
61
|
+
if (DEVPROXY_HOST_LABEL.test(key))
|
|
62
|
+
add(service, [key, value.split(",").map((host) => worktreeHost(host.trim(), worktree.task)).join(",")]);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return labels;
|
|
66
|
+
}
|
|
67
|
+
function renderOverride(worktree, config) {
|
|
68
|
+
const skip = new Set(worktree.project.skip);
|
|
69
|
+
const routeHosts = new Set(worktree.project.routeHosts);
|
|
70
|
+
const labels = proxyLabels(worktree, config);
|
|
71
|
+
const network = worktree.project.settings.proxyNetwork;
|
|
72
|
+
const extraHosts = worktree.project.routes.filter((route) => !route.host.startsWith("*.")).map((route) => ` - ${q(`${worktreeHost(route.host, worktree.task)}:host-gateway`)}`);
|
|
73
|
+
const lines = [`# Generated by wt for ${worktree.id}, rewritten on every \`wt sync\`.`, "services:"];
|
|
74
|
+
let joined = false;
|
|
75
|
+
for (const [name, service] of Object.entries(config.services)) {
|
|
76
|
+
const body = [];
|
|
77
|
+
if (skip.has(name))
|
|
78
|
+
body.push(` profiles: [${q(SKIP_PROFILE)}]`);
|
|
79
|
+
if (service.container_name !== undefined && service.container_name !== "")
|
|
80
|
+
body.push(" container_name: !reset null");
|
|
81
|
+
if ((service.ports?.length ?? 0) > 0)
|
|
82
|
+
body.push(" ports: !reset []");
|
|
83
|
+
if (routeHosts.has(name) && extraHosts.length)
|
|
84
|
+
body.push(" extra_hosts:", ...extraHosts);
|
|
85
|
+
if (labels.has(name))
|
|
86
|
+
body.push(" labels:", ...labels.get(name).map(([key, value]) => ` ${q(key)}: ${q(value)}`));
|
|
87
|
+
const networks = (service.network_mode ?? "") !== "" ? [] : Object.entries(service.networks ?? {});
|
|
88
|
+
const joins = (service.network_mode ?? "") === "" && !skip.has(name) && !(network in (service.networks ?? {})) && labels.get(name)?.some(([key]) => key.endsWith(".port")) === true;
|
|
89
|
+
const networkLines = networks.flatMap(([own, settings]) => {
|
|
90
|
+
if (own === network)
|
|
91
|
+
return (settings?.aliases?.length ?? 0) > 0 ? [` ${network}:`, " aliases: !reset []"] : [];
|
|
92
|
+
if (service.container_name !== undefined && service.container_name !== "")
|
|
93
|
+
return [` ${q(own)}:`, ` aliases: [${q(service.container_name)}]`];
|
|
94
|
+
return joins ? [` ${q(own)}: {}`] : [];
|
|
95
|
+
});
|
|
96
|
+
if (joins) {
|
|
97
|
+
joined = true;
|
|
98
|
+
networkLines.push(` ${network}: {}`);
|
|
99
|
+
}
|
|
100
|
+
if (networkLines.length)
|
|
101
|
+
body.push(" networks:", ...networkLines);
|
|
102
|
+
if (body.length)
|
|
103
|
+
lines.push(` ${q(name)}:`, ...body);
|
|
104
|
+
}
|
|
105
|
+
if (joined && config.networks?.[network] === undefined)
|
|
106
|
+
lines.push("networks:", ` ${network}:`, ` name: ${network}`, " external: true");
|
|
107
|
+
return `${lines.join(`
|
|
108
|
+
`)}
|
|
109
|
+
`;
|
|
110
|
+
}
|
|
111
|
+
function overrideWarnings(worktree, config) {
|
|
112
|
+
const skip = new Set(worktree.project.skip);
|
|
113
|
+
const network = worktree.project.settings.proxyNetwork;
|
|
114
|
+
const warnings = [];
|
|
115
|
+
for (const [name, service] of Object.entries(config.services)) {
|
|
116
|
+
if (skip.has(name))
|
|
117
|
+
continue;
|
|
118
|
+
if (service.network_mode === "host")
|
|
119
|
+
warnings.push(`service ${name} runs on the host network and may collide with main, consider adding it to skip`);
|
|
120
|
+
if (service.networks && network in service.networks && !service.networks[network]?.aliases?.some((alias) => alias !== name))
|
|
121
|
+
warnings.push(`service ${name} has no alias of its own on the proxy network, so the worktree answers to ${name} there too and the shared proxy round-robins between them, give it one in the project override`);
|
|
122
|
+
}
|
|
123
|
+
for (const [key, volume] of Object.entries(config.volumes ?? {})) {
|
|
124
|
+
if (volume.external || volume.name !== undefined && !volume.name.startsWith(`${config.name}_`))
|
|
125
|
+
warnings.push(`volume ${key} is named ${volume.name ?? key} outside the project, main and the worktree share it`);
|
|
126
|
+
}
|
|
127
|
+
return warnings;
|
|
128
|
+
}
|
|
129
|
+
async function unknownServices(project, config) {
|
|
130
|
+
const named = [
|
|
131
|
+
["skip", project.skip ?? []],
|
|
132
|
+
["routeHosts", project.routeHosts ?? []],
|
|
133
|
+
["routes", project.routes.filter((route) => route.to !== "client").map((route) => SERVICE.exec(route.to)[0])],
|
|
134
|
+
["run.service", project.run ? [project.run.service] : []]
|
|
135
|
+
];
|
|
136
|
+
const missing = named.flatMap(([setting, names]) => [...new Set(names)].filter((name) => config.services[name] === undefined).map((name) => [setting, name]));
|
|
137
|
+
if (!missing.length)
|
|
138
|
+
return [];
|
|
139
|
+
const profiled = await compose(["--profile", "*", "config", "--services"], { cwd: project.root, env: composeEnv() });
|
|
140
|
+
const every = new Set(profiled.code === 0 ? profiled.stdout.split(`
|
|
141
|
+
`).filter(Boolean) : []);
|
|
142
|
+
return missing.filter(([, name]) => !every.has(name)).map(([setting, name]) => `${project.name}: ${setting} names ${name}, which is not a service of ${config.name}`);
|
|
143
|
+
}
|
|
144
|
+
async function runningProjects(all = false) {
|
|
145
|
+
if (Bun.which("docker") === null)
|
|
146
|
+
return new Set;
|
|
147
|
+
const result = await compose(["ls", ...all ? ["-a"] : [], "--format", "json"]);
|
|
148
|
+
if (result.code !== 0)
|
|
149
|
+
return new Set;
|
|
150
|
+
return new Set(JSON.parse(result.stdout).map((stack) => stack.Name));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export { composeEnv, composeConfig, baseComposeFiles, renderOverride, overrideWarnings, unknownServices, runningProjects };
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
WtError
|
|
4
|
+
} from "./cli-kek450vq.js";
|
|
5
|
+
|
|
6
|
+
// src/git.ts
|
|
7
|
+
import { existsSync, mkdirSync, readdirSync, rmdirSync } from "fs";
|
|
8
|
+
import { basename, dirname, join } from "path";
|
|
9
|
+
var {$ } = globalThis.Bun;
|
|
10
|
+
async function git(cwd, ...args) {
|
|
11
|
+
const result = await $`git -C ${cwd} ${args}`.quiet().nothrow();
|
|
12
|
+
return { ok: result.exitCode === 0, out: `${result.stdout.toString()}${result.stderr.toString()}`.trim() };
|
|
13
|
+
}
|
|
14
|
+
async function branchExists(repo, branch) {
|
|
15
|
+
if ((await git(repo, "show-ref", "--quiet", "--verify", `refs/heads/${branch}`)).ok)
|
|
16
|
+
return true;
|
|
17
|
+
return (await git(repo, "for-each-ref", "--format=%(refname)", `refs/remotes/*/${branch}`)).out !== "";
|
|
18
|
+
}
|
|
19
|
+
async function forkPoint(repo, from) {
|
|
20
|
+
const sha = await git(repo, "rev-parse", "--short", `${from ?? "HEAD"}^{commit}`);
|
|
21
|
+
if (!sha.ok)
|
|
22
|
+
return;
|
|
23
|
+
if (from !== undefined)
|
|
24
|
+
return `${from} (${sha.out})`;
|
|
25
|
+
const name = (await git(repo, "rev-parse", "--abbrev-ref", "HEAD")).out;
|
|
26
|
+
return name === "HEAD" ? `a detached HEAD (${sha.out})` : `${name} (${sha.out})`;
|
|
27
|
+
}
|
|
28
|
+
async function onBranch(repo, dir, branch, from) {
|
|
29
|
+
if (await branchExists(repo, branch))
|
|
30
|
+
return { ...await git(repo, "worktree", "add", dir, branch), start: `on ${branch} as it is` };
|
|
31
|
+
const point = await forkPoint(repo, from);
|
|
32
|
+
if (point === undefined)
|
|
33
|
+
return { ok: false, out: `no commit ${from ?? "HEAD"} in ${repo}`, start: "" };
|
|
34
|
+
return { ...await git(repo, "worktree", "add", "-b", branch, dir, ...from === undefined ? [] : [from]), start: `on ${branch}, forked from ${point}` };
|
|
35
|
+
}
|
|
36
|
+
async function addWorktrees(worktree, branch, from) {
|
|
37
|
+
const { project, dir } = worktree;
|
|
38
|
+
if (existsSync(dir))
|
|
39
|
+
throw new WtError(`${dir} already exists`, `\`wt sync ${worktree.task} -p ${project.name}\` finishes it, \`wt rm ${worktree.task} -p ${project.name}\` removes it`);
|
|
40
|
+
if (from !== undefined) {
|
|
41
|
+
for (const repo of project.repos.length ? project.repos : ["."]) {
|
|
42
|
+
if (await branchExists(join(project.root, repo), branch))
|
|
43
|
+
throw new WtError(`${branch} already exists${repo === "." ? "" : ` in ${repo}`}, so it is checked out as it is`, "drop --from, or name a new branch");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
mkdirSync(dirname(dir), { recursive: true });
|
|
47
|
+
if (!project.repos.length) {
|
|
48
|
+
const root = await onBranch(project.root, dir, branch, from);
|
|
49
|
+
if (!root.ok)
|
|
50
|
+
throw new WtError(`git worktree add failed for the root:
|
|
51
|
+
${root.out}`);
|
|
52
|
+
return [root.start];
|
|
53
|
+
}
|
|
54
|
+
const root = await git(project.root, "worktree", "add", "--detach", dir);
|
|
55
|
+
if (!root.ok)
|
|
56
|
+
throw new WtError(`git worktree add failed for the root:
|
|
57
|
+
${root.out}`);
|
|
58
|
+
const starts = [];
|
|
59
|
+
for (const repo of project.repos) {
|
|
60
|
+
const added = await onBranch(join(project.root, repo), join(dir, repo), branch, from);
|
|
61
|
+
if (!added.ok) {
|
|
62
|
+
await removeWorktrees(worktree);
|
|
63
|
+
throw new WtError(`git worktree add failed for ${repo}, rolled back:
|
|
64
|
+
${added.out}`);
|
|
65
|
+
}
|
|
66
|
+
starts.push(`${repo} ${added.start}`);
|
|
67
|
+
}
|
|
68
|
+
return starts;
|
|
69
|
+
}
|
|
70
|
+
async function removeWorktrees(worktree) {
|
|
71
|
+
const { project, dir } = worktree;
|
|
72
|
+
await Promise.all(project.repos.map(async (repo) => git(join(project.root, repo), "worktree", "remove", "--force", join(dir, repo))));
|
|
73
|
+
await git(project.root, "worktree", "remove", "--force", dir);
|
|
74
|
+
if (existsSync(dir))
|
|
75
|
+
await $`docker run --rm -v ${`${dirname(dir)}:/parent`} alpine rm -rf ${`/parent/${basename(dir)}`}`.quiet();
|
|
76
|
+
await Promise.all([".", ...project.repos].map(async (repo) => git(join(project.root, repo), "worktree", "prune")));
|
|
77
|
+
if (existsSync(dirname(dir)) && !readdirSync(dirname(dir)).length)
|
|
78
|
+
rmdirSync(dirname(dir));
|
|
79
|
+
}
|
|
80
|
+
async function dirtyRepos(worktree) {
|
|
81
|
+
const repos = [".", ...worktree.project.repos];
|
|
82
|
+
const statuses = await Promise.all(repos.map(async (repo) => git(join(worktree.dir, repo), "status", "--porcelain")));
|
|
83
|
+
return repos.filter((_, index) => statuses[index].ok && statuses[index].out !== "").map((repo) => repo === "." ? "root" : repo);
|
|
84
|
+
}
|
|
85
|
+
async function unreachableByRepo(dir, repos) {
|
|
86
|
+
const all = [".", ...repos];
|
|
87
|
+
const counts = await Promise.all(all.map(async (repo) => git(join(dir, repo), "rev-list", "--count", "HEAD", "--not", "--branches", "--remotes", "--tags")));
|
|
88
|
+
return all.map((repo, index) => ({ repo: repo === "." ? "root" : repo, count: Number(counts[index].ok ? counts[index].out : 0) })).filter(({ count }) => count > 0);
|
|
89
|
+
}
|
|
90
|
+
async function unreachableCommits(worktree) {
|
|
91
|
+
return (await unreachableByRepo(worktree.dir, worktree.project.repos)).map(({ repo, count }) => `${repo} (${count} commit${count === 1 ? "" : "s"})`);
|
|
92
|
+
}
|
|
93
|
+
async function unreachableCount(dir, repos) {
|
|
94
|
+
return (await unreachableByRepo(dir, repos)).reduce((total, { count }) => total + count, 0);
|
|
95
|
+
}
|
|
96
|
+
async function isRegistered(worktree) {
|
|
97
|
+
const listed = await git(worktree.project.root, "worktree", "list", "--porcelain");
|
|
98
|
+
return listed.out.split(`
|
|
99
|
+
`).includes(`worktree ${worktree.dir}`);
|
|
100
|
+
}
|
|
101
|
+
async function currentBranch(dir) {
|
|
102
|
+
const result = await git(dir, "rev-parse", "--abbrev-ref", "HEAD");
|
|
103
|
+
return result.ok ? result.out : "?";
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export { git, addWorktrees, removeWorktrees, dirtyRepos, unreachableCommits, unreachableCount, isRegistered, currentBranch };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
WtError,
|
|
4
|
+
worktreeHost
|
|
5
|
+
} from "./cli-kek450vq.js";
|
|
6
|
+
|
|
7
|
+
// src/routes.ts
|
|
8
|
+
import { existsSync, mkdirSync } from "fs";
|
|
9
|
+
import { join } from "path";
|
|
10
|
+
var {$ } = globalThis.Bun;
|
|
11
|
+
var LEADING_STAR = /^\*/;
|
|
12
|
+
async function mkcert(certFile, keyFile, hosts) {
|
|
13
|
+
const result = await $`mkcert -cert-file ${certFile} -key-file ${keyFile} ${hosts}`.quiet().nothrow();
|
|
14
|
+
if (result.exitCode !== 0)
|
|
15
|
+
throw new WtError(`mkcert failed for ${hosts.join(" ")}:
|
|
16
|
+
${result.stderr.toString()}`);
|
|
17
|
+
}
|
|
18
|
+
async function writeStackCerts(worktree) {
|
|
19
|
+
const { project } = worktree;
|
|
20
|
+
if (project.certs === undefined)
|
|
21
|
+
return;
|
|
22
|
+
const dir = join(worktree.dir, project.certs);
|
|
23
|
+
mkdirSync(dir, { recursive: true });
|
|
24
|
+
await Promise.all(project.routes.map(async (route) => {
|
|
25
|
+
const served = worktreeHost(route.host, worktree.task);
|
|
26
|
+
const name = served.replace(LEADING_STAR, "_wildcard");
|
|
27
|
+
const cert = join(dir, `${name}.pem`);
|
|
28
|
+
const key = join(dir, `${name}-key.pem`);
|
|
29
|
+
return existsSync(cert) && existsSync(key) ? undefined : mkcert(cert, key, [served]);
|
|
30
|
+
}));
|
|
31
|
+
}
|
|
32
|
+
function urlsOf(worktree) {
|
|
33
|
+
return worktree.project.routes.filter((route) => !route.host.startsWith("*.")).map((route) => `https://${worktreeHost(route.host, worktree.task)}`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export { writeStackCerts, urlsOf };
|