@kaynooo/cli-check 0.22.3 → 0.22.5

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/dist/cli.js CHANGED
@@ -1,2692 +1,14 @@
1
1
  #!/bin/sh
2
2
  // @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
3
- var __esm = (fn, res, err) => () => {
4
- if (fn)
5
- try {
6
- res = fn(fn = 0);
7
- } catch (e) {
8
- err = [e];
9
- }
10
- if (err)
11
- throw err[0];
12
- return res;
13
- };
3
+ import{paint,header,formatDuration,table,printJson,duration,jsonOption,fail,parse}from"./chunk-ef4tt9f7.js";import{exitCodeOf,holdSignals,runMain,version,shellQuote}from"./chunk-zbkaf2pz.js";import{place,shellIn,Stack,programOf,placeOptions,placeSettings,RESULTS_FILE,logDirectory,lastResults,lastFailed,runStep,refusedStep,outcomeJson,printOutcome}from"./chunk-eekge8ft.js";import{STEP_NAMES,MAKEFILES,CS_FIXER_CONFIGS,read,candidates,firstFile,discoverProjects}from"./chunk-w13gc4ne.js";import process3 from"process";import{writeFile as writeFile2}from"fs/promises";import{basename as basename2,join as join4}from"path";import process2 from"process";import{existsSync,statSync}from"fs";import{rename,writeFile}from"fs/promises";import{join as join2}from"path";import process from"process";import{stat}from"fs/promises";import{join}from"path";var{$}=globalThis.Bun;async function dirtyFiles(dir){let listed=await $`git ls-files -z --modified --others --exclude-standard`.cwd(dir).quiet().nothrow();if(listed.exitCode!==0)return;let files=new Map;for(let path of listed.stdout.toString().split("\x00").filter(Boolean))try{let{size,mtimeMs}=await stat(join(dir,path));files.set(path,`${size}:${mtimeMs}`)}catch{files.set(path,"")}return files}function changedFiles(before,after){return[...after].filter(([path,hash])=>before.get(path)!==hash).map(([path])=>path)}var TARGET=/^([\w-]+(?:[ \t]+[\w-]+)*)[ \t]*::?(?!:?=)(.*)$/gm,PHONY_LINE=/^\.PHONY:((?:.*\\\n)*.*)$/gm,DEFINE_BLOCK=/^define\b.*\n(?:.*\n)*?endef\b.*$/gm,BLANKS=/\s+/,CONTINUATION=/\\\n/g,EXTRA_BLANK_LINES=/\n\s*\n\s*\n/g,LEADING_BLANK_LINES=/^\s*\n/,TRAILING_WHITESPACE=/\s+$/,FILE_LIKE=/[./]/;function declarePhony(content,exists=()=>!1){let declared=Array.from(content.matchAll(PHONY_LINE),(match)=>match[1].replace(CONTINUATION," ").split(BLANKS)).flat().filter((name)=>name!==""),found=Array.from(content.replace(DEFINE_BLOCK,"").matchAll(TARGET),(match)=>({names:match[1].split(BLANKS),deps:match[2]})).filter(({deps})=>!FILE_LIKE.test(deps)).flatMap(({names})=>names).filter((name)=>!exists(name)),targets=[...new Set([...declared,...found])].sort((a,b)=>a.localeCompare(b)),isFirst=!0,body=content.replace(PHONY_LINE,()=>{let kept=isFirst?"\x00phony\x00":"";return isFirst=!1,kept}).replace(EXTRA_BLANK_LINES,`
14
4
 
15
- // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
16
- function Ao(t, e, r = "...") {
17
- let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
18
- if (t.length <= e)
19
- return t;
20
- let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
21
- if (o && !Y.test(t[c.length] ?? " "))
22
- c = c.replace(Nt, "") || c;
23
- if (o)
24
- c = c.trimEnd();
25
- return s ? (c + n).slice(0, l) : c + n;
26
- }
27
- var N, Nt, Y, be, W;
28
- var init_chunk_rkhsft4a = __esm(() => {
29
- N = new Map;
30
- Nt = /\s+\S*$/;
31
- Y = /\s/;
32
- be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
33
- W = new Map;
34
- });
5
+ `).replace(LEADING_BLANK_LINES,""),line=targets.length===0?"":`.PHONY: ${targets.join(" ")}`;return{content:(body.includes("\x00phony\x00")||line===""?body.replace("\x00phony\x00",()=>line):`${line}
35
6
 
36
- // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
37
- var init_text = __esm(() => {
38
- init_chunk_rkhsft4a();
39
- });
40
-
41
- // ../kit/src/mode.ts
42
- import process2 from "process";
43
- function isSet(value) {
44
- return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
45
- }
46
- function outputMode(stream = process2.stdout, env = process2.env) {
47
- const chosen = env.KIT_MODE;
48
- if (chosen !== undefined && MODES.has(chosen))
49
- return chosen;
50
- if (AGENT_VARIABLES.some((name) => isSet(env[name])))
51
- return "agent";
52
- if (stream.isTTY === true)
53
- return "terminal";
54
- return isSet(env.CI) ? "ci" : "pipe";
55
- }
56
- function isInteractive(streams = process2) {
57
- return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
58
- }
59
- var MODES, AGENT_VARIABLES;
60
- var init_mode = __esm(() => {
61
- MODES = new Set(["terminal", "ci", "agent", "pipe"]);
62
- AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
63
- });
64
-
65
- // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
66
- function b(r) {
67
- let e = r.startsWith("#") ? r.slice(1) : r;
68
- if (!G2.test(e))
69
- return [0, 0, 0];
70
- if (e.length === 3 || e.length === 4)
71
- return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
72
- if (e.length !== 6 && e.length !== 8)
73
- throw Error(`Invalid hex color length: ${e.length}`);
74
- return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
75
- }
76
- function C(r, e = globalThis.process?.env ?? {}) {
77
- if (e.FORCE_COLOR !== undefined)
78
- return h.has(e.FORCE_COLOR);
79
- if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
80
- return false;
81
- return r?.isTTY === true;
82
- }
83
- function f(r, e = []) {
84
- let l = "", n = "";
85
- for (let t = 0, i = e.length;t < i; t++)
86
- l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
87
- let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
88
- return new Proxy(c, { get(t, i) {
89
- let a = B[i];
90
- if (Array.isArray(a)) {
91
- let s = g.get(i);
92
- if (s === undefined)
93
- s = f(r, [...e, a]), g.set(i, s);
94
- return s;
95
- }
96
- if (typeof a === "function")
97
- return (...s) => {
98
- let y = `${i}:${s.join(",")}`, u = g.get(y);
99
- if (u === undefined) {
100
- if (g.size >= 64)
101
- g.clear();
102
- u = f(r, [...e, a(...s)]), g.set(y, u);
103
- }
104
- return u;
105
- };
106
- throw Error(`Unknown style: ${String(i)}`);
107
- } });
108
- }
109
- function Fe(r = {}) {
110
- return f(r);
111
- }
112
- var G2, B, h, o;
113
- var init_chunk_x450vn3m = __esm(() => {
114
- G2 = /^[a-f0-9]+$/i;
115
- B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
116
- let [l, n, c] = b(r);
117
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
118
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
119
- h = new Set(["", "1", "2", "3", "true"]);
120
- o = Fe();
121
- });
122
-
123
- // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
124
- var init_colors = __esm(() => {
125
- init_chunk_x450vn3m();
126
- });
127
-
128
- // ../kit/src/config.ts
129
- import { existsSync } from "fs";
130
- import { dirname, join, resolve } from "path";
131
- import process3 from "process";
132
- function findUp(names, from = process3.cwd(), stop = () => false) {
133
- const wanted = typeof names === "string" ? [names] : names;
134
- for (let dir = resolve(from);; dir = dirname(dir)) {
135
- const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
136
- if (found !== undefined)
137
- return found;
138
- if (stop(dir) || dirname(dir) === dir)
139
- return;
140
- }
141
- }
142
- var init_config = __esm(() => {
143
- init_args();
144
- });
145
-
146
- // ../kit/src/user-config.ts
147
- import { existsSync as existsSync2, readFileSync } from "fs";
148
- import { homedir } from "os";
149
- import { isAbsolute, join as join2 } from "path";
150
- import process4 from "process";
151
- function xdgFolder(value, fallback) {
152
- return value !== undefined && isAbsolute(value) ? value : fallback;
153
- }
154
- function configBase(where = {}) {
155
- const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
156
- return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
157
- }
158
- function userConfigPath(bin, where = {}) {
159
- return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
160
- }
161
- function userConfigReadPath(bin, legacy = [], where = {}) {
162
- const current = userConfigPath(bin, where);
163
- if (existsSync2(current))
164
- return current;
165
- const base = configBase(where);
166
- return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
167
- }
168
- function readUserConfig(bin, where = {}, legacy = []) {
169
- const path = userConfigReadPath(bin, legacy, where);
170
- if (!existsSync2(path))
171
- return {};
172
- try {
173
- const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
174
- return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
175
- } catch {
176
- return {};
177
- }
178
- }
179
- var init_user_config = () => {};
180
-
181
- // ../kit/src/theme.ts
182
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
183
- import { homedir as homedir2 } from "os";
184
- import { join as join3, resolve as resolve2 } from "path";
185
- import process5 from "process";
186
- function isColorSpec(spec) {
187
- if (typeof spec === "number")
188
- return Number.isInteger(spec) && spec >= 0 && spec <= 255;
189
- return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
190
- }
191
- function cubeLevel(channel) {
192
- return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
193
- }
194
- function nearest256(hex) {
195
- const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
196
- const levels = rgb.map(cubeLevel);
197
- const cube = levels.map((level) => CUBE[level]);
198
- const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
199
- const greyValue = 8 + grey * 10;
200
- const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
201
- return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
202
- }
203
- function hasTrueColor(env) {
204
- return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
205
- }
206
- function tinted(colors, spec, env = process5.env) {
207
- if (typeof spec === "number")
208
- return colors.ansi256(spec);
209
- return spec.trim().split(SPACES).reduce((chain, token) => {
210
- if (HEX.test(token))
211
- return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
212
- return chain[token] ?? chain;
213
- }, colors);
214
- }
215
- function isRecord(value) {
216
- return typeof value === "object" && value !== null && !Array.isArray(value);
217
- }
218
- function readThemeFile(path, warn) {
219
- try {
220
- const stat = statSync(path, { throwIfNoEntry: false });
221
- if (stat === undefined)
222
- return;
223
- if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
224
- warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
225
- return;
226
- }
227
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
228
- if (isRecord(parsed))
229
- return parsed;
230
- warn(`${path} is not a JSON object, theme ignored`);
231
- } catch (error) {
232
- warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
233
- }
234
- return;
235
- }
236
- function applyPreset(theme, name, warn, where) {
237
- if (name === undefined)
238
- return;
239
- if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
240
- warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
241
- return;
242
- }
243
- const preset = PRESETS[name];
244
- Object.assign(theme.colors, preset.colors);
245
- Object.assign(theme.glyphs, preset.glyphs);
246
- if (preset.accents !== undefined)
247
- theme.accents = [...preset.accents];
248
- if (Object.hasOwn(preset, "gradient"))
249
- theme.gradient = preset.gradient;
250
- return name;
251
- }
252
- function applyFile(theme, file, where, warn) {
253
- if (isRecord(file.colors)) {
254
- for (const [key, value] of Object.entries(file.colors)) {
255
- if (!Object.hasOwn(DEFAULT.colors, key))
256
- warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
257
- else if (!isColorSpec(value))
258
- warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
259
- else
260
- theme.colors[key] = value;
261
- }
262
- }
263
- if (isRecord(file.glyphs)) {
264
- for (const [key, value] of Object.entries(file.glyphs)) {
265
- if (!Object.hasOwn(DEFAULT.glyphs, key))
266
- warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
267
- else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
268
- warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
269
- else
270
- theme.glyphs[key] = value;
271
- }
272
- }
273
- if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
274
- theme.accents = [...file.accents];
275
- else if (file.accents !== undefined)
276
- warn(`${where}: accents must be a non-empty list of colours`);
277
- if (file.gradient === null)
278
- theme.gradient = undefined;
279
- else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
280
- theme.gradient = [file.gradient[0], file.gradient[1]];
281
- else if (file.gradient !== undefined)
282
- warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
283
- if (isRecord(file.bins)) {
284
- for (const [bin, value] of Object.entries(file.bins)) {
285
- if (isColorSpec(value))
286
- theme.bins[bin] = value;
287
- else
288
- warn(`${where}: bin ${bin} has no valid colour`);
289
- }
290
- }
291
- }
292
- function endsWalk(home) {
293
- return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
294
- }
295
- function warnOnce(message) {
296
- if (warned.has(message))
297
- return;
298
- warned.add(message);
299
- console.error(`warning: theme ${message}`);
300
- }
301
- function isPath(chosen) {
302
- return chosen.includes("/") || chosen.endsWith(".json");
303
- }
304
- function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
305
- const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
306
- const sources = [];
307
- const chosen = env.KIT_THEME ?? "";
308
- const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
309
- if (isPath(chosen))
310
- wanted.push(resolve2(from, chosen));
311
- const files = [];
312
- for (const path of wanted) {
313
- const file = path === undefined ? undefined : readThemeFile(path, warn);
314
- if (path !== undefined && file !== undefined)
315
- files.push({ path, file });
316
- }
317
- let preset = "default";
318
- if (chosen !== "" && !isPath(chosen)) {
319
- preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
320
- } else {
321
- const named = files.findLast(({ file }) => file.preset !== undefined);
322
- if (named !== undefined)
323
- preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
324
- }
325
- for (const { path, file } of files) {
326
- applyFile(theme, file, path, warn);
327
- sources.push(path);
328
- }
329
- return { theme, sources, preset };
330
- }
331
- function activeTheme() {
332
- const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
333
- if (current === undefined || key !== currentKey) {
334
- current = loadTheme();
335
- currentKey = key;
336
- }
337
- return current;
338
- }
339
- var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
340
- var init_theme = __esm(() => {
341
- init_config();
342
- init_user_config();
343
- ENDS = new Map;
344
- DEFAULT = {
345
- colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
346
- glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
347
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
348
- bins: {},
349
- gradient: ["#c084fc", "#67e8f9"]
350
- };
351
- BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
352
- MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
353
- ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
354
- PRESETS = {
355
- default: {},
356
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
357
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
358
- ascii: { glyphs: ASCII }
359
- };
360
- STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
361
- HEX = /^#[0-9a-f]{6}$/i;
362
- CONTROL = /\p{Cc}/u;
363
- MAX_FILE_BYTES = 64 * 1024;
364
- SPACES = /\s+/;
365
- CUBE = [0, 95, 135, 175, 215, 255];
366
- warned = new Set;
367
- });
368
-
369
- // ../kit/src/style.ts
370
- import process6 from "process";
371
- function takesControlCodes(stream, env = process6.env) {
372
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
373
- }
374
- function paint(stream, env = process6.env) {
375
- return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
376
- }
377
- function marked(mark, text, stream, detail, env = process6.env) {
378
- const colors = paint(stream, env);
379
- let head = MARK_WORDS[mark];
380
- if (takesControlCodes(stream, env)) {
381
- const { theme } = activeTheme();
382
- head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
383
- }
384
- return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
385
- }
386
- function warn(text, detail) {
387
- console.error(marked("warn", text, process6.stderr, detail));
388
- }
389
- function role(name, stream, env = process6.env) {
390
- const colors = paint(stream, env);
391
- return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
392
- }
393
- function header(bin, context, stream, env = process6.env) {
394
- if (!takesControlCodes(stream, env))
395
- return "";
396
- const colors = paint(stream, env);
397
- const hash = [...bin].reduce((sum, char) => sum + char.charCodeAt(0), 0);
398
- const { theme } = activeTheme();
399
- const spec = theme.bins[bin] ?? theme.accents[hash % theme.accents.length];
400
- const accent = tinted(typeof spec === "string" && spec.split(" ").includes("bold") ? colors : colors.bold, spec, env);
401
- return `${accent(bin)}${context === undefined ? "" : colors.dim(` \u203A ${context}`)}`;
402
- }
403
- var MARK_WORDS, STATUS_WORDS, STATUS_OF;
404
- var init_style = __esm(() => {
405
- init_colors();
406
- init_mode();
407
- init_theme();
408
- MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
409
- STATUS_WORDS = {
410
- passed: ["passed", "success", "succeeded", "ok"],
411
- failed: ["failed", "failure", "error", "errored"],
412
- running: ["running", "in_progress", "started", "holding"],
413
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
414
- skipped: ["skipped", "cancelled", "canceled", "manual"]
415
- };
416
- STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
417
- });
418
-
419
- // ../kit/src/format.ts
420
- import process7 from "process";
421
- function formatSeconds(total) {
422
- let rest = Math.max(0, Math.round(total));
423
- const amounts = UNITS.map(([unit, size]) => {
424
- const amount = Math.floor(rest / size);
425
- rest -= amount * size;
426
- return `${amount}${unit}`;
427
- });
428
- const first = amounts.findIndex((amount) => !amount.startsWith("0"));
429
- if (first === -1)
430
- return "0s";
431
- const next = amounts[first + 1];
432
- return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
433
- }
434
- function formatDuration(ms) {
435
- return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
436
- }
437
- function upTo(text, separator) {
438
- const end = text.indexOf(separator);
439
- return end === -1 ? text : text.slice(0, end);
440
- }
441
- function truncate(text, width) {
442
- return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
443
- }
444
- function textWidth(text) {
445
- return Bun.stringWidth(text);
446
- }
447
- function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
448
- const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
449
- if (outputMode(stream, env) === "agent")
450
- return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
451
- `);
452
- const widths = [];
453
- for (const row of cells) {
454
- for (const [index, cell] of row.entries())
455
- widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
456
- }
457
- const shown = fit === undefined ? cells : narrow(cells, widths, fit);
458
- const colors = paint(stream);
459
- const lines = shown.map((row) => row.map((cell, index) => {
460
- const width = widths[index] ?? 0;
461
- const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
462
- if (align[index] === "right")
463
- return `${gap}${cell}`;
464
- return index === row.length - 1 ? cell : `${cell}${gap}`;
465
- }).join(" ").trimEnd());
466
- const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
467
- return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
468
- `);
469
- }
470
- function narrow(rows, widths, limit) {
471
- const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
472
- const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
473
- const floor = 8;
474
- while (used() > limit) {
475
- let widest = -1;
476
- for (const [index, width] of widths.entries()) {
477
- if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
478
- widest = index;
479
- }
480
- if (widest === -1)
481
- break;
482
- widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
483
- }
484
- return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
485
- }
486
- function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
487
- return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
488
- }
489
- function printJson(value) {
490
- console.log(jsonText(value));
491
- }
492
- var UNITS, LINE_BREAKS, ESCAPE;
493
- var init_format = __esm(() => {
494
- init_text();
495
- init_mode();
496
- init_style();
497
- UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
498
- LINE_BREAKS = /\s*\n\s*/g;
499
- ESCAPE = String.fromCharCode(27);
500
- });
501
-
502
- // ../kit/src/help.ts
503
- import process8 from "process";
504
- function usageLine(usage, colors = paint(process8.stdout), { summary: withSummary = true } = {}) {
505
- const lines = usage.replace(USAGE_PREFIX, "").split(`
506
- `);
507
- const blank = lines.indexOf("");
508
- const synopses = blank === -1 ? lines : lines.slice(0, blank);
509
- const details = blank === -1 ? [] : lines.slice(blank + 1);
510
- const colon = synopses[0].indexOf(": ");
511
- const inline = synopses[0].slice(colon + 2);
512
- const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
513
- if (colon !== -1)
514
- synopses[0] = synopses[0].slice(0, colon);
515
- const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
516
- `)}`;
517
- const lead = summary === undefined || !withSummary ? [] : ["", colors.bold(prose(summary, colors))];
518
- const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
519
- return [head, ...lead, ...rest].join(`
520
- `);
521
- }
522
- function prose(line, colors) {
523
- if (colors.cyan("x") === "x")
524
- return line;
525
- return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
526
- }
527
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [], bin } = {}) {
528
- const { summary } = description(usage);
529
- const head = bin === undefined ? [usageLine(usage, colors)] : [`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary === "" ? "" : ` ${summary}`}`, "", usageLine(usage, colors, { summary: false })];
530
- return [...head, "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
531
- `);
532
- }
533
- function exitRows(exits, colors = paint(process8.stdout)) {
534
- if (exits.length === 0)
535
- return [];
536
- return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
537
- }
538
- function wantsHelpJson(env = process8.env) {
539
- return env.KIT_HELP === "json";
540
- }
541
- function description(usage, { examples = [], replaces, exits } = {}, options) {
542
- const lines = usage.replace(USAGE_PREFIX, "").split(`
543
- `);
544
- const first = lines[0];
545
- const colon = first.indexOf(": ");
546
- const prose = lines[lines.indexOf("") + 1] ?? "";
547
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
548
- return {
549
- synopsis: colon === -1 ? first : first.slice(0, colon),
550
- summary: colon === -1 ? fallback : first.slice(colon + 2),
551
- ...replaces === undefined ? {} : { replaces },
552
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
553
- ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
554
- ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
555
- };
556
- }
557
- function exampleRows(examples, colors = paint(process8.stdout)) {
558
- if (examples.length === 0 || outputMode() === "agent")
559
- return [];
560
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
561
- }
562
- function optionRows(options, colors = paint(process8.stdout)) {
563
- const rows = Object.entries(options).map(([name, option]) => {
564
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
565
- const choices = option.choices?.join("|");
566
- const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
567
- const named = inline ? `<${choices}>` : "<value>";
568
- const placeholder = option.optional === undefined ? named : `[${named}]`;
569
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
570
- const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
571
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
572
- });
573
- const width = Math.max(0, ...rows.map((row) => row.width));
574
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
575
- }
576
- var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
577
- var init_help = __esm(() => {
578
- init_mode();
579
- init_style();
580
- OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
581
- USAGE_PREFIX = /^usage:\s*/i;
582
- FULL_STOP = /\.$/;
583
- PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
584
- });
585
-
586
- // ../kit/src/text.ts
587
- function stripAnsi(text) {
588
- return text.replace(ANSI, "");
589
- }
590
- function distance(a, b) {
591
- const left = [...a];
592
- const right = [...b];
593
- let before = [];
594
- let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
595
- for (const [i, x] of left.entries()) {
596
- const current = [i + 1];
597
- for (const [j, y] of right.entries()) {
598
- let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
599
- if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
600
- cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
601
- current.push(cost);
602
- }
603
- before = previous;
604
- previous = current;
605
- }
606
- return previous[right.length] ?? 0;
607
- }
608
- function closest(name, names) {
609
- const started = names.find((known) => known.startsWith(name));
610
- if (started !== undefined)
611
- return started;
612
- const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
613
- return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
614
- }
615
- var ANSI;
616
- var init_text2 = __esm(() => {
617
- ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
618
- });
619
-
620
- // ../kit/src/input.ts
621
- import process9 from "process";
622
- function durationMs(text, unit) {
623
- if (BARE_DURATION.test(text))
624
- return Number(text) * UNIT_MS[unit];
625
- if (!DURATION.test(text))
626
- return 0;
627
- let ms = 0;
628
- for (const [, amount, part] of text.matchAll(DURATION_PART))
629
- ms += Number(amount) * UNIT_MS[part];
630
- return ms;
631
- }
632
- function duration(value, name, fallback, unit = "s") {
633
- if (value === undefined)
634
- return fallback;
635
- const ms = durationMs(value.trim(), unit);
636
- if (ms < 1)
637
- badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
638
- return ms;
639
- }
640
- async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
641
- if (path === "-") {
642
- if (process9.stdin.isTTY)
643
- fail(noStdin);
644
- return Bun.stdin.text();
645
- }
646
- const file = Bun.file(path);
647
- if (!await file.exists())
648
- fail(`no file ${path}`);
649
- return file.text();
650
- }
651
- var BARE_DURATION, DURATION, DURATION_PART, UNIT_MS;
652
- var init_input = __esm(() => {
653
- init_args();
654
- BARE_DURATION = /^\d+(?:\.\d+)?$/;
655
- DURATION = /^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/;
656
- DURATION_PART = /(\d+(?:\.\d+)?)(ms|min|[smhd])/g;
657
- UNIT_MS = { ms: 1, s: 1000, m: 60000, min: 60000, h: 3600000, d: 86400000 };
658
- });
659
-
660
- // ../kit/src/args.ts
661
- import process10 from "process";
662
- import { parseArgs } from "util";
663
- function jsonOption(holds) {
664
- return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
665
- }
666
- function fail(message, code = 2, hint) {
667
- throw new Exit(message, code, hint);
668
- }
669
- function badUsage(message) {
670
- throw new UsageError(message);
671
- }
672
-
673
- class Completing {
674
- options;
675
- positionals;
676
- candidates;
677
- constructor(options, positionals = [], candidates = {}) {
678
- this.options = options;
679
- this.positionals = positionals;
680
- this.candidates = candidates;
681
- }
682
- }
683
- function applyOutput(color, plain, env = process10.env) {
684
- const when = plain === true ? "never" : color ?? "auto";
685
- if (when === "auto")
686
- return;
687
- if (when !== "always" && when !== "never")
688
- badUsage(`--color takes auto, always or never, not ${when}`);
689
- if (when === "always") {
690
- env.FORCE_COLOR = "1";
691
- delete env.NO_COLOR;
692
- } else {
693
- env.NO_COLOR = "1";
694
- delete env.FORCE_COLOR;
695
- }
696
- }
697
- function parse(args, usage, options, settings = {}) {
698
- const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
699
- const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
700
- const listing = listed(all, settings.allowNegative === true);
701
- if (completion.active)
702
- throw new Completing(listing, settings.positionals, settings.candidates);
703
- const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
704
- let parsed;
705
- try {
706
- parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
707
- } catch (error) {
708
- const message = parseError(error);
709
- throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
710
- }
711
- const values = parsed.values;
712
- applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
713
- if (values.help === true) {
714
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, { ...settings, bin: heading.bin }));
715
- throw new HelpShown;
716
- }
717
- checkChoices(parsed.values, all);
718
- checkConflicts(parsed.values, all);
719
- if (settings.positionals !== undefined)
720
- checkPositionals(parsed.positionals, settings.positionals);
721
- return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
722
- }
723
- function splitRest(args, passes) {
724
- const separator = passes ? args.indexOf("--") : -1;
725
- return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
726
- }
727
- function splitTrailing(args, options, count) {
728
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
729
- let seen = 0;
730
- if (count === 0)
731
- return { own: args, rest: undefined };
732
- for (let at = 0;at < args.length; at++) {
733
- const word = args[at];
734
- if (word === "--")
735
- break;
736
- if (word.startsWith("-")) {
737
- if (takesValue(word))
738
- at++;
739
- continue;
740
- }
741
- seen++;
742
- if (seen === count)
743
- return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
744
- }
745
- return { own: args, rest: undefined };
746
- }
747
- function listed(options, allowNegative) {
748
- if (!allowNegative)
749
- return options;
750
- return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
751
- if (option.type !== "boolean" || option.negative === undefined)
752
- return [[name, option]];
753
- return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
754
- }));
755
- }
756
- function withAliases(args, options) {
757
- const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
758
- if (named.size === 0)
759
- return args;
760
- const separator = args.indexOf("--");
761
- const own = separator === -1 ? args : args.slice(0, separator);
762
- return [...own.map((arg) => {
763
- const at = arg.indexOf("=");
764
- const current = named.get(at === -1 ? arg : arg.slice(0, at));
765
- return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
766
- }), ...separator === -1 ? [] : args.slice(separator)];
767
- }
768
- function withBare(args, options) {
769
- const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
770
- if (bare.size === 0)
771
- return args;
772
- const separator = args.indexOf("--");
773
- const own = separator === -1 ? args : args.slice(0, separator);
774
- return [...own.flatMap((arg, index) => {
775
- const optional = bare.get(arg);
776
- const next = own[index + 1];
777
- const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
778
- return optional === undefined || value ? [arg] : [arg, optional.bare];
779
- }), ...separator === -1 ? [] : args.slice(separator)];
780
- }
781
- function checkConflicts(values, options) {
782
- const given = (name) => values[name] !== undefined && values[name] !== false;
783
- for (const [name, { conflicts = [] }] of Object.entries(options)) {
784
- const other = given(name) ? conflicts.find(given) : undefined;
785
- if (other !== undefined)
786
- badUsage(`--${name} cannot be used with --${other}`);
787
- }
788
- }
789
- function checkChoices(values, options) {
790
- for (const [name, option] of Object.entries(options)) {
791
- if (option.choices === undefined)
792
- continue;
793
- const given = values[name];
794
- for (const value of Array.isArray(given) ? given : [given]) {
795
- if (typeof value === "string")
796
- oneOf(value, name, option.choices);
797
- }
798
- }
799
- }
800
- function oneOf(value, name, choices) {
801
- if (!choices.includes(value))
802
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
803
- return value;
804
- }
805
- function checkPositionals(given, names) {
806
- const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
807
- const required = names.filter((name) => !name.startsWith("[")).length;
808
- if (given.length < required)
809
- badUsage(`missing ${names[given.length]}`);
810
- if (!variadic && given.length > names.length)
811
- badUsage(`unexpected argument ${given[names.length]}`);
812
- }
813
- function joinDashValues(args, options) {
814
- const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
815
- const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
816
- const joined = [];
817
- for (let i = 0;i < args.length; i++) {
818
- const arg = args[i] ?? "";
819
- if (arg === "--")
820
- return [...joined, ...args.slice(i)];
821
- const name = longOf.get(arg);
822
- const next = args[i + 1];
823
- if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
824
- joined.push(`--${name}=${next}`);
825
- i++;
826
- } else {
827
- joined.push(arg);
828
- }
829
- }
830
- return joined;
831
- }
832
- function parseError(error) {
833
- const message = upTo(error instanceof Error ? error.message : String(error), ". ");
834
- return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
835
- }
836
- function nearestOption(message, options, allowNegative) {
837
- const typed = UNKNOWN_OPTION.exec(message)?.[1];
838
- if (typed === undefined)
839
- return;
840
- const word = typed.replace(DASHES, "");
841
- if (word.length < 2 && !typed.startsWith("--"))
842
- return;
843
- const known = Object.entries(options).flatMap(([name, option]) => [
844
- ...option.short === undefined ? [] : [`-${option.short}`],
845
- `--${name}`,
846
- ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
847
- ]);
848
- const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
849
- return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
850
- }
851
- var DASHES, EXIT, Exit, UsageError, HelpShown, completion, heading, OUTPUT_OPTIONS, UNKNOWN_OPTION;
852
- var init_args = __esm(() => {
853
- init_format();
854
- init_help();
855
- init_text2();
856
- init_help();
857
- init_input();
858
- DASHES = /^-+/;
859
- EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
860
- Exit = class Exit extends Error {
861
- code;
862
- hint;
863
- [EXIT] = true;
864
- constructor(message, code, hint) {
865
- super(message);
866
- this.code = code;
867
- this.hint = hint;
868
- }
869
- static [Symbol.hasInstance](value) {
870
- if (this !== Exit)
871
- return Function.prototype[Symbol.hasInstance].call(this, value);
872
- return typeof value === "object" && value !== null && value[EXIT] === true;
873
- }
874
- };
875
- UsageError = class UsageError extends Exit {
876
- constructor(message, hint) {
877
- super(message, 2, hint);
878
- }
879
- };
880
- HelpShown = class HelpShown extends Exit {
881
- constructor() {
882
- super("help shown", 0);
883
- }
884
- };
885
- completion = { active: false };
886
- heading = { bin: undefined };
887
- OUTPUT_OPTIONS = {
888
- color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
889
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
890
- };
891
- UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
892
- });
893
-
894
- // ../kit/src/folders.ts
895
- import { homedir as homedir5 } from "os";
896
- import { join as join7 } from "path";
897
- import process18 from "process";
898
- function ignoredFolders(extra = [], where = {}) {
899
- const configured = readUserConfig("config", where).ignore;
900
- const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
901
- return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
902
- }
903
- function cacheFolder({ home = homedir5(), env = process18.env } = {}) {
904
- return xdgFolder(env.XDG_CACHE_HOME, join7(home, ".cache"));
905
- }
906
- var SKIPPED_FOLDERS;
907
- var init_folders = __esm(() => {
908
- init_user_config();
909
- SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
910
- });
911
-
912
- // src/cli.ts
913
- import process24 from "process";
914
-
915
- // ../kit/src/index.ts
916
- init_args();
917
-
918
- // ../kit/src/argv.ts
919
- import { readFileSync as readFileSync3, realpathSync } from "fs";
920
- import { resolve as resolve3 } from "path";
921
- import process11 from "process";
922
- function commandLine() {
923
- try {
924
- return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
925
- } catch {
926
- return;
927
- }
928
- }
929
- function realPath(word) {
930
- try {
931
- return realpathSync(resolve3(word));
932
- } catch {
933
- return;
934
- }
935
- }
936
- function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
937
- const target = script === undefined ? undefined : realPath(script) ?? script;
938
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
939
- const after = at === -1 ? [] : cmdline.slice(at + 1);
940
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
941
- }
942
- // ../kit/src/chart.ts
943
- init_format();
944
- init_mode();
945
- init_style();
946
- init_theme();
947
- // ../kit/src/ci.ts
948
- init_args();
949
- init_format();
950
-
951
- // ../kit/src/progress.ts
952
- init_format();
953
-
954
- // ../kit/src/process.ts
955
- import { readFileSync as readFileSync4 } from "fs";
956
- import { constants } from "os";
957
- import process12 from "process";
958
- var KILL_GRACE_MS = 2000;
959
- var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
960
- var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
961
- function exitCodeOf(code, signal) {
962
- if (code !== null)
963
- return code;
964
- if (typeof signal === "number")
965
- return 128 + signal;
966
- return signal === null ? 129 : 128 + constants.signals[signal];
967
- }
968
- function groupsOf(pid) {
969
- try {
970
- const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
971
- const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
972
- return { group: Number(fields[2]), foreground: Number(fields[5]) };
973
- } catch {
974
- return;
975
- }
976
- }
977
- function heardTheTerminal(child) {
978
- if (child.pid === undefined)
979
- return false;
980
- const own = groupsOf("self");
981
- return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
982
- }
983
- function holdSignals(cleanup) {
984
- let received;
985
- let child;
986
- const held = {
987
- get signal() {
988
- return received;
989
- },
990
- forward: (to) => {
991
- child = to;
992
- },
993
- release: () => {
994
- for (const signal of SIGNALS)
995
- process12.off(signal, onSignal);
996
- }
997
- };
998
- function onSignal(signal) {
999
- received = signal;
1000
- if (child !== undefined) {
1001
- if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
1002
- child.kill(signal);
1003
- return;
1004
- }
1005
- if (cleanup === undefined)
1006
- return;
1007
- held.release();
1008
- cleanup(signal);
1009
- process12.kill(process12.pid, signal);
1010
- }
1011
- for (const signal of SIGNALS)
1012
- process12.on(signal, onSignal);
1013
- return held;
1014
- }
1015
- async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
1016
- const chunks = [];
1017
- const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
1018
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin: input === undefined ? stdin : new TextEncoder().encode(input), stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
1019
- const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
1020
- const timers = [];
1021
- const killGroup = (killing) => {
1022
- if (state.done)
1023
- return;
1024
- try {
1025
- if (grouped)
1026
- process12.kill(-proc.pid, killing);
1027
- else
1028
- proc.kill(killing);
1029
- } catch {}
1030
- };
1031
- const stop = () => {
1032
- killGroup("SIGTERM");
1033
- timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
1034
- };
1035
- const onAbort = () => stop();
1036
- if (timeoutMs !== undefined) {
1037
- timers.push(setTimeout(() => {
1038
- state.timedOut = true;
1039
- stop();
1040
- }, timeoutMs));
1041
- }
1042
- if (signal?.aborted === true)
1043
- onAbort();
1044
- else
1045
- signal?.addEventListener("abort", onAbort, { once: true });
1046
- onStart?.({ kill: (killing) => killGroup(killing) });
1047
- const drain = async (stream, name) => {
1048
- for await (const data of stream) {
1049
- if (state.failure !== undefined)
1050
- continue;
1051
- try {
1052
- onChunk?.({ stream: name, data });
1053
- } catch (error) {
1054
- state.failure = error;
1055
- stop();
1056
- continue;
1057
- }
1058
- if (state.truncated)
1059
- continue;
1060
- let kept = data;
1061
- if (state.kept + data.length > maxBytes) {
1062
- let cut = maxBytes - state.kept;
1063
- while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
1064
- cut--;
1065
- kept = data.subarray(0, cut);
1066
- state.truncated = true;
1067
- }
1068
- state.kept += kept.length;
1069
- if (kept.length > 0)
1070
- chunks.push({ stream: name, data: kept });
1071
- }
1072
- };
1073
- try {
1074
- await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
1075
- await proc.exited;
1076
- } finally {
1077
- state.done = true;
1078
- for (const timer of timers)
1079
- clearTimeout(timer);
1080
- signal?.removeEventListener("abort", onAbort);
1081
- }
1082
- if (state.failure !== undefined)
1083
- throw state.failure;
1084
- const joined = () => Buffer.concat(chunks.map(({ data }) => data));
1085
- let output;
1086
- let text;
1087
- let stdout;
1088
- return {
1089
- code: exitCodeOf(proc.exitCode, proc.signalCode),
1090
- chunks,
1091
- timedOut: state.timedOut,
1092
- truncated: state.truncated,
1093
- get output() {
1094
- return output ??= joined();
1095
- },
1096
- get text() {
1097
- return text ??= (output ??= joined()).toString();
1098
- },
1099
- get stdout() {
1100
- return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
1101
- }
1102
- };
1103
- }
1104
-
1105
- // ../kit/src/progress.ts
1106
- init_style();
1107
- init_theme();
1108
- var ESC = String.fromCharCode(27);
1109
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1110
- var RESET_STYLE = `${ESC}[0m`;
1111
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1112
-
1113
- // ../kit/src/ci.ts
1114
- init_style();
1115
-
1116
- // ../kit/src/tool.ts
1117
- init_format();
1118
- // ../kit/src/cli.ts
1119
- init_args();
1120
- import { readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
1121
- import { dirname as dirname3, join as join6 } from "path";
1122
- import process17 from "process";
1123
-
1124
- // ../kit/src/askpass.ts
1125
- import process13 from "process";
1126
- var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1127
- async function askpassClient(argv) {
1128
- const socketPath = process13.env[SOCKET_VARIABLE];
1129
- if (socketPath === undefined)
1130
- return;
1131
- const request = { prompt: argv[0] ?? "", ...process13.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1132
- const { promise, resolve } = Promise.withResolvers();
1133
- let received = "";
1134
- try {
1135
- await Bun.connect({
1136
- unix: socketPath,
1137
- socket: {
1138
- open: (socket) => void socket.write(`${JSON.stringify(request)}
1139
- `),
1140
- data: (_, chunk) => {
1141
- received += chunk.toString();
1142
- },
1143
- close: () => resolve(received),
1144
- error: () => resolve("")
1145
- }
1146
- });
1147
- } catch {
1148
- return 1;
1149
- }
1150
- const reply = await promise;
1151
- if (reply === "")
1152
- return 1;
1153
- const { answer } = JSON.parse(reply);
1154
- if (request.notice === true)
1155
- return 0;
1156
- if (answer === undefined)
1157
- return 1;
1158
- process13.stdout.write(`${answer}
1159
- `);
1160
- return 0;
1161
- }
1162
-
1163
- // ../kit/src/completions.ts
1164
- var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1165
- var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
1166
- set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1167
- set -l current (commandline -ct)
1168
- for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1169
- if test "$line" = __files__
1170
- __fish_complete_path $current
1171
- else
1172
- echo $line
1173
- end
1174
- end
1175
- end`;
1176
- var BASH_FUNCTION = `__kaynooo_cli_complete() {
1177
- local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1178
- local -a lines
1179
- COMPREPLY=()
1180
- lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1181
- for line in "\${lines[@]}"; do
1182
- if [[ $line == __files__ ]]; then
1183
- COMPREPLY+=($(compgen -f -- "$cur"))
1184
- else
1185
- words+="\${line%%$'\\t'*}"$'\\n'
1186
- fi
1187
- done
1188
- COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1189
- }`;
1190
- var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1191
- local line
1192
- local -a described plain
1193
- for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1194
- if [[ $line == __files__ ]]; then
1195
- _files
1196
- elif [[ $line == *$'\\t'* ]]; then
1197
- described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1198
- else
1199
- plain+=("$line")
1200
- fi
1201
- done
1202
- (( \${#described} )) && _describe -V value described
1203
- (( \${#plain} )) && compadd -- "\${plain[@]}"
1204
- return 0
1205
- }
1206
- __kaynooo_cli_register() {
1207
- add-zsh-hook -d precmd __kaynooo_cli_register
1208
- (( $+functions[compdef] )) || { autoload -Uz compinit && compinit }
1209
- compdef __kaynooo_cli_complete $__kaynooo_cli_bins
1210
- }
1211
- autoload -Uz add-zsh-hook
1212
- add-zsh-hook precmd __kaynooo_cli_register
1213
- typeset -gaU __kaynooo_cli_bins`;
1214
- function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1215
- if (shell === "fish")
1216
- return `${header}
1217
- ${FISH_FUNCTION}
1218
- ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1219
- `).join("")}`;
1220
- if (shell === "bash")
1221
- return `${header}
1222
- ${BASH_FUNCTION}
1223
- complete -F __kaynooo_cli_complete ${bins.join(" ")}
1224
- `;
1225
- return `${header}
1226
- ${ZSH_FUNCTION}
1227
- __kaynooo_cli_bins+=(${bins.join(" ")})
1228
- `;
1229
- }
1230
-
1231
- // ../kit/src/notify.ts
1232
- init_format();
1233
- init_mode();
1234
- import process14 from "process";
1235
- var NOTIFY_AFTER_MS = 1e4;
1236
- var CANCELLED = 130;
1237
- function base64(text) {
1238
- return Buffer.from(text).toString("base64");
1239
- }
1240
- function notification(title, body, env = process14.env) {
1241
- const id = `kit${process14.pid}`;
1242
- const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
1243
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1244
- }
1245
- function notifyEnd(command, code, ms, { stream = process14.stderr, env = process14.env } = {}) {
1246
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1247
- return;
1248
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1249
- }
1250
-
1251
- // ../kit/src/cli.ts
1252
- init_style();
1253
- init_text2();
1254
-
1255
- // ../kit/src/usage.ts
1256
- import { appendFileSync, mkdirSync } from "fs";
1257
- import { homedir as homedir4 } from "os";
1258
- import { dirname as dirname2, join as join5 } from "path";
1259
- import process16 from "process";
1260
-
1261
- // ../kit/src/logs.ts
1262
- init_user_config();
1263
- import { lstatSync, openSync } from "fs";
1264
- import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
1265
- import { homedir as homedir3, tmpdir } from "os";
1266
- import { join as join4 } from "path";
1267
- import process15 from "process";
1268
- var DAY_MS = 24 * 60 * 60 * 1000;
1269
- var CLI_FOLDER = "kaynooo-cli";
1270
- function isPrivateDirectory(path) {
1271
- try {
1272
- const info = lstatSync(path, { throwIfNoEntry: false });
1273
- return info !== undefined && info.isDirectory() && info.uid === (process15.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
1274
- } catch {
1275
- return false;
1276
- }
1277
- }
1278
- async function privateLogDirectory(name, env = process15.env) {
1279
- const path = join4(xdgFolder(env.XDG_RUNTIME_DIR, join4(homedir3(), ".cache")), CLI_FOLDER, name);
1280
- try {
1281
- await mkdir(path, { recursive: true, mode: 448 });
1282
- if (isPrivateDirectory(path))
1283
- return path;
1284
- } catch {}
1285
- return mkdtemp(join4(tmpdir(), `${name.replaceAll("/", "-")}-`));
1286
- }
1287
- async function sweepLogs(dir, maxAgeMs = DAY_MS, now = Date.now()) {
1288
- let names;
1289
- try {
1290
- names = await readdir(dir);
1291
- } catch {
1292
- return;
1293
- }
1294
- for (const name of names) {
1295
- const path = join4(dir, name);
1296
- try {
1297
- const info = await stat(path);
1298
- if (info.isDirectory())
1299
- await sweepLogs(path, maxAgeMs, now);
1300
- if (now - info.mtimeMs > maxAgeMs)
1301
- await rm(path, { force: true, recursive: info.isDirectory() });
1302
- } catch {
1303
- continue;
1304
- }
1305
- }
1306
- }
1307
-
1308
- // ../kit/src/usage.ts
1309
- init_user_config();
1310
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1311
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1312
- var LONGEST_NAME = 40;
1313
- var usageError;
1314
- function noteUsageError(message) {
1315
- usageError = message;
1316
- }
1317
- function stateHome(env = process16.env) {
1318
- return xdgFolder(env.XDG_STATE_HOME, join5(homedir4(), ".local", "state"));
1319
- }
1320
- function usagePath(env = process16.env) {
1321
- return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
1322
- }
1323
- function usageRecorded(env = process16.env) {
1324
- const off = env.KAYNOOO_CLI_NO_USAGE;
1325
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1326
- }
1327
- function flagNames(argv) {
1328
- const end = argv.indexOf("--");
1329
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1330
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1331
- }
1332
- function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1333
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1334
- usageError = undefined;
1335
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1336
- }
1337
- function recordUsage(entry, env = process16.env) {
1338
- if (!usageRecorded(env))
1339
- return;
1340
- try {
1341
- const path = usagePath(env);
1342
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1343
- appendFileSync(path, `${JSON.stringify(entry)}
1344
- `, { mode: 384 });
1345
- } catch {}
1346
- }
1347
-
1348
- // ../kit/src/cli.ts
1349
- var LEVEL_OPTIONS = {
1350
- ...OUTPUT_OPTIONS,
1351
- help: { type: "boolean", short: "h", description: "show this help" }
1352
- };
1353
- var TOP_OPTIONS = {
1354
- ...LEVEL_OPTIONS,
1355
- version: { type: "boolean", short: "v", description: "print the version" },
1356
- completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1357
- };
1358
- function printError(prefix, message, hint, cause) {
1359
- const colors = paint(process17.stderr);
1360
- const styled = takesControlCodes(process17.stderr);
1361
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1362
- const under = (label, text, tint) => text === undefined ? "" : `
1363
- ${styled ? tint(label) : `${label}:`} ${text}`;
1364
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1365
- }
1366
- function printJsonError(message, hint, cause) {
1367
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1368
- }
1369
- function wantsJson(argv) {
1370
- const end = argv.indexOf("--");
1371
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1372
- }
1373
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
1374
- if (error instanceof HelpShown)
1375
- return 0;
1376
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1377
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1378
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1379
- if (error instanceof Exit && error.code === 2)
1380
- noteUsageError(error.message);
1381
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1382
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1383
- return error instanceof Exit ? error.code : 1;
1384
- }
1385
- var COMPLETE = "__complete";
1386
- var FILES = "__files__";
1387
- async function completingOf(run) {
1388
- completion.active = true;
1389
- try {
1390
- await run([]);
1391
- } catch (error) {
1392
- if (error instanceof Completing)
1393
- return error;
1394
- } finally {
1395
- completion.active = false;
1396
- }
1397
- return new Completing({});
1398
- }
1399
- function candidateLine(candidate) {
1400
- return typeof candidate === "string" ? candidate : candidate.join("\t");
1401
- }
1402
- function positionalBeingTyped(before, { options, positionals }) {
1403
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1404
- const typed = [];
1405
- let at = 0;
1406
- while (at < before.length) {
1407
- const word = before[at];
1408
- if (word === "--") {
1409
- typed.push(...before.slice(at + 1));
1410
- break;
1411
- }
1412
- if (!word.startsWith("-"))
1413
- typed.push(word);
1414
- else if (takesValue(word))
1415
- at++;
1416
- at++;
1417
- }
1418
- const last = positionals.at(-1);
1419
- if (typed.length < positionals.length)
1420
- return { name: positionals[typed.length], typed };
1421
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1422
- }
1423
- async function leafCandidates(run, words) {
1424
- const completing = await completingOf(run);
1425
- if ((words.at(-1) ?? "").startsWith("-"))
1426
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1427
- const flag = words.at(-2);
1428
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1429
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1430
- if (option?.type === "string") {
1431
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1432
- return values === undefined ? [FILES] : values.map(candidateLine);
1433
- }
1434
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1435
- return values === undefined ? [FILES] : values.map(candidateLine);
1436
- }
1437
- var COMPLETIONS = "--completions";
1438
- function flagValue([flag = "", ...rest]) {
1439
- return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1440
- }
1441
- function printCompletionScript(name, args) {
1442
- const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1443
- if (shell === undefined || args.length !== 1) {
1444
- printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1445
- return 2;
1446
- }
1447
- console.log(completionScript(shell, [name]).trimEnd());
1448
- return 0;
1449
- }
1450
- async function printCandidates(found) {
1451
- for (const line of await found)
1452
- console.log(line);
1453
- return 0;
1454
- }
1455
- function packageVersion(entry = Bun.main) {
1456
- let resolved = entry;
1457
- try {
1458
- resolved = realpathSync2(entry);
1459
- } catch {}
1460
- for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1461
- try {
1462
- const { version } = JSON.parse(readFileSync5(join6(dir, "package.json"), "utf8"));
1463
- if (typeof version === "string")
1464
- return version;
1465
- } catch {}
1466
- if (dirname3(dir) === dir)
1467
- return "0.0.0";
1468
- }
1469
- }
1470
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1471
- const answered = await askpassClient(argv);
1472
- if (answered !== undefined)
1473
- return answered;
1474
- if (argv[0] === COMPLETE)
1475
- return printCandidates(leafCandidates(run, argv.slice(1)));
1476
- if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1477
- return printCompletionScript(name, flagValue(argv));
1478
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1479
- console.log(version ?? packageVersion());
1480
- return 0;
1481
- }
1482
- let code;
1483
- const started = performance.now();
1484
- heading.bin = { name, version: () => version ?? packageVersion() };
1485
- try {
1486
- code = await run(argv);
1487
- } catch (error) {
1488
- code = reportThrown(name, error, redact, wantsJson(argv));
1489
- } finally {
1490
- heading.bin = undefined;
1491
- }
1492
- notifyEnd(name, code, performance.now() - started);
1493
- if (usage !== false) {
1494
- try {
1495
- recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
1496
- } catch {}
1497
- }
1498
- return code;
1499
- }
1500
-
1501
- // ../kit/src/index.ts
1502
- init_config();
1503
-
1504
- // ../kit/src/excerpt.ts
1505
- init_text2();
1506
- var BASH_ECHO = /^\$ /;
1507
- var DURATION2 = / \[[\d.]+m?s\]$/;
1508
- var BOUNDARY = /^(?:\((?:pass|fail|skip|todo)\) |\S+\.test\.[jt]sx?:$)/;
1509
- var BUN_TEST_SUMMARY = /^\s*\d+ (?:pass|fail|skip|todo)$|^Ran \d+ tests?/;
1510
- var BUN_CHECK_BLOCK = /<error file=[\s\S]*?<\/error>/g;
1511
- var BUN_CHECK_SOURCE = /<source>[\s\S]*?<\/source>\n?/g;
1512
- var BUN_CHECK_ATTRIBUTE = /(\w+)="([^"]*)"/g;
1513
- var BUN_CHECK_SUMMARY = /^Found \d+ errors?/;
1514
- var TSC_ERROR = /\berror TS\d+/;
1515
- var TSC_CONTINUATION = /^\s{2,}\S/;
1516
- var TSC_FRAME = /^\s*[~^|]/;
1517
- var TSC_SUMMARY = /^Found \d+ errors?/;
1518
- var ESLINT_PROBLEM = /^\s+\d+:\d+\s+(?:error|warning)\s/;
1519
- var ESLINT_SUMMARY = /^(?:\u2716 )?\d+ problems? \(/;
1520
- var PHPSTAN_TABLE = /^\s*-{3,} -{3,}/;
1521
- var PHPSTAN_NOISE = /^\s*\[OK\]/;
1522
- var PHP_FAILURES = /^(?:There w(?:as|ere) \d+ (?:failure|error|risky|warning)|\s+(?:FAIL|FAILED)\s+\S|In \S+\.php line \d+:$)/;
1523
- var VITEST_FAIL_LINE = /^ FAIL {2}\S/;
1524
- var PLAYWRIGHT_FAIL_LINE = /^ {2}1\) .+:\d+:\d+ \u203A .+ \u2500+$/;
1525
- var CS_FIXER_LINE = /^\s+\d+\) \S.*\.php(?: \(.+\))?$/;
1526
- var CS_FIXER_TOTAL = /^Found \d+ of \d+ files/;
1527
- var MAX_TESTS = 10;
1528
- var MAX_LINES = 100;
1529
- var TAIL = 30;
1530
- var bunTest = (lines) => {
1531
- const seen = new Set;
1532
- const blocks = [];
1533
- for (const [index, line] of lines.entries()) {
1534
- const name = line.replace(DURATION2, "");
1535
- if (!line.startsWith("(fail) ") || seen.has(name))
1536
- continue;
1537
- seen.add(name);
1538
- if (blocks.length < MAX_TESTS)
1539
- blocks.push(lines.slice(lines.findLastIndex((text, at) => at < index && BOUNDARY.test(text)) + 1, index + 1).join(`
1540
- `).trim());
1541
- }
1542
- if (blocks.length === 0)
1543
- return;
1544
- if (seen.size > MAX_TESTS)
1545
- blocks.push(`and ${seen.size - MAX_TESTS} more failed tests`);
1546
- return [...blocks.join(`
1547
-
1548
- `).split(`
1549
- `), "", ...lines.filter((line) => BUN_TEST_SUMMARY.test(line)).map((line) => line.trim())];
1550
- };
1551
- var bunCheck = (lines) => {
1552
- const text = lines.join(`
1553
- `);
1554
- const blocks = text.match(BUN_CHECK_BLOCK);
1555
- if (blocks === null)
1556
- return;
1557
- const errors = blocks.map((block) => {
1558
- const { file, line, column, code, message } = bunCheckFields(block);
1559
- return `${file}:${line}:${column} ${code}: ${message}`;
1560
- });
1561
- return [...errors, ...lines.filter((line) => BUN_CHECK_SUMMARY.test(line))];
1562
- };
1563
- function bunCheckFields(block) {
1564
- const attributes = Object.fromEntries([...block.slice(0, block.indexOf(`
1565
- `)).matchAll(BUN_CHECK_ATTRIBUTE)].map((match) => [match[1] ?? "", match[2] ?? ""]));
1566
- return {
1567
- file: attributes.file ?? "",
1568
- line: attributes.line ?? "",
1569
- column: attributes.column ?? "",
1570
- code: attributes.code ?? "",
1571
- message: block.replace(BUN_CHECK_SOURCE, "").split(`
1572
- `).slice(1, -1).join(`
1573
- `).trim()
1574
- };
1575
- }
1576
- var tsc = (lines) => {
1577
- const kept = [];
1578
- let inError = false;
1579
- for (const line of lines) {
1580
- if (TSC_ERROR.test(line)) {
1581
- inError = true;
1582
- kept.push(line);
1583
- } else if (TSC_SUMMARY.test(line)) {
1584
- inError = false;
1585
- kept.push(line);
1586
- } else if (inError && TSC_CONTINUATION.test(line) && !TSC_FRAME.test(line)) {
1587
- kept.push(line);
1588
- } else {
1589
- inError = false;
1590
- }
1591
- }
1592
- return kept.some((line) => TSC_ERROR.test(line)) ? kept : undefined;
1593
- };
1594
- var eslint = (lines) => {
1595
- const kept = [];
1596
- let file = "";
1597
- let shown = "";
1598
- for (const line of lines) {
1599
- if (ESLINT_PROBLEM.test(line)) {
1600
- if (file !== shown) {
1601
- kept.push(file);
1602
- shown = file;
1603
- }
1604
- kept.push(line);
1605
- } else if (ESLINT_SUMMARY.test(line)) {
1606
- kept.push(line);
1607
- } else if (line.trim() !== "") {
1608
- file = line;
1609
- }
1610
- }
1611
- return kept.some((line) => ESLINT_PROBLEM.test(line)) ? kept : undefined;
1612
- };
1613
- var phpstan = (lines) => {
1614
- const start = lines.findIndex((line) => PHPSTAN_TABLE.test(line));
1615
- return start === -1 ? undefined : lines.slice(start).filter((line) => !PHPSTAN_NOISE.test(line));
1616
- };
1617
- var php = (lines) => {
1618
- const start = lines.findIndex((line) => PHP_FAILURES.test(line));
1619
- return start === -1 ? undefined : lines.slice(start);
1620
- };
1621
- var vitest = (lines) => {
1622
- const start = lines.findIndex((line) => VITEST_FAIL_LINE.test(line));
1623
- return start === -1 ? undefined : lines.slice(start);
1624
- };
1625
- var playwright = (lines) => {
1626
- const start = lines.findIndex((line) => PLAYWRIGHT_FAIL_LINE.test(line));
1627
- return start === -1 ? undefined : lines.slice(start);
1628
- };
1629
- var phpCsFixer = (lines) => {
1630
- const files = lines.filter((line) => CS_FIXER_LINE.test(line) || CS_FIXER_TOTAL.test(line));
1631
- return files.some((line) => CS_FIXER_LINE.test(line)) ? files : undefined;
1632
- };
1633
- var PARSERS = [bunTest, bunCheck, tsc, eslint, vitest, playwright, phpCsFixer, phpstan, php];
1634
- function squeeze(lines) {
1635
- const out = [];
1636
- for (const line of lines.map((text) => text.trimEnd())) {
1637
- if (line !== "" || out.at(-1) !== "")
1638
- out.push(line);
1639
- }
1640
- while (out.at(-1) === "")
1641
- out.pop();
1642
- return out;
1643
- }
1644
- function cut(shown) {
1645
- return shown.length > MAX_LINES ? [...shown.slice(0, MAX_LINES), `... ${shown.length - MAX_LINES} more lines`].join(`
1646
- `) : shown.join(`
1647
- `);
1648
- }
1649
- function recognised(lines, parsers) {
1650
- return parsers.map((parser) => parser(lines)).find((result) => result !== undefined && result.some((line) => line.trim() !== ""));
1651
- }
1652
- function failureExcerpt(output) {
1653
- const lines = stripAnsi(output).split(`
1654
- `);
1655
- if (BASH_ECHO.test(lines[0] ?? ""))
1656
- lines.shift();
1657
- return cut(squeeze(recognised(lines, PARSERS) ?? lines.slice(-TAIL)));
1658
- }
1659
- var LOG_PATTERNS = { BASH_ECHO, DURATION: DURATION2, BOUNDARY, BUN_TEST_SUMMARY, BUN_CHECK_SUMMARY, TSC_CONTINUATION, TSC_FRAME, TSC_SUMMARY, ESLINT_PROBLEM, ESLINT_SUMMARY };
1660
-
1661
- // ../kit/src/index.ts
1662
- init_folders();
1663
- init_format();
1664
-
1665
- // ../kit/src/git.ts
1666
- init_args();
1667
- // ../kit/src/limit.ts
1668
- init_args();
1669
-
1670
- // ../kit/src/index.ts
1671
- init_mode();
1672
-
1673
- // ../kit/src/report.ts
1674
- init_style();
1675
- init_text2();
1676
- // ../kit/src/secrets.ts
1677
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1678
- var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1679
- // ../kit/src/sessions.ts
1680
- var {Glob } = globalThis.Bun;
1681
- var SESSION_FILES = new Glob("*.json");
1682
- var ACCOUNT_DIRS = new Glob("*/sessions");
1683
-
1684
- // ../kit/src/index.ts
1685
- init_style();
1686
- init_text2();
1687
- init_theme();
1688
- init_user_config();
1689
-
1690
- // ../kit/src/watch.ts
1691
- init_args();
1692
- init_input();
1693
- init_style();
1694
- // ../kit/src/workspace-root.ts
1695
- init_user_config();
1696
- // package.json
1697
- var version = "0.22.3";
1698
-
1699
- // src/check.ts
1700
- import { writeFile as writeFile3 } from "fs/promises";
1701
- import { basename as basename4, join as join14 } from "path";
1702
- import process23 from "process";
1703
-
1704
- // ../kit/src/shell.ts
1705
- var SEPARATORS = new Set([`
1706
- `, ";", "|"]);
1707
- var PLAIN_BREAKERS = new Set(["<", ">", "(", ")", "&", "|"]);
1708
- var GLOB_CHARS = new Set(["*", "?", "["]);
1709
- var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
1710
- var SAFE_WORD = /^[\w@%+=:,./-]+$/;
1711
- var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
1712
- var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
1713
- var FISH_COMBINERS = new Set(["and", "or", "not"]);
1714
- var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
1715
- var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
1716
- var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
1717
- var POWERSHELL = new Set(["pwsh", "powershell"]);
1718
- var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
1719
- var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
1720
- var PRINTERS = new Set(["echo", "printf"]);
1721
- var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
1722
- function wrapper(short = "", long = [], operands = 0, runsString = false) {
1723
- return { short, long, operands, runsString };
1724
- }
1725
- var RUNNER = { ...wrapper(), afterDashes: true };
1726
- var WRAPPERS = new Map([
1727
- ["command", wrapper()],
1728
- ["builtin", wrapper()],
1729
- ["nohup", wrapper()],
1730
- ["setsid", wrapper()],
1731
- ["busybox", wrapper()],
1732
- ["exec", wrapper("a")],
1733
- ["time", wrapper("fo", ["--format", "--output"])],
1734
- ["env", wrapper("uCS", ["--unset", "--chdir", "--split-string", "--argv0"])],
1735
- ["sudo", wrapper("ughpCTrtUDR", ["--user", "--group", "--host", "--prompt", "--close-from", "--command-timeout", "--role", "--type", "--other-user", "--chdir", "--chroot"])],
1736
- ["doas", wrapper("uC")],
1737
- ["timeout", wrapper("sk", ["--signal", "--kill-after"], 1)],
1738
- ["nice", wrapper("n", ["--adjustment"])],
1739
- ["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
1740
- ["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
1741
- ["chroot", wrapper("", ["--userspec", "--groups"], 1)],
1742
- ["watch", wrapper("n", ["--interval"], 0, true)],
1743
- ["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
1744
- ["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
1745
- ["unbuffer", wrapper()],
1746
- ["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
1747
- ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])],
1748
- ["strace", wrapper("abeEIoOpPsSuUX", ["--trace", "--output", "--attach", "--string-limit", "--user", "--env", "--columns", "--trace-path", "--signal", "--status", "--summary-sort-by", "--summary-columns", "--const-print-style", "--interruptible", "--detach-on"])],
1749
- ["ltrace", wrapper("aeFlnopsuxX", ["--output", "--user", "--library", "--config", "--align", "--indent"])],
1750
- ["taskset", wrapper("", [], 1)],
1751
- ["fakeroot", wrapper("lsib", ["--lib", "--faked"])],
1752
- ["sshpass", wrapper("pfdP")],
1753
- ["coproc", wrapper()],
1754
- ["proxychains", wrapper("f")],
1755
- ["proxychains4", wrapper("f")],
1756
- ["torsocks", wrapper("upaP", ["--user", "--pass", "--address", "--port"])],
1757
- ["chrt", wrapper("TPD", ["--sched-runtime", "--sched-period", "--sched-deadline"], 1)],
1758
- ["unshare", wrapper("SGRw", ["--setuid", "--setgid", "--root", "--wd", "--map-user", "--map-group", "--map-users", "--map-groups", "--propagation", "--setgroups"])],
1759
- ["nsenter", wrapper("tSG", ["--target", "--setuid", "--setgid"])],
1760
- ["out", RUNNER],
1761
- ["slot", RUNNER],
1762
- ["waitfor", RUNNER],
1763
- ["base", RUNNER]
1764
- ]);
1765
- function shellQuote(word) {
1766
- return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
1767
- }
1768
-
1769
- // src/compose.ts
1770
- import { existsSync as existsSync4 } from "fs";
1771
- import { homedir as homedir6 } from "os";
1772
- import { basename, dirname as dirname4, join as join8, relative, resolve as resolve4 } from "path";
1773
- import process20 from "process";
1774
- var COMPOSE_FILES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
1775
- var OVERRIDE_FILES = ["compose.override.yaml", "compose.override.yml", "docker-compose.override.yaml", "docker-compose.override.yml"];
1776
- var PS_TIMEOUT_MS = 20000;
1777
- var VARIABLE = /\$\{(\w+)(?::?-([^${}]*))?\}|\$(\w+)/g;
1778
- var ENV_LINE = /^\s*(?:export\s+)?(\w+)=(.*)$/;
1779
- var QUOTED = /^(['"])(.*)\1$/;
1780
- var TOOL_WORDS = {
1781
- bun: ["bun"],
1782
- bunx: ["bun"],
1783
- node: ["node", "bun"],
1784
- npm: ["node", "bun"],
1785
- npx: ["node", "bun"],
1786
- pnpm: ["node", "bun"],
1787
- yarn: ["node", "bun"],
1788
- composer: ["php"],
1789
- php: ["php"],
1790
- phpunit: ["php"],
1791
- phpstan: ["php"],
1792
- paratest: ["php"],
1793
- pest: ["php"],
1794
- symfony: ["php"]
1795
- };
1796
- function toolWords(program) {
1797
- const name = basename(program);
1798
- return TOOL_WORDS[name] ?? (program.includes("vendor/bin/") ? ["php"] : []);
1799
- }
1800
- async function readFiles(dir, names) {
1801
- for (const name of names) {
1802
- const handle = Bun.file(join8(dir, name));
1803
- if (await handle.exists())
1804
- return { name, text: await handle.text() };
1805
- }
1806
- return;
1807
- }
1808
- async function variables(composeDir) {
1809
- const env = {};
1810
- const text = (await readFiles(composeDir, [".env"]))?.text ?? "";
1811
- for (const line of text.split(`
1812
- `)) {
1813
- const match = ENV_LINE.exec(line);
1814
- if (match !== null && !line.trimStart().startsWith("#"))
1815
- env[match[1] ?? ""] = (match[2] ?? "").trim().replace(QUOTED, "$2");
1816
- }
1817
- for (const [key, value] of Object.entries(process20.env)) {
1818
- if (value !== undefined)
1819
- env[key] = value;
1820
- }
1821
- env.PWD = composeDir;
1822
- return env;
1823
- }
1824
- function interpolate(text, env) {
1825
- let current = text;
1826
- for (let round = 0;round < 4 && current.includes("$"); round++) {
1827
- current = current.replaceAll(VARIABLE, (_, braced, fallback, bare) => {
1828
- const value = env[braced ?? bare ?? ""];
1829
- return value !== undefined && value !== "" ? value : fallback ?? "";
1830
- });
1831
- }
1832
- return current;
1833
- }
1834
- function bindSource(source, composeDir, env) {
1835
- const path = interpolate(source, env);
1836
- if (path.startsWith("~"))
1837
- return join8(homedir6(), path.slice(1));
1838
- if (path.startsWith("/"))
1839
- return resolve4(path);
1840
- return path.startsWith(".") ? resolve4(composeDir, path) : undefined;
1841
- }
1842
- function mountsOf(volumes, composeDir, env) {
1843
- if (!Array.isArray(volumes))
1844
- return [];
1845
- const mounts = [];
1846
- for (const volume of volumes) {
1847
- let source;
1848
- let target;
1849
- if (typeof volume === "string") {
1850
- [source, target] = interpolate(volume, env).split(":");
1851
- } else if (typeof volume === "object" && volume !== null) {
1852
- const object = volume;
1853
- if (object.type === "bind" && typeof object.source === "string" && typeof object.target === "string")
1854
- ({ source, target } = object);
1855
- }
1856
- const resolved = source === undefined ? undefined : bindSource(source, composeDir, env);
1857
- if (resolved !== undefined && target?.startsWith("/") === true)
1858
- mounts.push({ source: resolved, target });
1859
- }
1860
- return mounts;
1861
- }
1862
- function buildText(build) {
1863
- if (typeof build === "string")
1864
- return build;
1865
- return typeof build === "object" && build !== null ? Object.values(build).filter((value) => typeof value === "string").join(" ") : "";
1866
- }
1867
- function parseServices(text, composeDir, env) {
1868
- const services = new Map;
1869
- const parsed = Bun.YAML.parse(text);
1870
- for (const [name, service] of Object.entries(parsed?.services ?? {})) {
1871
- if (service !== null && typeof service === "object")
1872
- services.set(name, { ...service, mounts: mountsOf(service.volumes, composeDir, env) });
1873
- }
1874
- return services;
1875
- }
1876
- async function composeFiles(composeDir, env) {
1877
- const listed = env.COMPOSE_FILE;
1878
- if (listed !== undefined && listed !== "") {
1879
- const files = [];
1880
- const separator = env.COMPOSE_PATH_SEPARATOR;
1881
- for (const name of listed.split(separator === undefined || separator === "" ? ":" : separator).filter((entry) => entry !== "")) {
1882
- const file = Bun.file(resolve4(composeDir, name));
1883
- if (!await file.exists())
1884
- fail(`COMPOSE_FILE names ${join8(composeDir, name)}, which does not exist`, 1, "fix COMPOSE_FILE, or run on the host with --host");
1885
- files.push({ name, text: await file.text() });
1886
- }
1887
- return files;
1888
- }
1889
- const base = await readFiles(composeDir, COMPOSE_FILES);
1890
- if (base === undefined)
1891
- return [];
1892
- const override = await readFiles(composeDir, OVERRIDE_FILES);
1893
- return override === undefined ? [base] : [base, override];
1894
- }
1895
- async function readServices(composeDir) {
1896
- const env = await variables(composeDir);
1897
- const files = await composeFiles(composeDir, env);
1898
- if (files.length === 0)
1899
- return;
1900
- const services = new Map;
1901
- for (const file of files) {
1902
- let parsed;
1903
- try {
1904
- parsed = parseServices(file.text, composeDir, env);
1905
- } catch (error) {
1906
- fail(`cannot read ${join8(composeDir, file.name)}: ${error instanceof Error ? error.message : String(error)}`, 1, "fix the file, or run on the host with --host");
1907
- }
1908
- for (const [name, extra] of parsed) {
1909
- const known = services.get(name);
1910
- services.set(name, known === undefined ? extra : { ...known, ...extra, mounts: [...known.mounts, ...extra.mounts], image: extra.image ?? known.image, build: extra.build ?? known.build });
1911
- }
1912
- }
1913
- return [...services].map(([name, service]) => ({ name, mounts: service.mounts, profile: `${name} ${typeof service.image === "string" ? service.image : ""} ${buildText(service.build)}`.toLowerCase() }));
1914
- }
1915
- function climb(dir) {
1916
- const folders = [dir];
1917
- let current = dir;
1918
- while (!existsSync4(join8(current, ".git")) && dirname4(current) !== current) {
1919
- current = dirname4(current);
1920
- folders.push(current);
1921
- }
1922
- return existsSync4(join8(current, ".git")) ? folders : [dir];
1923
- }
1924
- function containerPath(service, dir) {
1925
- const holding = service.mounts.filter((mount) => {
1926
- const inside = relative(mount.source, dir);
1927
- return !inside.startsWith("..") && !inside.startsWith("/");
1928
- });
1929
- const deepest = holding.toSorted((a, b) => b.source.length - a.source.length)[0];
1930
- if (deepest === undefined)
1931
- return;
1932
- const inside = relative(deepest.source, dir);
1933
- return inside === "" ? deepest.target : join8(deepest.target, inside);
1934
- }
1935
- var noticed = new Set;
1936
- async function place(dir, program, { service, host } = {}) {
1937
- if (host === true)
1938
- return;
1939
- let found;
1940
- for (const composeDir of climb(dir)) {
1941
- const services = await readServices(composeDir);
1942
- const mounting = (services ?? []).filter((candidate) => containerPath(candidate, dir) !== undefined);
1943
- if (services !== undefined && (mounting.length > 0 || services.some((candidate) => candidate.name === service))) {
1944
- found = { composeDir, services, mounting };
1945
- break;
1946
- }
1947
- }
1948
- if (found === undefined) {
1949
- if (service !== undefined)
1950
- fail(`--in ${service}: no compose project mounts ${dir}`);
1951
- return;
1952
- }
1953
- if (Bun.which("docker", { PATH: process20.env.PATH ?? "" }) === null) {
1954
- if (service !== undefined)
1955
- fail(`--in ${service}: docker not found`);
1956
- if (!noticed.has(found.composeDir)) {
1957
- noticed.add(found.composeDir);
1958
- warn(`host, docker not found: the compose project in ${found.composeDir} is not reached`);
1959
- }
1960
- return;
1961
- }
1962
- const chosen = choose(found.mounting, found.services, dir, program, service);
1963
- return { service: chosen.name, composeDir: found.composeDir, workdir: containerPath(chosen, dir) ?? dir };
1964
- }
1965
- function choose(mounting, services, dir, program, service) {
1966
- if (service !== undefined) {
1967
- const named = mounting.find((candidate) => candidate.name === service);
1968
- if (named === undefined)
1969
- fail(`--in ${service}: ${services.some((candidate) => candidate.name === service) ? `the service does not mount ${dir}` : `no such service, found ${services.map((candidate) => candidate.name).join(", ")}`}`);
1970
- return named;
1971
- }
1972
- const [only] = mounting;
1973
- if (mounting.length === 1 && only !== undefined)
1974
- return only;
1975
- const words = toolWords(program);
1976
- const fitting = mounting.filter((candidate) => words.some((word) => candidate.profile.includes(word)));
1977
- const [fit] = fitting;
1978
- if (fitting.length !== 1 || fit === undefined)
1979
- fail(`${mounting.map((candidate) => candidate.name).join(", ")} all mount ${dir} and none stands out for ${basename(program)}: pick one with --in <service>, or run on the host with --host`);
1980
- return fit;
1981
- }
1982
- function execArgv(placement, argv, env) {
1983
- const variables = Object.entries({ NO_COLOR: "1", FORCE_COLOR: "0", ...env }).flatMap(([name, value]) => ["-e", `${name}=${value}`]);
1984
- return ["docker", "compose", "exec", "-T", "-w", placement.workdir, ...variables, placement.service, ...argv];
1985
- }
1986
- function shellIn(placement, command, env = {}) {
1987
- return `cd ${shellQuote(placement.composeDir)} && ${execArgv(placement, ["sh", "-c", command], env).map((word) => shellQuote(word)).join(" ")}`;
1988
- }
1989
- function argvIn(placement, argv) {
1990
- return execArgv(placement, argv, {});
1991
- }
1992
-
1993
- class Stack {
1994
- answers = new Map;
1995
- async ask(composeDir) {
1996
- let answer = this.answers.get(composeDir);
1997
- if (answer === undefined) {
1998
- answer = Stack.running(composeDir);
1999
- this.answers.set(composeDir, answer);
2000
- }
2001
- return answer;
2002
- }
2003
- static async running(composeDir) {
2004
- try {
2005
- const ran = await runCommand(["docker", "compose", "ps", "--services", "--status", "running"], { cwd: composeDir, env: process20.env, timeoutMs: PS_TIMEOUT_MS });
2006
- if (ran.code !== 0)
2007
- return `docker compose ps failed in ${composeDir}: ${ran.text.trim().split(`
2008
- `).at(-1) ?? `exit ${ran.code}`}`;
2009
- return ran.text.split(`
2010
- `).map((line) => line.trim()).filter((line) => line !== "");
2011
- } catch (error) {
2012
- return `cannot run docker compose in ${composeDir}: ${error instanceof Error ? error.message : String(error)}`;
2013
- }
2014
- }
2015
- async problem(placement) {
2016
- const answer = await this.ask(placement.composeDir);
2017
- if (typeof answer === "string")
2018
- return answer;
2019
- return answer.includes(placement.service) ? undefined : `the ${placement.service} service is not running (compose project in ${placement.composeDir}): start it yourself, or run on the host with --host`;
2020
- }
2021
- }
2022
- function programOf(command) {
2023
- const end = command.indexOf(" ");
2024
- return end === -1 ? command : command.slice(0, end);
2025
- }
2026
- var placeOptions = {
2027
- in: { type: "string", description: "run in this compose service instead of the one found mounting the folder" },
2028
- host: { type: "boolean", description: "run on the host even when a compose service mounts the folder" }
2029
- };
2030
- function placeSettings(values) {
2031
- if (values.in !== undefined && values.host === true)
2032
- fail("--in and --host exclude each other");
2033
- return { service: values.in, host: values.host };
2034
- }
2035
-
2036
- // src/fix.ts
2037
- import { existsSync as existsSync5, statSync as statSync2 } from "fs";
2038
- import { rename, writeFile as writeFile2 } from "fs/promises";
2039
- import { join as join12 } from "path";
2040
- import process22 from "process";
2041
-
2042
- // src/changes.ts
2043
- import { stat as stat2 } from "fs/promises";
2044
- import { join as join9 } from "path";
2045
- var {$ } = globalThis.Bun;
2046
- async function dirtyFiles(dir) {
2047
- const listed = await $`git ls-files -z --modified --others --exclude-standard`.cwd(dir).quiet().nothrow();
2048
- if (listed.exitCode !== 0)
2049
- return;
2050
- const files = new Map;
2051
- for (const path of listed.stdout.toString().split("\x00").filter(Boolean)) {
2052
- try {
2053
- const { size, mtimeMs } = await stat2(join9(dir, path));
2054
- files.set(path, `${size}:${mtimeMs}`);
2055
- } catch {
2056
- files.set(path, "");
2057
- }
2058
- }
2059
- return files;
2060
- }
2061
- function changedFiles(before, after) {
2062
- return [...after].filter(([path, hash]) => before.get(path) !== hash).map(([path]) => path);
2063
- }
2064
-
2065
- // src/makefile.ts
2066
- var TARGET = /^([\w-]+(?:[ \t]+[\w-]+)*)[ \t]*::?(?!:?=)(.*)$/gm;
2067
- var PHONY_LINE = /^\.PHONY:((?:.*\\\n)*.*)$/gm;
2068
- var DEFINE_BLOCK = /^define\b.*\n(?:.*\n)*?endef\b.*$/gm;
2069
- var BLANKS = /\s+/;
2070
- var CONTINUATION = /\\\n/g;
2071
- var EXTRA_BLANK_LINES = /\n\s*\n\s*\n/g;
2072
- var LEADING_BLANK_LINES = /^\s*\n/;
2073
- var TRAILING_WHITESPACE = /\s+$/;
2074
- var FILE_LIKE = /[./]/;
2075
- var PLACEHOLDER = "\x00phony\x00";
2076
- function declarePhony(content, exists = () => false) {
2077
- const declared = Array.from(content.matchAll(PHONY_LINE), (match) => match[1].replace(CONTINUATION, " ").split(BLANKS)).flat().filter((name) => name !== "");
2078
- const found = Array.from(content.replace(DEFINE_BLOCK, "").matchAll(TARGET), (match) => ({ names: match[1].split(BLANKS), deps: match[2] })).filter(({ deps }) => !FILE_LIKE.test(deps)).flatMap(({ names }) => names).filter((name) => !exists(name));
2079
- const targets = [...new Set([...declared, ...found])].sort((a, b) => a.localeCompare(b));
2080
- let isFirst = true;
2081
- const body = content.replace(PHONY_LINE, () => {
2082
- const kept = isFirst ? PLACEHOLDER : "";
2083
- isFirst = false;
2084
- return kept;
2085
- }).replace(EXTRA_BLANK_LINES, `
2086
-
2087
- `).replace(LEADING_BLANK_LINES, "");
2088
- const line = targets.length === 0 ? "" : `.PHONY: ${targets.join(" ")}`;
2089
- const fixed = body.includes(PLACEHOLDER) || line === "" ? body.replace(PLACEHOLDER, () => line) : `${line}
2090
-
2091
- ${body}`;
2092
- return { content: fixed.replace(LEADING_BLANK_LINES, "").replace(TRAILING_WHITESPACE, `
2093
- `), targets };
2094
- }
2095
-
2096
- // src/steps.ts
2097
- import { readdir as readdir2 } from "fs/promises";
2098
- import { join as join10 } from "path";
2099
- var STEP_NAMES = ["check", "typecheck", "lint", "fmt", "test"];
2100
- var STEP_SOURCES = { fmt: ["fmt:check", "format:check", "fmt-check", "format-check"] };
2101
- var TARGET2 = /^@?([\w-]+)(?:[ \t][^:=\n]*)?:(?!=)/gm;
2102
- var JUSTFILES = ["justfile", "Justfile", ".justfile"];
2103
- var TASK_RUNNERS = new Set(["Justfile", "Makefile"]);
2104
- var MAKEFILES = ["GNUmakefile", "makefile", "Makefile"];
2105
- var CS_FIXER_CONFIGS = [".php-cs-fixer.php", ".php-cs-fixer.dist.php"];
2106
- var JUST_TIMEOUT_MS = 1e4;
2107
- var PHPSTAN_CONFIGS = ["phpstan.neon", "phpstan.neon.dist", "phpstan.dist.neon"];
2108
- var PHPUNIT_CONFIGS = ["phpunit.xml", "phpunit.xml.dist", "phpunit.dist.xml"];
2109
- async function readFirst(dir, files) {
2110
- for (const file of files) {
2111
- const handle = Bun.file(join10(dir, file));
2112
- if (await handle.exists())
2113
- return { file, text: await handle.text() };
2114
- }
2115
- return;
2116
- }
2117
- async function read(dir, ...files) {
2118
- for (const file of files) {
2119
- const handle = Bun.file(join10(dir, file));
2120
- if (await handle.exists())
2121
- return handle.text();
2122
- }
2123
- return;
2124
- }
2125
- function scripts(file, text) {
2126
- try {
2127
- const parsed = JSON.parse(text);
2128
- return parsed.scripts ?? {};
2129
- } catch {
2130
- fail(`${file} is not valid JSON`);
2131
- }
2132
- }
2133
- function targets(text) {
2134
- return [...text.matchAll(TARGET2)].map((match) => match[1] ?? "");
2135
- }
2136
- async function recipes(dir, file, text) {
2137
- if (Bun.which("just") === null)
2138
- return targets(text);
2139
- try {
2140
- const ran = await runCommand(["just", "--justfile", file, "--dump", "--dump-format", "json"], { cwd: dir, timeoutMs: JUST_TIMEOUT_MS });
2141
- const dump = JSON.parse(ran.text);
2142
- if (ran.code !== 0)
2143
- return targets(text);
2144
- return Object.entries(dump.recipes ?? {}).filter(([, recipe]) => recipe.private !== true && (recipe.parameters ?? []).every((parameter) => parameter.default !== null || parameter.kind === "star")).map(([name]) => name);
2145
- } catch {
2146
- return targets(text);
2147
- }
2148
- }
2149
- function callsSelf(value, bin) {
2150
- return typeof value === "string" && (value === bin || value.startsWith(`${bin} `) || value.startsWith(`${bin} `));
2151
- }
2152
- async function candidates(dir, bin) {
2153
- const steps = [];
2154
- const packageJson = await read(dir, "package.json");
2155
- const composerJson = await read(dir, "composer.json");
2156
- const justfile = await readFirst(dir, JUSTFILES);
2157
- const makefile = await read(dir, ...MAKEFILES);
2158
- if (packageJson !== undefined) {
2159
- for (const [name, value] of Object.entries(scripts("package.json", packageJson))) {
2160
- if (!callsSelf(value, bin))
2161
- steps.push({ name, command: `bun run ${name}`, source: "package.json" });
2162
- }
2163
- }
2164
- if (composerJson !== undefined) {
2165
- for (const name of Object.keys(scripts("composer.json", composerJson)))
2166
- steps.push({ name, command: `composer run ${name}`, source: "composer.json" });
2167
- }
2168
- if (justfile !== undefined) {
2169
- for (const name of await recipes(dir, justfile.file, justfile.text))
2170
- steps.push({ name, command: `just ${name}`, source: "Justfile" });
2171
- }
2172
- for (const name of targets(makefile ?? ""))
2173
- steps.push({ name, command: `make ${name}`, source: "Makefile" });
2174
- steps.push(...await phpSteps(dir));
2175
- return steps;
2176
- }
2177
- async function firstFile(dir, names) {
2178
- for (const name of names) {
2179
- if (await Bun.file(join10(dir, name)).exists())
2180
- return name;
2181
- }
2182
- return;
2183
- }
2184
- async function phpSteps(dir) {
2185
- const steps = [];
2186
- const phpstan = await firstFile(dir, PHPSTAN_CONFIGS);
2187
- const csFixer = await firstFile(dir, CS_FIXER_CONFIGS);
2188
- const phpunit = await firstFile(dir, PHPUNIT_CONFIGS);
2189
- if (phpstan !== undefined)
2190
- steps.push({ name: "typecheck", command: "vendor/bin/phpstan analyse --no-progress --memory-limit=1G", source: phpstan });
2191
- if (csFixer !== undefined)
2192
- steps.push({ name: "lint", command: "vendor/bin/php-cs-fixer fix --dry-run -v", source: csFixer });
2193
- if (phpunit !== undefined)
2194
- steps.push({ name: "test", command: "vendor/bin/phpunit", source: phpunit });
2195
- return steps;
2196
- }
2197
- async function discoverProjects(dir) {
2198
- const own = await discover(dir);
2199
- if (own.length > 0)
2200
- return [{ dir, steps: own }];
2201
- const projects = [];
2202
- const entries = await readdir2(dir, { withFileTypes: true });
2203
- const ignored = ignoredFolders(["var", "tmp"]);
2204
- for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
2205
- if (!entry.isDirectory() || entry.name.startsWith(".") || ignored.has(entry.name))
2206
- continue;
2207
- const steps = await discover(join10(dir, entry.name));
2208
- if (steps.length > 0)
2209
- projects.push({ name: entry.name, dir: join10(dir, entry.name), steps });
2210
- }
2211
- return projects;
2212
- }
2213
- async function discover(dir) {
2214
- const found = await candidates(dir, "check");
2215
- const runnerCheck = found.find((candidate) => candidate.name === "check" && TASK_RUNNERS.has(candidate.source));
2216
- return STEP_NAMES.flatMap((name) => {
2217
- const step = name === "check" && runnerCheck !== undefined ? runnerCheck : (STEP_SOURCES[name] ?? [name]).map((each) => found.find((candidate) => candidate.name === each)).find((each) => each !== undefined);
2218
- return step === undefined ? [] : [{ ...step, name }];
2219
- });
2220
- }
2221
-
2222
- // src/options.ts
2223
- var options = {
2224
- list: { type: "boolean", short: "l", description: "print the steps (or, with --fix, the fixers) found, the commands that run them and where (host or service), without running them" },
2225
- only: { type: "string", short: "o", description: `comma separated steps to run, among ${STEP_NAMES.join(", ")}; with --fix the fixers to run, by the names --list prints`, candidates: () => [...STEP_NAMES] },
2226
- timeout: { type: "string", short: "t", description: "longest a step or fixer may run before it is ended (30s, 5m, 1h), none by default" },
2227
- ...placeOptions,
2228
- json: jsonOption("[{name, command, in?, ok, ms, log, failed?}], with --list [{name, command, source, in?}], with --fix {fixers, changed}"),
2229
- fix: { type: "boolean", short: "f", description: "run the folder's fixers and formatters instead of the steps" },
2230
- quiet: { type: "boolean", short: "q", description: "print nothing for a passing step, and nothing at all when every step passes" },
2231
- failed: { type: "boolean", description: "run only the steps that failed in the last run of this folder, read from the run folder" },
2232
- changed: { type: "boolean", short: "c", description: "narrow lint and test to the files changed against HEAD (a bare linter script, a bare bun test script), every other step runs in full and says so" },
2233
- slot: { type: "boolean", description: "run each step through slot, queued behind the machine-wide slots of the other sessions, as it does by default when the slot bin is installed; fails without the bin" },
2234
- "no-slot": { type: "boolean", description: "run the steps at once, without queueing behind the other sessions' slots" },
2235
- parallel: { type: "boolean", description: "run the steps at the same time, printing each one's output in step order" }
2236
- };
2237
- var COMMA = /\s*,\s*/;
2238
- function pick(steps, only, noun = "step") {
2239
- if (only === undefined)
2240
- return steps;
2241
- const names = only.split(COMMA).filter((name) => name !== "");
2242
- if (names.length === 0)
2243
- fail(`--only names no ${noun}, found ${steps.map((step) => step.name).join(", ")}`);
2244
- const unknown = names.filter((name) => !steps.some((step) => step.name === name));
2245
- if (unknown.length > 0)
2246
- fail(`no ${unknown.join(", ")} ${noun} here, found ${[...new Set(steps.map((step) => step.name))].join(", ")}`);
2247
- return steps.filter((step) => names.includes(step.name));
2248
- }
2249
-
2250
- // src/run.ts
2251
- import { mkdir as mkdir2, readdir as readdir3, stat as stat3, writeFile } from "fs/promises";
2252
- import { basename as basename2, join as join11 } from "path";
2253
- import process21 from "process";
2254
- var LOG_MAX_AGE_MS = 3 * 24 * 60 * 60 * 1000;
2255
- var RESULTS_FILE = "results.json";
2256
- var runPrefix = (cwd) => `${basename2(cwd)}-${Bun.hash(cwd).toString(36)}-`;
2257
- async function logDirectory(cwd) {
2258
- const root = await privateLogDirectory("check");
2259
- await sweepLogs(root, LOG_MAX_AGE_MS);
2260
- const path = join11(root, `${runPrefix(cwd)}${Date.now().toString(36)}-${process21.pid}`);
2261
- await mkdir2(path, { mode: 448 });
2262
- return path;
2263
- }
2264
- async function lastResults(cwd) {
2265
- const root = await privateLogDirectory("check");
2266
- const prefix = runPrefix(cwd);
2267
- let latest;
2268
- for (const name of await readdir3(root)) {
2269
- if (!name.startsWith(prefix))
2270
- continue;
2271
- const file = join11(root, name, RESULTS_FILE);
2272
- try {
2273
- const { mtimeMs } = await stat3(file);
2274
- if (latest === undefined || mtimeMs > latest.time)
2275
- latest = { time: mtimeMs, file };
2276
- } catch {}
2277
- }
2278
- if (latest === undefined)
2279
- return;
2280
- return JSON.parse(await Bun.file(latest.file).text());
2281
- }
2282
- async function lastFailed(cwd) {
2283
- return (await lastResults(cwd))?.filter((result) => !result.ok).map((result) => result.name);
2284
- }
2285
- async function saveLog(output) {
2286
- const root = await privateLogDirectory("errs");
2287
- await sweepLogs(root);
2288
- const path = join11(root, `${new Date().toISOString().replaceAll(/[:.]/g, "-")}-${process21.pid}-${crypto.randomUUID().slice(0, 8)}.log`);
2289
- await writeFile(path, output, { mode: 384, flag: "wx" });
2290
- return path;
2291
- }
2292
- async function runStep(command, cwd, logFile, { env = {}, timeoutMs, held } = {}) {
2293
- const started = Date.now();
2294
- const { code, text, timedOut } = await runCommand(["sh", "-c", `${command} 2>&1`], {
2295
- cwd,
2296
- env: { ...process21.env, NO_COLOR: "1", FORCE_COLOR: "0", ...env },
2297
- ...timeoutMs === undefined ? {} : { timeoutMs },
2298
- ...held === undefined ? {} : { onStart: (child) => held.forward(child) }
2299
- });
2300
- const output = stripAnsi(text);
2301
- await writeFile(logFile, output, { mode: 384, flag: "wx" });
2302
- return { ok: code === 0, ms: Date.now() - started, output, ...timedOut ? { timedOut } : {} };
2303
- }
2304
- async function refusedStep(reason, logFile) {
2305
- await writeFile(logFile, reason, { mode: 384, flag: "wx" });
2306
- return { ok: false, ms: 0, output: reason };
2307
- }
2308
- function outcomeJson(name, command, logFile, outcome, service) {
2309
- return { name, command, ...service === undefined ? {} : { in: service }, ok: outcome.ok, ms: outcome.ms, log: logFile, ...outcome.timedOut === true ? { timedOut: true } : {}, ...outcome.ok ? {} : { failed: failureExcerpt(outcome.output) } };
2310
- }
2311
- function printOutcome(name, width, command, logFile, outcome) {
2312
- const colors = paint(process21.stdout);
2313
- const path = role("path", process21.stdout);
2314
- const took = colors.dim(formatDuration(outcome.ms));
2315
- if (outcome.ok) {
2316
- console.log(`${colors.bold(colors.green("ok "))} ${name.padEnd(width)} ${took} ${path(logFile)}`);
2317
- return;
2318
- }
2319
- const label = outcome.timedOut === true ? colors.bold(colors.yellow("TIME ")) : colors.bold(colors.red("FAIL "));
2320
- console.log(`${label} ${name.padEnd(width)} ${took} ${colors.dim(command)} ${path(logFile)}`);
2321
- if (outcome.timedOut === true)
2322
- console.log(colors.yellow(` timed out after ${formatDuration(outcome.ms)}, the step and what it started were ended`));
2323
- console.log(failureExcerpt(outcome.output).split(`
2324
- `).map((line) => ` ${line}`.trimEnd()).join(`
2325
- `));
2326
- }
2327
-
2328
- // src/fix.ts
2329
- var RUNNING = "KAYNOOO_CLI_FIX";
2330
- var JUSTFILES2 = ["justfile", "Justfile", ".justfile"];
2331
- var RUFF_CONFIGS = ["ruff.toml", ".ruff.toml"];
2332
- var RUFF_SECTION = /^\[tool\.ruff/m;
2333
- var MAX_CHANGED = 30;
2334
- async function replaceFile(path, content) {
2335
- const temporary = `${path}.${process22.pid}.tmp`;
2336
- await writeFile2(temporary, content, { mode: statSync2(path).mode & 511 });
2337
- await rename(temporary, path);
2338
- }
2339
- async function projectFixers(dir) {
2340
- const found = await candidates(dir, "check");
2341
- const named = (name) => found.find((step) => step.name === name);
2342
- const all = named("fix");
2343
- if (all !== undefined)
2344
- return [all];
2345
- return [named("lint:fix") ?? named("lint-fix"), named("fmt") ?? named("format")].filter((step) => step !== undefined);
2346
- }
2347
- async function toolFixers(dir) {
2348
- const fixers = [];
2349
- const makefile = await firstFile(dir, MAKEFILES);
2350
- const justfile = await firstFile(dir, JUSTFILES2);
2351
- const ruff = await firstFile(dir, RUFF_CONFIGS) !== undefined || RUFF_SECTION.test(await read(dir, "pyproject.toml") ?? "");
2352
- if (makefile !== undefined) {
2353
- fixers.push({ name: "makefile", command: "declare every target .PHONY", source: makefile, write: async (cwd) => {
2354
- const path = join12(cwd, makefile);
2355
- const current = await Bun.file(path).text();
2356
- const { content, targets } = declarePhony(current, (name) => existsSync5(join12(cwd, name)));
2357
- if (content !== current)
2358
- await replaceFile(path, content);
2359
- return `.PHONY: ${targets.join(" ")}`;
2360
- } });
2361
- }
2362
- if (justfile !== undefined)
2363
- fixers.push({ name: "justfile", command: `just --justfile ${justfile} --fmt`, source: justfile, requires: "just" });
2364
- if (await Bun.file(join12(dir, "go.mod")).exists())
2365
- fixers.push({ name: "go", command: "go fmt ./... && go mod tidy", source: "go.mod", requires: "go" });
2366
- if (await Bun.file(join12(dir, "Cargo.toml")).exists())
2367
- fixers.push({ name: "rust", command: "cargo fmt", source: "Cargo.toml", requires: "cargo" });
2368
- if (ruff)
2369
- fixers.push({ name: "python", command: "ruff check --fix . && ruff format .", source: "ruff", requires: "ruff" });
2370
- return fixers;
2371
- }
2372
- async function fixers(dir) {
2373
- const project = await projectFixers(dir);
2374
- const csFixer = await firstFile(dir, CS_FIXER_CONFIGS);
2375
- const php = csFixer === undefined || project.some((fixer) => fixer.source === "composer.json") ? [] : [{ name: "php-cs-fixer", command: "vendor/bin/php-cs-fixer fix", source: csFixer }];
2376
- return [...project, ...php, ...await toolFixers(dir)];
2377
- }
2378
- function runsInService(fixer) {
2379
- return fixer.write === undefined && fixer.requires === undefined;
2380
- }
2381
- async function runFixer(fixer, placement, cwd, logFile, settings) {
2382
- if (fixer.write === undefined && placement !== undefined)
2383
- return runStep(shellIn(placement, fixer.command, { [RUNNING]: "1" }), cwd, logFile, { ...settings, env: { [RUNNING]: "1" } });
2384
- if (fixer.write === undefined)
2385
- return runStep(fixer.command, cwd, logFile, { ...settings, env: { [RUNNING]: "1" } });
2386
- const started = Date.now();
2387
- let outcome;
2388
- try {
2389
- outcome = { ok: true, ms: 0, output: await fixer.write(cwd) };
2390
- } catch (error) {
2391
- outcome = { ok: false, ms: 0, output: error instanceof Error ? error.message : String(error) };
2392
- }
2393
- await writeFile2(logFile, outcome.output, { mode: 384, flag: "wx" });
2394
- return { ...outcome, ms: Date.now() - started };
2395
- }
2396
- function printChanged(changed) {
2397
- if (changed.length === 0) {
2398
- console.log("nothing changed");
2399
- return;
2400
- }
2401
- console.log(`changed ${changed.length} file${changed.length === 1 ? "" : "s"}:`);
2402
- for (const path of changed.slice(0, MAX_CHANGED))
2403
- console.log(` ${path}`);
2404
- if (changed.length > MAX_CHANGED)
2405
- console.log(` and ${changed.length - MAX_CHANGED} more`);
2406
- }
2407
- async function runFixers(values, cwd) {
2408
- const parsed = { values };
2409
- const settings = placeSettings(values);
2410
- if (process22.env[RUNNING] !== undefined)
2411
- fail("a fixer called check --fix again, which would recurse: give its script another command");
2412
- const found = await fixers(cwd);
2413
- if (found.length === 0)
2414
- fail("nothing to fix here: no fix, lint:fix, fmt or format script, php-cs-fixer config, Makefile, Justfile, go.mod, Cargo.toml nor ruff config");
2415
- const picked = pick(found, parsed.values.only, "fixer");
2416
- const placements = new Map;
2417
- for (const fixer of picked)
2418
- placements.set(fixer, runsInService(fixer) ? await place(cwd, programOf(fixer.command), settings) : undefined);
2419
- const json = parsed.values.json === true;
2420
- const missing = (fixer) => fixer.requires !== undefined && Bun.which(fixer.requires) === null;
2421
- if (parsed.values.list === true) {
2422
- if (json)
2423
- printJson(picked.map((fixer) => ({ name: fixer.name, command: fixer.command, source: fixer.source, ...placements.get(fixer) === undefined ? {} : { in: placements.get(fixer)?.service }, ...missing(fixer) ? { needs: fixer.requires } : {} })));
2424
- else
2425
- console.log(table(picked.map((fixer) => [fixer.name, fixer.command, missing(fixer) ? `${fixer.source}, needs ${fixer.requires}` : fixer.source, placements.get(fixer)?.service ?? "host"])));
2426
- return 0;
2427
- }
2428
- const timeoutMs = parsed.values.timeout === undefined ? undefined : duration(parsed.values.timeout, "timeout", 0);
2429
- const directory = await logDirectory(cwd);
2430
- const held = holdSignals();
2431
- const runSettings = { ...timeoutMs === undefined ? {} : { timeoutMs }, held };
2432
- const stack = new Stack;
2433
- const width = Math.max(...picked.map((fixer) => fixer.name.length));
2434
- const before = await dirtyFiles(cwd);
2435
- const ran = [];
2436
- let failed = 0;
2437
- let timedOut = false;
2438
- try {
2439
- for (const fixer of picked) {
2440
- if (held.signal !== undefined)
2441
- break;
2442
- if (missing(fixer)) {
2443
- if (!json)
2444
- console.log(`${paint(process22.stdout).yellow("skip ")} ${fixer.name.padEnd(width)} ${fixer.requires} is not installed`);
2445
- ran.push({ name: fixer.name, command: fixer.command, skipped: `${fixer.requires} is not installed` });
2446
- continue;
2447
- }
2448
- const logFile = join12(directory, `fix-${fixer.name.replaceAll(":", "-")}.log`);
2449
- const placement = placements.get(fixer);
2450
- const down = placement === undefined ? undefined : await stack.problem(placement);
2451
- const outcome = down === undefined ? await runFixer(fixer, placement, cwd, logFile, runSettings) : await refusedStep(down, logFile);
2452
- if (!json)
2453
- printOutcome(fixer.name, width, placement === undefined ? fixer.command : `${fixer.command} (in ${placement.service})`, logFile, outcome);
2454
- ran.push(outcomeJson(fixer.name, fixer.command, logFile, outcome, placement?.service));
2455
- if (outcome.timedOut === true)
2456
- timedOut = true;
2457
- if (!outcome.ok)
2458
- failed++;
2459
- }
2460
- } finally {
2461
- held.release();
2462
- }
2463
- const after = before && await dirtyFiles(cwd);
2464
- const changed = before !== undefined && after !== undefined ? changedFiles(before, after) : null;
2465
- if (json)
2466
- printJson({ fixers: ran, changed });
2467
- else if (changed !== null)
2468
- printChanged(changed);
2469
- if (held.signal !== undefined)
2470
- return exitCodeOf(null, held.signal);
2471
- if (timedOut)
2472
- return 2;
2473
- return failed === 0 ? 0 : 1;
2474
- }
2475
-
2476
- // src/narrow.ts
2477
- import { existsSync as existsSync6 } from "fs";
2478
- import { basename as basename3, dirname as dirname5, extname, join as join13 } from "path";
2479
- var {$: $2 } = globalThis.Bun;
2480
- var LINTERS = /^(?:keslint|eslint|oxlint)\b/;
2481
- var LINTABLE = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".vue", ".svelte"]);
2482
- var TEST_RUNNER = /^(?:bun test|\$npm_execpath test)\b/;
2483
- var TEST_FILE = /\.(?:test|spec)\.[jt]sx?$/;
2484
- var WHITESPACE = /\s+/;
2485
- async function changedPaths(dir) {
2486
- const tracked = await $2`git diff --name-only --relative -z HEAD`.cwd(dir).quiet().nothrow();
2487
- const untracked = await $2`git ls-files -z --others --exclude-standard`.cwd(dir).quiet().nothrow();
2488
- if (tracked.exitCode !== 0 || untracked.exitCode !== 0)
2489
- return;
2490
- return [...new Set([...tracked.stdout.toString().split("\x00"), ...untracked.stdout.toString().split("\x00")])].filter((path) => path !== "" && existsSync6(join13(dir, path)));
2491
- }
2492
- function siblingTests(path, exists) {
2493
- const extension = extname(path);
2494
- const name = basename3(path, extension);
2495
- const dir = dirname5(path);
2496
- const folders = [dir, join13(dir, "tests"), join13(dir, "..", "tests"), join13(dir, "__tests__")];
2497
- const found = new Set;
2498
- for (const folder of folders) {
2499
- for (const kind of ["test", "spec"]) {
2500
- for (const candidate of [`${name}.${kind}${extension}`, `${name}.${kind}.ts`].map((file) => join13(folder, file))) {
2501
- if (exists(candidate))
2502
- found.add(candidate);
2503
- }
2504
- }
2505
- }
2506
- return [...found];
2507
- }
2508
- function isBare(script, tool) {
2509
- return tool.test(script.trim()) && script.trim().replace(tool, "").split(WHITESPACE).every((word) => word.startsWith("-") || word === "");
2510
- }
2511
- async function narrow2(step, dir, changed) {
2512
- const script = step.source === "package.json" ? (await scriptText(dir, step.name))?.trim() : undefined;
2513
- const full = (why) => ({ command: step.command, note: `in full, ${why}` });
2514
- if (script !== undefined && step.name === "lint" && isBare(script, LINTERS)) {
2515
- const files = changed.filter((path) => LINTABLE.has(extname(path)));
2516
- return files.length === 0 ? { command: "true", note: "nothing changed to lint" } : { command: `${step.command} -- ${files.map(quote).join(" ")}`, note: `${files.length} changed file${files.length === 1 ? "" : "s"}` };
2517
- }
2518
- if (script !== undefined && step.name === "test" && isBare(script, TEST_RUNNER)) {
2519
- const tests = new Set;
2520
- for (const path of changed) {
2521
- if (TEST_FILE.test(path)) {
2522
- tests.add(path);
2523
- } else {
2524
- for (const test of siblingTests(path, (candidate) => existsSync6(join13(dir, candidate)))) {
2525
- tests.add(test);
2526
- }
2527
- }
2528
- }
2529
- if (tests.size === 0)
2530
- return full("no test sits next to the changed files");
2531
- return { command: `${step.command} -- ${[...tests].map((test) => quote(`./${test}`)).join(" ")}`, note: `${tests.size} test file${tests.size === 1 ? "" : "s"}` };
2532
- }
2533
- return full(`${step.name} cannot be narrowed`);
2534
- }
2535
- function quote(path) {
2536
- return `'${path.replaceAll("'", "'\\''")}'`;
2537
- }
2538
- async function scriptText(dir, name) {
2539
- const text = await read(dir, "package.json");
2540
- if (text === undefined)
2541
- return;
2542
- try {
2543
- const value = JSON.parse(text).scripts?.[name];
2544
- return typeof value === "string" ? value : undefined;
2545
- } catch {
2546
- return;
2547
- }
2548
- }
2549
-
2550
- // src/check.ts
2551
- var usage2 = `check [--only <steps>] [--changed] [--failed] [--quiet] [--timeout <duration>] [--slot | --no-slot] [--parallel] [--in <service> | --host] [--list]
7
+ ${body}`).replace(LEADING_BLANK_LINES,"").replace(TRAILING_WHITESPACE,`
8
+ `),targets}}var options={list:{type:"boolean",short:"l",description:"print the steps (or, with --fix, the fixers) found, the commands that run them and where (host or service), without running them"},only:{type:"string",short:"o",description:`comma separated steps to run, among ${STEP_NAMES.join(", ")}; with --fix the fixers to run, by the names --list prints`,candidates:()=>[...STEP_NAMES]},timeout:{type:"string",short:"t",description:"longest a step or fixer may run before it is ended (30s, 5m, 1h), none by default"},...placeOptions,json:jsonOption("[{name, command, in?, ok, ms, log, failed?}], with --list [{name, command, source, in?}], with --fix {fixers, changed}"),fix:{type:"boolean",short:"f",description:"run the folder's fixers and formatters instead of the steps"},quiet:{type:"boolean",short:"q",description:"print nothing for a passing step, and nothing at all when every step passes"},failed:{type:"boolean",description:"run only the steps that failed in the last run of this folder, read from the run folder"},changed:{type:"boolean",short:"c",description:"narrow lint and test to the files changed against HEAD (a bare linter script, a bare bun test script), every other step runs in full and says so"},slot:{type:"boolean",description:"run each step through slot, queued behind the machine-wide slots of the other sessions, as it does by default when the slot bin is installed; fails without the bin"},"no-slot":{type:"boolean",description:"run the steps at once, without queueing behind the other sessions' slots"},parallel:{type:"boolean",description:"run the steps at the same time, printing each one's output in step order"}},COMMA=/\s*,\s*/;function pick(steps,only,noun="step"){if(only===void 0)return steps;let names=only.split(COMMA).filter((name)=>name!=="");if(names.length===0)fail(`--only names no ${noun}, found ${steps.map((step)=>step.name).join(", ")}`);let unknown=names.filter((name)=>!steps.some((step)=>step.name===name));if(unknown.length>0)fail(`no ${unknown.join(", ")} ${noun} here, found ${[...new Set(steps.map((step)=>step.name))].join(", ")}`);return steps.filter((step)=>names.includes(step.name))}var RUNNING="KAYNOOO_CLI_FIX",JUSTFILES=["justfile","Justfile",".justfile"],RUFF_CONFIGS=["ruff.toml",".ruff.toml"],RUFF_SECTION=/^\[tool\.ruff/m,MAX_CHANGED=30;async function replaceFile(path,content){let temporary=`${path}.${process.pid}.tmp`;await writeFile(temporary,content,{mode:statSync(path).mode&511}),await rename(temporary,path)}async function projectFixers(dir){let found=await candidates(dir,"check"),named=(name)=>found.find((step)=>step.name===name),all=named("fix");if(all!==void 0)return[all];return[named("lint:fix")??named("lint-fix"),named("fmt")??named("format")].filter((step)=>step!==void 0)}async function toolFixers(dir){let fixers=[],makefile=await firstFile(dir,MAKEFILES),justfile=await firstFile(dir,JUSTFILES),ruff=await firstFile(dir,RUFF_CONFIGS)!==void 0||RUFF_SECTION.test(await read(dir,"pyproject.toml")??"");if(makefile!==void 0)fixers.push({name:"makefile",command:"declare every target .PHONY",source:makefile,write:async(cwd)=>{let path=join2(cwd,makefile),current=await Bun.file(path).text(),{content,targets}=declarePhony(current,(name)=>existsSync(join2(cwd,name)));if(content!==current)await replaceFile(path,content);return`.PHONY: ${targets.join(" ")}`}});if(justfile!==void 0)fixers.push({name:"justfile",command:`just --justfile ${justfile} --fmt`,source:justfile,requires:"just"});if(await Bun.file(join2(dir,"go.mod")).exists())fixers.push({name:"go",command:"go fmt ./... && go mod tidy",source:"go.mod",requires:"go"});if(await Bun.file(join2(dir,"Cargo.toml")).exists())fixers.push({name:"rust",command:"cargo fmt",source:"Cargo.toml",requires:"cargo"});if(ruff)fixers.push({name:"python",command:"ruff check --fix . && ruff format .",source:"ruff",requires:"ruff"});return fixers}async function fixers(dir){let project=await projectFixers(dir),csFixer=await firstFile(dir,CS_FIXER_CONFIGS),php=csFixer===void 0||project.some((fixer)=>fixer.source==="composer.json")?[]:[{name:"php-cs-fixer",command:"vendor/bin/php-cs-fixer fix",source:csFixer}];return[...project,...php,...await toolFixers(dir)]}function runsInService(fixer){return fixer.write===void 0&&fixer.requires===void 0}async function runFixer(fixer,placement,cwd,logFile,settings){if(fixer.write===void 0&&placement!==void 0)return runStep(shellIn(placement,fixer.command,{[RUNNING]:"1"}),cwd,logFile,{...settings,env:{[RUNNING]:"1"}});if(fixer.write===void 0)return runStep(fixer.command,cwd,logFile,{...settings,env:{[RUNNING]:"1"}});let started=Date.now(),outcome;try{outcome={ok:!0,ms:0,output:await fixer.write(cwd)}}catch(error){outcome={ok:!1,ms:0,output:error instanceof Error?error.message:String(error)}}return await writeFile(logFile,outcome.output,{mode:384,flag:"wx"}),{...outcome,ms:Date.now()-started}}function printChanged(changed){if(changed.length===0){console.log("nothing changed");return}console.log(`changed ${changed.length} file${changed.length===1?"":"s"}:`);for(let path of changed.slice(0,MAX_CHANGED))console.log(` ${path}`);if(changed.length>MAX_CHANGED)console.log(` and ${changed.length-MAX_CHANGED} more`)}async function runFixers(values,cwd){let parsed={values},settings=placeSettings(values);if(process.env[RUNNING]!==void 0)fail("a fixer called check --fix again, which would recurse: give its script another command");let found=await fixers(cwd);if(found.length===0)fail("nothing to fix here: no fix, lint:fix, fmt or format script, php-cs-fixer config, Makefile, Justfile, go.mod, Cargo.toml nor ruff config");let picked=pick(found,parsed.values.only,"fixer"),placements=new Map;for(let fixer of picked)placements.set(fixer,runsInService(fixer)?await place(cwd,programOf(fixer.command),settings):void 0);let json=parsed.values.json===!0,missing=(fixer)=>fixer.requires!==void 0&&Bun.which(fixer.requires)===null;if(parsed.values.list===!0){if(json)printJson(picked.map((fixer)=>({name:fixer.name,command:fixer.command,source:fixer.source,...placements.get(fixer)===void 0?{}:{in:placements.get(fixer)?.service},...missing(fixer)?{needs:fixer.requires}:{}})));else console.log(table(picked.map((fixer)=>[fixer.name,fixer.command,missing(fixer)?`${fixer.source}, needs ${fixer.requires}`:fixer.source,placements.get(fixer)?.service??"host"])));return 0}let timeoutMs=parsed.values.timeout===void 0?void 0:duration(parsed.values.timeout,"timeout",0),directory=await logDirectory(cwd),held=holdSignals(),runSettings={...timeoutMs===void 0?{}:{timeoutMs},held},stack=new Stack,width=Math.max(...picked.map((fixer)=>fixer.name.length)),before=await dirtyFiles(cwd),ran=[],failed=0,timedOut=!1;try{for(let fixer of picked){if(held.signal!==void 0)break;if(missing(fixer)){if(!json)console.log(`${paint(process.stdout).yellow("skip ")} ${fixer.name.padEnd(width)} ${fixer.requires} is not installed`);ran.push({name:fixer.name,command:fixer.command,skipped:`${fixer.requires} is not installed`});continue}let logFile=join2(directory,`fix-${fixer.name.replaceAll(":","-")}.log`),placement=placements.get(fixer),down=placement===void 0?void 0:await stack.problem(placement),outcome=down===void 0?await runFixer(fixer,placement,cwd,logFile,runSettings):await refusedStep(down,logFile);if(!json)printOutcome(fixer.name,width,placement===void 0?fixer.command:`${fixer.command} (in ${placement.service})`,logFile,outcome);if(ran.push(outcomeJson(fixer.name,fixer.command,logFile,outcome,placement?.service)),outcome.timedOut===!0)timedOut=!0;if(!outcome.ok)failed++}}finally{held.release()}let after=before&&await dirtyFiles(cwd),changed=before!==void 0&&after!==void 0?changedFiles(before,after):null;if(json)printJson({fixers:ran,changed});else if(changed!==null)printChanged(changed);if(held.signal!==void 0)return exitCodeOf(null,held.signal);if(timedOut)return 2;return failed===0?0:1}import{existsSync as existsSync2}from"fs";import{basename,dirname,extname,join as join3}from"path";var{$:$2}=globalThis.Bun;var LINTERS=/^(?:keslint|eslint|oxlint)\b/,LINTABLE=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".svelte"]),TEST_RUNNER=/^(?:bun test|\$npm_execpath test)\b/,TEST_FILE=/\.(?:test|spec)\.[jt]sx?$/,WHITESPACE=/\s+/;async function changedPaths(dir){let tracked=await $2`git diff --name-only --relative -z HEAD`.cwd(dir).quiet().nothrow(),untracked=await $2`git ls-files -z --others --exclude-standard`.cwd(dir).quiet().nothrow();if(tracked.exitCode!==0||untracked.exitCode!==0)return;return[...new Set([...tracked.stdout.toString().split("\x00"),...untracked.stdout.toString().split("\x00")])].filter((path)=>path!==""&&existsSync2(join3(dir,path)))}function siblingTests(path,exists){let extension=extname(path),name=basename(path,extension),dir=dirname(path),folders=[dir,join3(dir,"tests"),join3(dir,"..","tests"),join3(dir,"__tests__")],found=new Set;for(let folder of folders)for(let kind of["test","spec"])for(let candidate of[`${name}.${kind}${extension}`,`${name}.${kind}.ts`].map((file)=>join3(folder,file)))if(exists(candidate))found.add(candidate);return[...found]}function isBare(script,tool){return tool.test(script.trim())&&script.trim().replace(tool,"").split(WHITESPACE).every((word)=>word.startsWith("-")||word==="")}async function narrow(step,dir,changed){let script=step.source==="package.json"?(await scriptText(dir,step.name))?.trim():void 0,full=(why)=>({command:step.command,note:`in full, ${why}`});if(script!==void 0&&step.name==="lint"&&isBare(script,LINTERS)){let files=changed.filter((path)=>LINTABLE.has(extname(path)));return files.length===0?{command:"true",note:"nothing changed to lint"}:{command:`${step.command} -- ${files.map(quote).join(" ")}`,note:`${files.length} changed file${files.length===1?"":"s"}`}}if(script!==void 0&&step.name==="test"&&isBare(script,TEST_RUNNER)){let tests=new Set;for(let path of changed)if(TEST_FILE.test(path))tests.add(path);else for(let test of siblingTests(path,(candidate)=>existsSync2(join3(dir,candidate))))tests.add(test);if(tests.size===0)return full("no test sits next to the changed files");return{command:`${step.command} -- ${[...tests].map((test)=>quote(`./${test}`)).join(" ")}`,note:`${tests.size} test file${tests.size===1?"":"s"}`}}return full(`${step.name} cannot be narrowed`)}function quote(path){return`'${path.replaceAll("'","'\\''")}'`}async function scriptText(dir,name){let text=await read(dir,"package.json");if(text===void 0)return;try{let value=JSON.parse(text).scripts?.[name];return typeof value==="string"?value:void 0}catch{return}}var usage=`check [--only <steps>] [--changed] [--failed] [--quiet] [--timeout <duration>] [--slot | --no-slot] [--parallel] [--in <service> | --host] [--list]
2552
9
  check --fix [--only <fixers>] [--timeout <duration>] [--in <service> | --host] [--list]
2553
10
 
2554
11
  Runs the repo's check, typecheck, lint, fmt (its fmt:check or format:check script) and test steps, found in package.json scripts, composer.json, a Justfile, a Makefile or the PHP tools' configs; a folder with no steps runs its subfolders' (api/, client/).
2555
12
  A step runs inside the running compose service that mounts its folder and never starts one, and queues for a machine-wide slot when \`slot\` is installed.
2556
13
  A passing step prints one line, a failing one only what failed, and each step's full log is saved to the file its line ends with.
2557
- With --fix, the project's fix, lint:fix and fmt or format scripts run instead, then the formatters its files call for (php-cs-fixer, \`just --fmt\`, go fmt, cargo fmt, ruff), and the files they changed are listed.`;
2558
- var EXITS = [[0, "every step passed"], [1, "one failed"], [2, "bad usage, no step is found or a step timed out"]];
2559
- function slotted(command) {
2560
- return `slot -- sh -c ${shellQuote(command)}`;
2561
- }
2562
- async function plan(steps, settings) {
2563
- const planned = [];
2564
- for (const { project, ...step } of steps)
2565
- planned.push({ ...step, dir: project.dir, label: project.name === undefined ? step.name : `${project.name}/${step.name}`, placement: await place(project.dir, programOf(step.command), settings) });
2566
- return planned;
2567
- }
2568
- async function narrowed(steps) {
2569
- const cache = new Map;
2570
- const result = [];
2571
- for (const step of steps) {
2572
- if (!cache.has(step.dir)) {
2573
- const paths = await changedPaths(step.dir);
2574
- if (paths === undefined)
2575
- fail("--changed needs a git repository");
2576
- cache.set(step.dir, paths);
2577
- }
2578
- const { command, note } = await narrow2(step, step.dir, cache.get(step.dir) ?? []);
2579
- result.push({ ...step, command, note });
2580
- }
2581
- return result;
2582
- }
2583
- function launch(step) {
2584
- return step.placement === undefined ? step.command : shellIn(step.placement, step.command);
2585
- }
2586
- function summaryLine(outcomes) {
2587
- const colors = paint(process23.stdout);
2588
- const failed = outcomes.filter((outcome) => !outcome.ok).length;
2589
- const passed = outcomes.length - failed;
2590
- const parts = [colors.green(`${passed} passed`), ...failed === 0 ? [] : [colors.red(`${failed} failed`)], colors.dim(formatDuration(outcomes.reduce((sum, outcome) => sum + outcome.ms, 0)))];
2591
- return parts.join(colors.dim(" \xB7 "));
2592
- }
2593
- async function check(args, cwd = process23.cwd()) {
2594
- const parsed = parse(args, usage2, options, { exits: EXITS, replaces: "chaining docker compose exec <service> bun run check | tail, lint and test by hand, or bun run check && bun run lint && bun run test read through tail, and with --fix each fixer and formatter run by hand", examples: ["check", ["check --only lint,test", "two of the steps"], ["check --in app", "every step inside the app service"], ["check --fix", "the fixers and formatters instead"], ["check --fix --list", "the fixers it would run"]] });
2595
- const settings = placeSettings(parsed.values);
2596
- if (parsed.values.fix === true) {
2597
- for (const flag of ["changed", "failed", "slot", "no-slot", "parallel"]) {
2598
- if (parsed.values[flag] === true)
2599
- fail(`--${flag} does not apply to --fix`);
2600
- }
2601
- return runFixers(parsed.values, cwd);
2602
- }
2603
- const timeoutMs = parsed.values.timeout === undefined ? undefined : duration(parsed.values.timeout, "timeout", 0);
2604
- if (parsed.values.slot === true && parsed.values["no-slot"] === true)
2605
- fail("--slot and --no-slot exclude each other");
2606
- const hasSlot = Bun.which("slot", { PATH: process23.env.PATH ?? "" }) !== null;
2607
- if (parsed.values.slot === true && !hasSlot)
2608
- fail("--slot needs the slot bin: bun install -g @kaynooo/cli-wait");
2609
- const slotting = parsed.values["no-slot"] !== true && hasSlot;
2610
- const projects = await discoverProjects(cwd);
2611
- const found = projects.flatMap((project) => project.steps.map((step) => ({ ...step, project })));
2612
- if (found.length === 0)
2613
- fail(`no ${STEP_NAMES.join(", ")} step in package.json, composer.json, a Justfile, a Makefile or a PHP tool's config, nor in a subfolder`);
2614
- let wanted = pick(found, parsed.values.only);
2615
- if (parsed.values.failed === true) {
2616
- const failed = await lastFailed(cwd);
2617
- if (failed === undefined || failed.length === 0)
2618
- fail("no failed step in the last run of this folder");
2619
- wanted = wanted.filter((step) => failed.includes(step.project.name === undefined ? step.name : `${step.project.name}/${step.name}`));
2620
- if (wanted.length === 0)
2621
- fail(`none of the steps picked failed in the last run, which failed ${failed.join(", ")}`);
2622
- }
2623
- const planned = await plan(wanted, settings);
2624
- const steps = parsed.values.changed === true ? await narrowed(planned) : planned;
2625
- const json = parsed.values.json === true;
2626
- if (parsed.values.list === true) {
2627
- if (json)
2628
- printJson(steps.map(({ label, command, source, placement }) => ({ name: label, command, source, ...placement === undefined ? {} : { in: placement.service } })));
2629
- else
2630
- console.log(table(steps.map((step) => [step.label, step.command, step.source, step.placement?.service ?? "host"])));
2631
- return 0;
2632
- }
2633
- const directory = await logDirectory(cwd);
2634
- const held = holdSignals();
2635
- const stack = new Stack;
2636
- const width = Math.max(...steps.map((step) => step.label.length));
2637
- const outcomes = [];
2638
- const quiet = parsed.values.quiet === true;
2639
- const heading = json || quiet ? "" : header("check", `${basename4(cwd)} \xB7 ${steps.length} ${steps.length === 1 ? "step" : "steps"}`, process23.stdout);
2640
- if (heading !== "")
2641
- console.log(heading);
2642
- const execute = async (step, signals) => {
2643
- const logFile = join14(directory, `${step.label.replaceAll("/", "-")}.log`);
2644
- const down = step.placement === undefined ? undefined : await stack.problem(step.placement);
2645
- const command = slotting ? slotted(launch(step)) : launch(step);
2646
- const outcome = down === undefined ? await runStep(command, step.dir, logFile, { ...timeoutMs === undefined ? {} : { timeoutMs }, held: signals }) : await refusedStep(down, logFile);
2647
- return { step, logFile, outcome };
2648
- };
2649
- const report = ({ step, logFile, outcome }) => {
2650
- if (!json && !(quiet && outcome.ok))
2651
- printOutcome(step.label, width, `${step.command}${step.note === undefined ? "" : ` (${step.note})`}${step.placement === undefined ? "" : ` (in ${step.placement.service})`}`, logFile, outcome);
2652
- outcomes.push(outcomeJson(step.label, step.command, logFile, outcome, step.placement?.service));
2653
- };
2654
- try {
2655
- if (parsed.values.parallel === true) {
2656
- const children = new Set;
2657
- const shared = { get signal() {
2658
- return held.signal;
2659
- }, forward: (child) => children.add(child), release: held.release };
2660
- held.forward({ kill: (signal) => {
2661
- for (const child of children) {
2662
- child.kill(signal);
2663
- }
2664
- } });
2665
- for (const run of steps.map(async (step) => execute(step, shared)))
2666
- report(await run);
2667
- } else {
2668
- for (const step of steps) {
2669
- report(await execute(step, held));
2670
- if (held.signal !== undefined)
2671
- break;
2672
- }
2673
- }
2674
- } finally {
2675
- held.release();
2676
- }
2677
- const ran = outcomes.map(({ name, ok }) => ({ name, ok }));
2678
- const kept = (await lastResults(cwd) ?? []).filter(({ name }) => !ran.some((each) => each.name === name));
2679
- await writeFile3(join14(directory, RESULTS_FILE), JSON.stringify([...kept, ...ran]), { mode: 384 });
2680
- if (json)
2681
- printJson(outcomes);
2682
- else if (heading !== "" || quiet && !outcomes.every((outcome) => outcome.ok))
2683
- console.log(summaryLine(outcomes));
2684
- if (held.signal !== undefined)
2685
- return exitCodeOf(null, held.signal);
2686
- if (outcomes.some((outcome) => outcome.timedOut === true))
2687
- return 2;
2688
- return outcomes.every((outcome) => outcome.ok) ? 0 : 1;
2689
- }
2690
-
2691
- // src/cli.ts
2692
- process24.exitCode = await runMain({ name: "check", version, run: async (args) => check(args) });
14
+ With --fix, the project's fix, lint:fix and fmt or format scripts run instead, then the formatters its files call for (php-cs-fixer, \`just --fmt\`, go fmt, cargo fmt, ruff), and the files they changed are listed.`,EXITS=[[0,"every step passed"],[1,"one failed"],[2,"bad usage, no step is found or a step timed out"]];function slotted(command){return`slot -- sh -c ${shellQuote(command)}`}async function plan(steps,settings){let planned=[];for(let{project,...step}of steps)planned.push({...step,dir:project.dir,label:project.name===void 0?step.name:`${project.name}/${step.name}`,placement:await place(project.dir,programOf(step.command),settings)});return planned}async function narrowed(steps){let cache=new Map,result=[];for(let step of steps){if(!cache.has(step.dir)){let paths=await changedPaths(step.dir);if(paths===void 0)fail("--changed needs a git repository");cache.set(step.dir,paths)}let{command,note}=await narrow(step,step.dir,cache.get(step.dir)??[]);result.push({...step,command,note})}return result}function launch(step){return step.placement===void 0?step.command:shellIn(step.placement,step.command)}function summaryLine(outcomes){let colors=paint(process2.stdout),failed=outcomes.filter((outcome)=>!outcome.ok).length,passed=outcomes.length-failed;return[colors.green(`${passed} passed`),...failed===0?[]:[colors.red(`${failed} failed`)],colors.dim(formatDuration(outcomes.reduce((sum,outcome)=>sum+outcome.ms,0)))].join(colors.dim(" \xB7 "))}async function check(args,cwd=process2.cwd()){let parsed=parse(args,usage,options,{exits:EXITS,replaces:"chaining docker compose exec <service> bun run check | tail, lint and test by hand, or bun run check && bun run lint && bun run test read through tail, and with --fix each fixer and formatter run by hand",examples:["check",["check --only lint,test","two of the steps"],["check --in app","every step inside the app service"],["check --fix","the fixers and formatters instead"],["check --fix --list","the fixers it would run"]]}),settings=placeSettings(parsed.values);if(parsed.values.fix===!0){for(let flag of["changed","failed","slot","no-slot","parallel"])if(parsed.values[flag]===!0)fail(`--${flag} does not apply to --fix`);return runFixers(parsed.values,cwd)}let timeoutMs=parsed.values.timeout===void 0?void 0:duration(parsed.values.timeout,"timeout",0);if(parsed.values.slot===!0&&parsed.values["no-slot"]===!0)fail("--slot and --no-slot exclude each other");let hasSlot=Bun.which("slot",{PATH:process2.env.PATH??""})!==null;if(parsed.values.slot===!0&&!hasSlot)fail("--slot needs the slot bin: bun install -g @kaynooo/cli-wait");let slotting=parsed.values["no-slot"]!==!0&&hasSlot,found=(await discoverProjects(cwd)).flatMap((project)=>project.steps.map((step)=>({...step,project})));if(found.length===0)fail(`no ${STEP_NAMES.join(", ")} step in package.json, composer.json, a Justfile, a Makefile or a PHP tool's config, nor in a subfolder`);let wanted=pick(found,parsed.values.only);if(parsed.values.failed===!0){let failed=await lastFailed(cwd);if(failed===void 0||failed.length===0)fail("no failed step in the last run of this folder");if(wanted=wanted.filter((step)=>failed.includes(step.project.name===void 0?step.name:`${step.project.name}/${step.name}`)),wanted.length===0)fail(`none of the steps picked failed in the last run, which failed ${failed.join(", ")}`)}let planned=await plan(wanted,settings),steps=parsed.values.changed===!0?await narrowed(planned):planned,json=parsed.values.json===!0;if(parsed.values.list===!0){if(json)printJson(steps.map(({label,command,source,placement})=>({name:label,command,source,...placement===void 0?{}:{in:placement.service}})));else console.log(table(steps.map((step)=>[step.label,step.command,step.source,step.placement?.service??"host"])));return 0}let directory=await logDirectory(cwd),held=holdSignals(),stack=new Stack,width=Math.max(...steps.map((step)=>step.label.length)),outcomes=[],quiet=parsed.values.quiet===!0,heading=json||quiet?"":header("check",`${basename2(cwd)} \xB7 ${steps.length} ${steps.length===1?"step":"steps"}`,process2.stdout);if(heading!=="")console.log(heading);let execute=async(step,signals)=>{let logFile=join4(directory,`${step.label.replaceAll("/","-")}.log`),down=step.placement===void 0?void 0:await stack.problem(step.placement),command=slotting?slotted(launch(step)):launch(step),outcome=down===void 0?await runStep(command,step.dir,logFile,{...timeoutMs===void 0?{}:{timeoutMs},held:signals}):await refusedStep(down,logFile);return{step,logFile,outcome}},report=({step,logFile,outcome})=>{if(!json&&!(quiet&&outcome.ok))printOutcome(step.label,width,`${step.command}${step.note===void 0?"":` (${step.note})`}${step.placement===void 0?"":` (in ${step.placement.service})`}`,logFile,outcome);outcomes.push(outcomeJson(step.label,step.command,logFile,outcome,step.placement?.service))};try{if(parsed.values.parallel===!0){let children=new Set,shared={get signal(){return held.signal},forward:(child)=>children.add(child),release:held.release};held.forward({kill:(signal)=>{for(let child of children)child.kill(signal)}});for(let run of steps.map(async(step)=>execute(step,shared)))report(await run)}else for(let step of steps)if(report(await execute(step,held)),held.signal!==void 0)break}finally{held.release()}let ran=outcomes.map(({name,ok})=>({name,ok})),kept=(await lastResults(cwd)??[]).filter(({name})=>!ran.some((each)=>each.name===name));if(await writeFile2(join4(directory,RESULTS_FILE),JSON.stringify([...kept,...ran]),{mode:384}),json)printJson(outcomes);else if(heading!==""||quiet&&!outcomes.every((outcome)=>outcome.ok))console.log(summaryLine(outcomes));if(held.signal!==void 0)return exitCodeOf(null,held.signal);if(outcomes.some((outcome)=>outcome.timedOut===!0))return 2;return outcomes.every((outcome)=>outcome.ok)?0:1}process3.exitCode=await runMain({name:"check",version,run:async(args)=>check(args)});