@kaynooo/cli-code 0.15.0 → 0.17.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -21
- package/dist/cli.js +959 -269
- package/package.json +10 -16
- package/dist/hotspots-cli.js +0 -1580
- package/dist/peek-cli.js +0 -1804
- package/dist/todo-scan-cli.js +0 -1573
package/dist/todo-scan-cli.js
DELETED
|
@@ -1,1573 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
|
-
// @bun
|
|
3
|
-
|
|
4
|
-
// src/todo-scan-cli.ts
|
|
5
|
-
import process17 from "process";
|
|
6
|
-
// ../kit/src/args.ts
|
|
7
|
-
import process9 from "process";
|
|
8
|
-
import { parseArgs } from "util";
|
|
9
|
-
|
|
10
|
-
// ../kit/src/format.ts
|
|
11
|
-
import process7 from "process";
|
|
12
|
-
|
|
13
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
|
|
14
|
-
var ct = /[aeiou]y$/;
|
|
15
|
-
var N = new Map;
|
|
16
|
-
var Ot = /(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/;
|
|
17
|
-
var Gt = /(?:knife|life|wife)$/;
|
|
18
|
-
function K(t, e, { plural: r, zero: n = "singular" } = {}) {
|
|
19
|
-
if (e === 1 || e === 0 && n === "singular")
|
|
20
|
-
return t;
|
|
21
|
-
if (r !== undefined)
|
|
22
|
-
return r;
|
|
23
|
-
if (t.endsWith("y") && !ct.test(t))
|
|
24
|
-
return `${t.slice(0, -1)}ies`;
|
|
25
|
-
if (t.endsWith("s") || t.endsWith("x") || t.endsWith("z") || t.endsWith("ch") || t.endsWith("sh"))
|
|
26
|
-
return `${t}es`;
|
|
27
|
-
if (Ot.test(t))
|
|
28
|
-
return `${t.slice(0, -1)}ves`;
|
|
29
|
-
return Gt.test(t) ? `${t.slice(0, -2)}ves` : `${t}s`;
|
|
30
|
-
}
|
|
31
|
-
function go(t, e, { zero: r = "plural", ...n } = {}) {
|
|
32
|
-
return `${t} ${K(e, t, { ...n, zero: r })}`;
|
|
33
|
-
}
|
|
34
|
-
var Nt = /\s+\S*$/;
|
|
35
|
-
var Y = /\s/;
|
|
36
|
-
function ko(t, e, r = "...") {
|
|
37
|
-
let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
|
|
38
|
-
if (t.length <= e)
|
|
39
|
-
return t;
|
|
40
|
-
let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
|
|
41
|
-
if (o && !Y.test(t[c.length] ?? " "))
|
|
42
|
-
c = c.replace(Nt, "") || c;
|
|
43
|
-
if (o)
|
|
44
|
-
c = c.trimEnd();
|
|
45
|
-
return s ? (c + n).slice(0, l) : c + n;
|
|
46
|
-
}
|
|
47
|
-
var 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));
|
|
48
|
-
var z = new Map;
|
|
49
|
-
|
|
50
|
-
// ../kit/src/mode.ts
|
|
51
|
-
import process2 from "process";
|
|
52
|
-
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
53
|
-
var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
54
|
-
function isSet(value) {
|
|
55
|
-
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
56
|
-
}
|
|
57
|
-
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
58
|
-
const chosen = env.KIT_MODE;
|
|
59
|
-
if (chosen !== undefined && MODES.has(chosen))
|
|
60
|
-
return chosen;
|
|
61
|
-
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
62
|
-
return "agent";
|
|
63
|
-
if (stream.isTTY === true)
|
|
64
|
-
return "terminal";
|
|
65
|
-
return isSet(env.CI) ? "ci" : "pipe";
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// ../kit/src/style.ts
|
|
69
|
-
import { resolve as resolve3 } from "path";
|
|
70
|
-
import process6 from "process";
|
|
71
|
-
import { pathToFileURL } from "url";
|
|
72
|
-
|
|
73
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
74
|
-
var G2 = /^[a-f0-9]+$/i;
|
|
75
|
-
function b(r) {
|
|
76
|
-
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
77
|
-
if (!G2.test(e))
|
|
78
|
-
return [0, 0, 0];
|
|
79
|
-
if (e.length === 3 || e.length === 4)
|
|
80
|
-
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
81
|
-
if (e.length !== 6 && e.length !== 8)
|
|
82
|
-
throw Error(`Invalid hex color length: ${e.length}`);
|
|
83
|
-
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
84
|
-
}
|
|
85
|
-
var B2 = { 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") => {
|
|
86
|
-
let [l, n, c] = b(r);
|
|
87
|
-
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
88
|
-
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
89
|
-
var h = new Set(["", "1", "2", "3", "true"]);
|
|
90
|
-
function C(r, e = globalThis.process?.env ?? {}) {
|
|
91
|
-
if (e.FORCE_COLOR !== undefined)
|
|
92
|
-
return h.has(e.FORCE_COLOR);
|
|
93
|
-
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
94
|
-
return false;
|
|
95
|
-
return r?.isTTY === true;
|
|
96
|
-
}
|
|
97
|
-
function f(r, e = []) {
|
|
98
|
-
let l = "", n = "";
|
|
99
|
-
for (let t = 0, i = e.length;t < i; t++)
|
|
100
|
-
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
101
|
-
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
102
|
-
return new Proxy(c, { get(t, i) {
|
|
103
|
-
let a = B2[i];
|
|
104
|
-
if (Array.isArray(a)) {
|
|
105
|
-
let s = g.get(i);
|
|
106
|
-
if (s === undefined)
|
|
107
|
-
s = f(r, [...e, a]), g.set(i, s);
|
|
108
|
-
return s;
|
|
109
|
-
}
|
|
110
|
-
if (typeof a === "function")
|
|
111
|
-
return (...s) => {
|
|
112
|
-
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
113
|
-
if (u === undefined) {
|
|
114
|
-
if (g.size >= 64)
|
|
115
|
-
g.clear();
|
|
116
|
-
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
117
|
-
}
|
|
118
|
-
return u;
|
|
119
|
-
};
|
|
120
|
-
throw Error(`Unknown style: ${String(i)}`);
|
|
121
|
-
} });
|
|
122
|
-
}
|
|
123
|
-
function Fe(r = {}) {
|
|
124
|
-
return f(r);
|
|
125
|
-
}
|
|
126
|
-
var o = Fe();
|
|
127
|
-
|
|
128
|
-
// ../kit/src/theme.ts
|
|
129
|
-
import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
|
|
130
|
-
import { homedir as homedir2 } from "os";
|
|
131
|
-
import { join as join3, resolve as resolve2 } from "path";
|
|
132
|
-
import process5 from "process";
|
|
133
|
-
|
|
134
|
-
// ../kit/src/config.ts
|
|
135
|
-
import { existsSync } from "fs";
|
|
136
|
-
import { dirname, join, resolve } from "path";
|
|
137
|
-
import process3 from "process";
|
|
138
|
-
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
139
|
-
const wanted = typeof names === "string" ? [names] : names;
|
|
140
|
-
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
141
|
-
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
142
|
-
if (found !== undefined)
|
|
143
|
-
return found;
|
|
144
|
-
if (stop(dir) || dirname(dir) === dir)
|
|
145
|
-
return;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
// ../kit/src/user-config.ts
|
|
150
|
-
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
151
|
-
import { homedir } from "os";
|
|
152
|
-
import { join as join2 } from "path";
|
|
153
|
-
import process4 from "process";
|
|
154
|
-
function configBase(where = {}) {
|
|
155
|
-
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
156
|
-
return xdg !== undefined && xdg !== "" ? 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
|
-
function configuredNumber(bin, key, fallback, where = {}, legacy = []) {
|
|
180
|
-
const value = readUserConfig(bin, where, legacy)[key];
|
|
181
|
-
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// ../kit/src/theme.ts
|
|
185
|
-
var ENDS = new Map;
|
|
186
|
-
var DEFAULT = {
|
|
187
|
-
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" },
|
|
188
|
-
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" },
|
|
189
|
-
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
190
|
-
bins: {},
|
|
191
|
-
gradient: ["#c084fc", "#67e8f9"]
|
|
192
|
-
};
|
|
193
|
-
var 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" };
|
|
194
|
-
var 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" };
|
|
195
|
-
var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
196
|
-
var PRESETS = {
|
|
197
|
-
default: {},
|
|
198
|
-
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
199
|
-
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
200
|
-
ascii: { glyphs: ASCII }
|
|
201
|
-
};
|
|
202
|
-
var 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"]);
|
|
203
|
-
var HEX = /^#[0-9a-f]{6}$/i;
|
|
204
|
-
var CONTROL = /\p{Cc}/u;
|
|
205
|
-
var MAX_FILE_BYTES = 64 * 1024;
|
|
206
|
-
var SPACES = /\s+/;
|
|
207
|
-
function isColorSpec(spec) {
|
|
208
|
-
if (typeof spec === "number")
|
|
209
|
-
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
210
|
-
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
211
|
-
}
|
|
212
|
-
var CUBE = [0, 95, 135, 175, 215, 255];
|
|
213
|
-
function cubeLevel(channel) {
|
|
214
|
-
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
215
|
-
}
|
|
216
|
-
function nearest256(hex) {
|
|
217
|
-
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
218
|
-
const levels = rgb.map(cubeLevel);
|
|
219
|
-
const cube = levels.map((level) => CUBE[level]);
|
|
220
|
-
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
221
|
-
const greyValue = 8 + grey * 10;
|
|
222
|
-
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
223
|
-
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
224
|
-
}
|
|
225
|
-
function hasTrueColor(env) {
|
|
226
|
-
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
227
|
-
}
|
|
228
|
-
function tinted(colors, spec, env = process5.env) {
|
|
229
|
-
if (typeof spec === "number")
|
|
230
|
-
return colors.ansi256(spec);
|
|
231
|
-
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
232
|
-
if (HEX.test(token))
|
|
233
|
-
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
234
|
-
return chain[token] ?? chain;
|
|
235
|
-
}, colors);
|
|
236
|
-
}
|
|
237
|
-
function isRecord(value) {
|
|
238
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
239
|
-
}
|
|
240
|
-
function readThemeFile(path, warn) {
|
|
241
|
-
try {
|
|
242
|
-
const stat = statSync(path, { throwIfNoEntry: false });
|
|
243
|
-
if (stat === undefined)
|
|
244
|
-
return;
|
|
245
|
-
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
246
|
-
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
247
|
-
return;
|
|
248
|
-
}
|
|
249
|
-
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
250
|
-
if (isRecord(parsed))
|
|
251
|
-
return parsed;
|
|
252
|
-
warn(`${path} is not a JSON object, theme ignored`);
|
|
253
|
-
} catch (error) {
|
|
254
|
-
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
255
|
-
}
|
|
256
|
-
return;
|
|
257
|
-
}
|
|
258
|
-
function applyPreset(theme, name, warn, where) {
|
|
259
|
-
if (name === undefined)
|
|
260
|
-
return;
|
|
261
|
-
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
262
|
-
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
263
|
-
return;
|
|
264
|
-
}
|
|
265
|
-
const preset = PRESETS[name];
|
|
266
|
-
Object.assign(theme.colors, preset.colors);
|
|
267
|
-
Object.assign(theme.glyphs, preset.glyphs);
|
|
268
|
-
if (preset.accents !== undefined)
|
|
269
|
-
theme.accents = [...preset.accents];
|
|
270
|
-
if (Object.hasOwn(preset, "gradient"))
|
|
271
|
-
theme.gradient = preset.gradient;
|
|
272
|
-
return name;
|
|
273
|
-
}
|
|
274
|
-
function applyFile(theme, file, where, warn) {
|
|
275
|
-
if (isRecord(file.colors)) {
|
|
276
|
-
for (const [key, value] of Object.entries(file.colors)) {
|
|
277
|
-
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
278
|
-
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
279
|
-
else if (!isColorSpec(value))
|
|
280
|
-
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
281
|
-
else
|
|
282
|
-
theme.colors[key] = value;
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
if (isRecord(file.glyphs)) {
|
|
286
|
-
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
287
|
-
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
288
|
-
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
289
|
-
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
290
|
-
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
291
|
-
else
|
|
292
|
-
theme.glyphs[key] = value;
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
296
|
-
theme.accents = [...file.accents];
|
|
297
|
-
else if (file.accents !== undefined)
|
|
298
|
-
warn(`${where}: accents must be a non-empty list of colours`);
|
|
299
|
-
if (file.gradient === null)
|
|
300
|
-
theme.gradient = undefined;
|
|
301
|
-
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
302
|
-
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
303
|
-
else if (file.gradient !== undefined)
|
|
304
|
-
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
305
|
-
if (isRecord(file.bins)) {
|
|
306
|
-
for (const [bin, value] of Object.entries(file.bins)) {
|
|
307
|
-
if (isColorSpec(value))
|
|
308
|
-
theme.bins[bin] = value;
|
|
309
|
-
else
|
|
310
|
-
warn(`${where}: bin ${bin} has no valid colour`);
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
function endsWalk(home) {
|
|
315
|
-
return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
|
|
316
|
-
}
|
|
317
|
-
var warned = new Set;
|
|
318
|
-
function warnOnce(message) {
|
|
319
|
-
if (warned.has(message))
|
|
320
|
-
return;
|
|
321
|
-
warned.add(message);
|
|
322
|
-
console.error(`warning: theme ${message}`);
|
|
323
|
-
}
|
|
324
|
-
function isPath(chosen) {
|
|
325
|
-
return chosen.includes("/") || chosen.endsWith(".json");
|
|
326
|
-
}
|
|
327
|
-
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
328
|
-
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
329
|
-
const sources = [];
|
|
330
|
-
const chosen = env.KIT_THEME ?? "";
|
|
331
|
-
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
332
|
-
if (isPath(chosen))
|
|
333
|
-
wanted.push(resolve2(from, chosen));
|
|
334
|
-
const files = [];
|
|
335
|
-
for (const path of wanted) {
|
|
336
|
-
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
337
|
-
if (path !== undefined && file !== undefined)
|
|
338
|
-
files.push({ path, file });
|
|
339
|
-
}
|
|
340
|
-
let preset = "default";
|
|
341
|
-
if (chosen !== "" && !isPath(chosen)) {
|
|
342
|
-
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
343
|
-
} else {
|
|
344
|
-
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
345
|
-
if (named !== undefined)
|
|
346
|
-
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
347
|
-
}
|
|
348
|
-
for (const { path, file } of files) {
|
|
349
|
-
applyFile(theme, file, path, warn);
|
|
350
|
-
sources.push(path);
|
|
351
|
-
}
|
|
352
|
-
return { theme, sources, preset };
|
|
353
|
-
}
|
|
354
|
-
var current;
|
|
355
|
-
var currentKey = "";
|
|
356
|
-
function activeTheme() {
|
|
357
|
-
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
358
|
-
if (current === undefined || key !== currentKey) {
|
|
359
|
-
current = loadTheme();
|
|
360
|
-
currentKey = key;
|
|
361
|
-
}
|
|
362
|
-
return current;
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
// ../kit/src/style.ts
|
|
366
|
-
var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
|
|
367
|
-
function takesControlCodes(stream, env = process6.env) {
|
|
368
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
369
|
-
}
|
|
370
|
-
function paint(stream, env = process6.env) {
|
|
371
|
-
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
372
|
-
}
|
|
373
|
-
function marked(mark, text, stream, detail, env = process6.env) {
|
|
374
|
-
const colors = paint(stream, env);
|
|
375
|
-
let head = MARK_WORDS[mark];
|
|
376
|
-
if (takesControlCodes(stream, env)) {
|
|
377
|
-
const { theme } = activeTheme();
|
|
378
|
-
head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
|
|
379
|
-
}
|
|
380
|
-
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
381
|
-
}
|
|
382
|
-
function warn(text, detail) {
|
|
383
|
-
console.error(marked("warn", text, process6.stderr, detail));
|
|
384
|
-
}
|
|
385
|
-
function role(name, stream, env = process6.env) {
|
|
386
|
-
const colors = paint(stream, env);
|
|
387
|
-
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
388
|
-
}
|
|
389
|
-
var STATUS_WORDS = {
|
|
390
|
-
passed: ["passed", "success", "succeeded", "ok"],
|
|
391
|
-
failed: ["failed", "failure", "error", "errored"],
|
|
392
|
-
running: ["running", "in_progress", "started", "holding"],
|
|
393
|
-
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
394
|
-
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
395
|
-
};
|
|
396
|
-
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
397
|
-
function header(bin, context, stream, env = process6.env) {
|
|
398
|
-
if (!takesControlCodes(stream, env))
|
|
399
|
-
return "";
|
|
400
|
-
const colors = paint(stream, env);
|
|
401
|
-
const hash = [...bin].reduce((sum, char) => sum + char.charCodeAt(0), 0);
|
|
402
|
-
const { theme } = activeTheme();
|
|
403
|
-
const spec = theme.bins[bin] ?? theme.accents[hash % theme.accents.length];
|
|
404
|
-
const accent = tinted(typeof spec === "string" && spec.split(" ").includes("bold") ? colors : colors.bold, spec, env);
|
|
405
|
-
return `${accent(bin)}${context === undefined ? "" : colors.dim(` \u203A ${context}`)}`;
|
|
406
|
-
}
|
|
407
|
-
function link(text, url, stream, env = process6.env) {
|
|
408
|
-
if (takesControlCodes(stream, env))
|
|
409
|
-
return `\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`;
|
|
410
|
-
return text === url ? text : `${text} (${url})`;
|
|
411
|
-
}
|
|
412
|
-
function printHeader(bin, context, stream = process6.stdout, env = process6.env) {
|
|
413
|
-
const line = header(bin, context, stream, env);
|
|
414
|
-
if (line !== "")
|
|
415
|
-
console.log(line);
|
|
416
|
-
}
|
|
417
|
-
function hyperlink(text, url, stream, env = process6.env) {
|
|
418
|
-
return takesControlCodes(stream, env) ? paint(stream, env).underline(link(text, url, stream, env)) : text;
|
|
419
|
-
}
|
|
420
|
-
function fileLink(text, path, stream, from = process6.cwd(), env = process6.env) {
|
|
421
|
-
return hyperlink(text, pathToFileURL(resolve3(from, path)).href, stream, env);
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
// ../kit/src/format.ts
|
|
425
|
-
var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
426
|
-
function formatSeconds(total) {
|
|
427
|
-
let rest = Math.max(0, Math.round(total));
|
|
428
|
-
const amounts = UNITS.map(([unit, size]) => {
|
|
429
|
-
const amount = Math.floor(rest / size);
|
|
430
|
-
rest -= amount * size;
|
|
431
|
-
return `${amount}${unit}`;
|
|
432
|
-
});
|
|
433
|
-
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
434
|
-
if (first === -1)
|
|
435
|
-
return "0s";
|
|
436
|
-
const next = amounts[first + 1];
|
|
437
|
-
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
438
|
-
}
|
|
439
|
-
function formatDuration(ms) {
|
|
440
|
-
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
441
|
-
}
|
|
442
|
-
function upTo(text, separator) {
|
|
443
|
-
const end = text.indexOf(separator);
|
|
444
|
-
return end === -1 ? text : text.slice(0, end);
|
|
445
|
-
}
|
|
446
|
-
function truncate(text, width) {
|
|
447
|
-
return ko(text, width, { suffix: "\u2026", includeSuffix: true });
|
|
448
|
-
}
|
|
449
|
-
var LINE_BREAKS = /\s*\n\s*/g;
|
|
450
|
-
var ESCAPE = String.fromCharCode(27);
|
|
451
|
-
function textWidth(text) {
|
|
452
|
-
return Bun.stringWidth(text);
|
|
453
|
-
}
|
|
454
|
-
function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
|
|
455
|
-
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
456
|
-
if (outputMode(stream, env) === "agent")
|
|
457
|
-
return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
|
|
458
|
-
`);
|
|
459
|
-
const widths = [];
|
|
460
|
-
for (const row of cells) {
|
|
461
|
-
for (const [index, cell] of row.entries())
|
|
462
|
-
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
463
|
-
}
|
|
464
|
-
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
465
|
-
const colors = paint(stream);
|
|
466
|
-
const lines = shown.map((row) => row.map((cell, index) => {
|
|
467
|
-
const width = widths[index] ?? 0;
|
|
468
|
-
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
469
|
-
if (align[index] === "right")
|
|
470
|
-
return `${gap}${cell}`;
|
|
471
|
-
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
472
|
-
}).join(" ").trimEnd());
|
|
473
|
-
const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
|
|
474
|
-
return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
|
|
475
|
-
`);
|
|
476
|
-
}
|
|
477
|
-
function narrow(rows, widths, limit) {
|
|
478
|
-
const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
|
|
479
|
-
const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
|
|
480
|
-
const floor = 8;
|
|
481
|
-
while (used() > limit) {
|
|
482
|
-
let widest = -1;
|
|
483
|
-
for (const [index, width] of widths.entries()) {
|
|
484
|
-
if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
|
|
485
|
-
widest = index;
|
|
486
|
-
}
|
|
487
|
-
if (widest === -1)
|
|
488
|
-
break;
|
|
489
|
-
widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
|
|
490
|
-
}
|
|
491
|
-
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
492
|
-
}
|
|
493
|
-
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
494
|
-
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
495
|
-
}
|
|
496
|
-
function printJson(value) {
|
|
497
|
-
console.log(jsonText(value));
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
// ../kit/src/help.ts
|
|
501
|
-
import process8 from "process";
|
|
502
|
-
var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
503
|
-
var USAGE_PREFIX = /^usage:\s*/i;
|
|
504
|
-
var FULL_STOP = /\.$/;
|
|
505
|
-
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
506
|
-
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
507
|
-
}
|
|
508
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
509
|
-
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
510
|
-
`);
|
|
511
|
-
}
|
|
512
|
-
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
513
|
-
if (exits.length === 0)
|
|
514
|
-
return [];
|
|
515
|
-
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
516
|
-
}
|
|
517
|
-
function wantsHelpJson(env = process8.env) {
|
|
518
|
-
return env.KIT_HELP === "json";
|
|
519
|
-
}
|
|
520
|
-
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
521
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
522
|
-
`);
|
|
523
|
-
const first = lines[0];
|
|
524
|
-
const colon = first.indexOf(": ");
|
|
525
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
526
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
527
|
-
return {
|
|
528
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
529
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
530
|
-
...replaces === undefined ? {} : { replaces },
|
|
531
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
532
|
-
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
533
|
-
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
534
|
-
};
|
|
535
|
-
}
|
|
536
|
-
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
537
|
-
if (examples.length === 0 || outputMode() === "agent")
|
|
538
|
-
return [];
|
|
539
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
540
|
-
}
|
|
541
|
-
var MAX_INLINE_CHOICES = 24;
|
|
542
|
-
function optionRows(options, colors = paint(process8.stdout)) {
|
|
543
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
544
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
545
|
-
const choices = option.choices?.join("|");
|
|
546
|
-
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
547
|
-
const named = inline ? `<${choices}>` : "<value>";
|
|
548
|
-
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
549
|
-
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
550
|
-
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
551
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
552
|
-
});
|
|
553
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
554
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
// ../kit/src/text.ts
|
|
558
|
-
function distance(a, b) {
|
|
559
|
-
const left = [...a];
|
|
560
|
-
const right = [...b];
|
|
561
|
-
let before = [];
|
|
562
|
-
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
563
|
-
for (const [i, x] of left.entries()) {
|
|
564
|
-
const current = [i + 1];
|
|
565
|
-
for (const [j, y] of right.entries()) {
|
|
566
|
-
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
567
|
-
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
568
|
-
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
569
|
-
current.push(cost);
|
|
570
|
-
}
|
|
571
|
-
before = previous;
|
|
572
|
-
previous = current;
|
|
573
|
-
}
|
|
574
|
-
return previous[right.length] ?? 0;
|
|
575
|
-
}
|
|
576
|
-
function closest(name, names) {
|
|
577
|
-
const started = names.find((known) => known.startsWith(name));
|
|
578
|
-
if (started !== undefined)
|
|
579
|
-
return started;
|
|
580
|
-
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
581
|
-
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
582
|
-
}
|
|
583
|
-
// ../kit/src/input.ts
|
|
584
|
-
import { fstatSync } from "fs";
|
|
585
|
-
var WHOLE = /^\d+$/;
|
|
586
|
-
function wholeNumber(value, name, fallback, min = 1) {
|
|
587
|
-
if (value === undefined)
|
|
588
|
-
return fallback;
|
|
589
|
-
const number = Number(value);
|
|
590
|
-
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
591
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
592
|
-
return number;
|
|
593
|
-
}
|
|
594
|
-
var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
|
|
595
|
-
var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
|
|
596
|
-
function duration(value, name, fallback, unit = "s") {
|
|
597
|
-
if (value === undefined)
|
|
598
|
-
return fallback;
|
|
599
|
-
const match = DURATION.exec(value.trim());
|
|
600
|
-
const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
|
|
601
|
-
if (ms < 1)
|
|
602
|
-
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
603
|
-
return ms;
|
|
604
|
-
}
|
|
605
|
-
function isStdinPiped() {
|
|
606
|
-
const stat = fstatSync(0);
|
|
607
|
-
return stat.isFIFO() || stat.isFile();
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
// ../kit/src/args.ts
|
|
611
|
-
var DASHES = /^-+/;
|
|
612
|
-
function jsonOption(holds) {
|
|
613
|
-
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
614
|
-
}
|
|
615
|
-
class Exit extends Error {
|
|
616
|
-
code;
|
|
617
|
-
hint;
|
|
618
|
-
constructor(message, code, hint) {
|
|
619
|
-
super(message);
|
|
620
|
-
this.code = code;
|
|
621
|
-
this.hint = hint;
|
|
622
|
-
}
|
|
623
|
-
}
|
|
624
|
-
function fail(message, code = 2, hint) {
|
|
625
|
-
throw new Exit(message, code, hint);
|
|
626
|
-
}
|
|
627
|
-
|
|
628
|
-
class UsageError extends Exit {
|
|
629
|
-
constructor(message, hint) {
|
|
630
|
-
super(message, 2, hint);
|
|
631
|
-
}
|
|
632
|
-
}
|
|
633
|
-
function badUsage(message) {
|
|
634
|
-
throw new UsageError(message);
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
class HelpShown extends Exit {
|
|
638
|
-
constructor() {
|
|
639
|
-
super("help shown", 0);
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
class Completing {
|
|
644
|
-
options;
|
|
645
|
-
positionals;
|
|
646
|
-
candidates;
|
|
647
|
-
constructor(options, positionals = [], candidates = {}) {
|
|
648
|
-
this.options = options;
|
|
649
|
-
this.positionals = positionals;
|
|
650
|
-
this.candidates = candidates;
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
var completion = { active: false };
|
|
654
|
-
var OUTPUT_OPTIONS = {
|
|
655
|
-
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
656
|
-
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
657
|
-
};
|
|
658
|
-
function applyOutput(color, plain, env = process9.env) {
|
|
659
|
-
const when = plain === true ? "never" : color ?? "auto";
|
|
660
|
-
if (when === "auto")
|
|
661
|
-
return;
|
|
662
|
-
if (when !== "always" && when !== "never")
|
|
663
|
-
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
664
|
-
if (when === "always") {
|
|
665
|
-
env.FORCE_COLOR = "1";
|
|
666
|
-
delete env.NO_COLOR;
|
|
667
|
-
} else {
|
|
668
|
-
env.NO_COLOR = "1";
|
|
669
|
-
delete env.FORCE_COLOR;
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
function parse(args, usage, options, settings = {}) {
|
|
673
|
-
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
674
|
-
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
675
|
-
const listing = listed(all, settings.allowNegative === true);
|
|
676
|
-
if (completion.active)
|
|
677
|
-
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
678
|
-
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
679
|
-
let parsed;
|
|
680
|
-
try {
|
|
681
|
-
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
682
|
-
} catch (error) {
|
|
683
|
-
const message = parseError(error);
|
|
684
|
-
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
685
|
-
}
|
|
686
|
-
const values = parsed.values;
|
|
687
|
-
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
688
|
-
if (values.help === true) {
|
|
689
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
690
|
-
throw new HelpShown;
|
|
691
|
-
}
|
|
692
|
-
checkChoices(parsed.values, all);
|
|
693
|
-
checkConflicts(parsed.values, all);
|
|
694
|
-
if (settings.positionals !== undefined)
|
|
695
|
-
checkPositionals(parsed.positionals, settings.positionals);
|
|
696
|
-
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
697
|
-
}
|
|
698
|
-
function splitRest(args, passes) {
|
|
699
|
-
const separator = passes ? args.indexOf("--") : -1;
|
|
700
|
-
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
701
|
-
}
|
|
702
|
-
function splitTrailing(args, options, count) {
|
|
703
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
704
|
-
let seen = 0;
|
|
705
|
-
if (count === 0)
|
|
706
|
-
return { own: args, rest: undefined };
|
|
707
|
-
for (let at = 0;at < args.length; at++) {
|
|
708
|
-
const word = args[at];
|
|
709
|
-
if (word === "--")
|
|
710
|
-
break;
|
|
711
|
-
if (word.startsWith("-")) {
|
|
712
|
-
if (takesValue(word))
|
|
713
|
-
at++;
|
|
714
|
-
continue;
|
|
715
|
-
}
|
|
716
|
-
seen++;
|
|
717
|
-
if (seen === count)
|
|
718
|
-
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
719
|
-
}
|
|
720
|
-
return { own: args, rest: undefined };
|
|
721
|
-
}
|
|
722
|
-
function listed(options, allowNegative) {
|
|
723
|
-
if (!allowNegative)
|
|
724
|
-
return options;
|
|
725
|
-
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
726
|
-
if (option.type !== "boolean" || option.negative === undefined)
|
|
727
|
-
return [[name, option]];
|
|
728
|
-
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
729
|
-
}));
|
|
730
|
-
}
|
|
731
|
-
function withAliases(args, options) {
|
|
732
|
-
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
733
|
-
if (named.size === 0)
|
|
734
|
-
return args;
|
|
735
|
-
const separator = args.indexOf("--");
|
|
736
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
737
|
-
return [...own.map((arg) => {
|
|
738
|
-
const at = arg.indexOf("=");
|
|
739
|
-
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
740
|
-
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
741
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
742
|
-
}
|
|
743
|
-
function withBare(args, options) {
|
|
744
|
-
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
745
|
-
if (bare.size === 0)
|
|
746
|
-
return args;
|
|
747
|
-
const separator = args.indexOf("--");
|
|
748
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
749
|
-
return [...own.flatMap((arg, index) => {
|
|
750
|
-
const optional = bare.get(arg);
|
|
751
|
-
const next = own[index + 1];
|
|
752
|
-
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
753
|
-
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
754
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
755
|
-
}
|
|
756
|
-
function checkConflicts(values, options) {
|
|
757
|
-
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
758
|
-
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
759
|
-
const other = given(name) ? conflicts.find(given) : undefined;
|
|
760
|
-
if (other !== undefined)
|
|
761
|
-
badUsage(`--${name} cannot be used with --${other}`);
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
function checkChoices(values, options) {
|
|
765
|
-
for (const [name, option] of Object.entries(options)) {
|
|
766
|
-
if (option.choices === undefined)
|
|
767
|
-
continue;
|
|
768
|
-
const given = values[name];
|
|
769
|
-
for (const value of Array.isArray(given) ? given : [given]) {
|
|
770
|
-
if (typeof value === "string")
|
|
771
|
-
oneOf(value, name, option.choices);
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
function oneOf(value, name, choices) {
|
|
776
|
-
if (!choices.includes(value))
|
|
777
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
778
|
-
return value;
|
|
779
|
-
}
|
|
780
|
-
function checkPositionals(given, names) {
|
|
781
|
-
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
782
|
-
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
783
|
-
if (given.length < required)
|
|
784
|
-
badUsage(`missing ${names[given.length]}`);
|
|
785
|
-
if (!variadic && given.length > names.length)
|
|
786
|
-
badUsage(`unexpected argument ${given[names.length]}`);
|
|
787
|
-
}
|
|
788
|
-
function joinDashValues(args, options) {
|
|
789
|
-
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
790
|
-
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
791
|
-
const joined = [];
|
|
792
|
-
for (let i = 0;i < args.length; i++) {
|
|
793
|
-
const arg = args[i] ?? "";
|
|
794
|
-
if (arg === "--")
|
|
795
|
-
return [...joined, ...args.slice(i)];
|
|
796
|
-
const name = longOf.get(arg);
|
|
797
|
-
const next = args[i + 1];
|
|
798
|
-
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
799
|
-
joined.push(`--${name}=${next}`);
|
|
800
|
-
i++;
|
|
801
|
-
} else {
|
|
802
|
-
joined.push(arg);
|
|
803
|
-
}
|
|
804
|
-
}
|
|
805
|
-
return joined;
|
|
806
|
-
}
|
|
807
|
-
function parseError(error) {
|
|
808
|
-
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
809
|
-
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
810
|
-
}
|
|
811
|
-
var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
812
|
-
function nearestOption(message, options, allowNegative) {
|
|
813
|
-
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
814
|
-
if (typed === undefined)
|
|
815
|
-
return;
|
|
816
|
-
const word = typed.replace(DASHES, "");
|
|
817
|
-
if (word.length < 2 && !typed.startsWith("--"))
|
|
818
|
-
return;
|
|
819
|
-
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
820
|
-
...option.short === undefined ? [] : [`-${option.short}`],
|
|
821
|
-
`--${name}`,
|
|
822
|
-
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
823
|
-
]);
|
|
824
|
-
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
825
|
-
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
826
|
-
}
|
|
827
|
-
// ../kit/src/argv.ts
|
|
828
|
-
import { readFileSync as readFileSync3, realpathSync } from "fs";
|
|
829
|
-
import { resolve as resolve4 } from "path";
|
|
830
|
-
import process10 from "process";
|
|
831
|
-
function commandLine() {
|
|
832
|
-
try {
|
|
833
|
-
return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
834
|
-
} catch {
|
|
835
|
-
return;
|
|
836
|
-
}
|
|
837
|
-
}
|
|
838
|
-
function realPath(word) {
|
|
839
|
-
try {
|
|
840
|
-
return realpathSync(resolve4(word));
|
|
841
|
-
} catch {
|
|
842
|
-
return;
|
|
843
|
-
}
|
|
844
|
-
}
|
|
845
|
-
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
846
|
-
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
847
|
-
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve4(word) === script || realPath(word) === target));
|
|
848
|
-
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
849
|
-
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
850
|
-
}
|
|
851
|
-
// ../kit/src/process.ts
|
|
852
|
-
import { constants } from "os";
|
|
853
|
-
import process11 from "process";
|
|
854
|
-
var KILL_GRACE_MS = 2000;
|
|
855
|
-
function exitCodeOf(code, signal) {
|
|
856
|
-
if (code !== null)
|
|
857
|
-
return code;
|
|
858
|
-
if (typeof signal === "number")
|
|
859
|
-
return 128 + signal;
|
|
860
|
-
return signal === null ? 129 : 128 + constants.signals[signal];
|
|
861
|
-
}
|
|
862
|
-
async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
863
|
-
const chunks = [];
|
|
864
|
-
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
|
|
865
|
-
const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
|
|
866
|
-
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
|
|
867
|
-
const timers = [];
|
|
868
|
-
const killGroup = (killing) => {
|
|
869
|
-
if (state.done)
|
|
870
|
-
return;
|
|
871
|
-
try {
|
|
872
|
-
if (grouped)
|
|
873
|
-
process11.kill(-proc.pid, killing);
|
|
874
|
-
else
|
|
875
|
-
proc.kill(killing);
|
|
876
|
-
} catch {}
|
|
877
|
-
};
|
|
878
|
-
const stop = () => {
|
|
879
|
-
killGroup("SIGTERM");
|
|
880
|
-
timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
|
|
881
|
-
};
|
|
882
|
-
const onAbort = () => stop();
|
|
883
|
-
if (timeoutMs !== undefined) {
|
|
884
|
-
timers.push(setTimeout(() => {
|
|
885
|
-
state.timedOut = true;
|
|
886
|
-
stop();
|
|
887
|
-
}, timeoutMs));
|
|
888
|
-
}
|
|
889
|
-
if (signal?.aborted === true)
|
|
890
|
-
onAbort();
|
|
891
|
-
else
|
|
892
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
893
|
-
onStart?.({ kill: (killing) => killGroup(killing) });
|
|
894
|
-
const drain = async (stream, name) => {
|
|
895
|
-
for await (const data of stream) {
|
|
896
|
-
if (state.failure !== undefined)
|
|
897
|
-
continue;
|
|
898
|
-
try {
|
|
899
|
-
onChunk?.({ stream: name, data });
|
|
900
|
-
} catch (error) {
|
|
901
|
-
state.failure = error;
|
|
902
|
-
stop();
|
|
903
|
-
continue;
|
|
904
|
-
}
|
|
905
|
-
if (state.kept + data.length > maxBytes) {
|
|
906
|
-
state.truncated = true;
|
|
907
|
-
continue;
|
|
908
|
-
}
|
|
909
|
-
state.kept += data.length;
|
|
910
|
-
chunks.push({ stream: name, data });
|
|
911
|
-
}
|
|
912
|
-
};
|
|
913
|
-
try {
|
|
914
|
-
await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
|
|
915
|
-
await proc.exited;
|
|
916
|
-
} finally {
|
|
917
|
-
state.done = true;
|
|
918
|
-
for (const timer of timers)
|
|
919
|
-
clearTimeout(timer);
|
|
920
|
-
signal?.removeEventListener("abort", onAbort);
|
|
921
|
-
}
|
|
922
|
-
if (state.failure !== undefined)
|
|
923
|
-
throw state.failure;
|
|
924
|
-
const joined = () => Buffer.concat(chunks.map(({ data }) => data));
|
|
925
|
-
let output;
|
|
926
|
-
let text;
|
|
927
|
-
return {
|
|
928
|
-
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
929
|
-
chunks,
|
|
930
|
-
timedOut: state.timedOut,
|
|
931
|
-
truncated: state.truncated,
|
|
932
|
-
get output() {
|
|
933
|
-
return output ??= joined();
|
|
934
|
-
},
|
|
935
|
-
get text() {
|
|
936
|
-
return text ??= (output ??= joined()).toString();
|
|
937
|
-
}
|
|
938
|
-
};
|
|
939
|
-
}
|
|
940
|
-
|
|
941
|
-
// ../kit/src/progress.ts
|
|
942
|
-
var ESC = String.fromCharCode(27);
|
|
943
|
-
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
944
|
-
var RESET_STYLE = `${ESC}[0m`;
|
|
945
|
-
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
946
|
-
// ../kit/src/cli.ts
|
|
947
|
-
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
948
|
-
import { dirname as dirname3, join as join5 } from "path";
|
|
949
|
-
import process14 from "process";
|
|
950
|
-
|
|
951
|
-
// ../kit/src/notify.ts
|
|
952
|
-
import process12 from "process";
|
|
953
|
-
var NOTIFY_AFTER_MS = 1e4;
|
|
954
|
-
var CANCELLED = 130;
|
|
955
|
-
function base64(text) {
|
|
956
|
-
return Buffer.from(text).toString("base64");
|
|
957
|
-
}
|
|
958
|
-
function notification(title, body, env = process12.env) {
|
|
959
|
-
const id = `kit${process12.pid}`;
|
|
960
|
-
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\\`];
|
|
961
|
-
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
962
|
-
}
|
|
963
|
-
function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
|
|
964
|
-
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
965
|
-
return;
|
|
966
|
-
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
967
|
-
}
|
|
968
|
-
|
|
969
|
-
// ../kit/src/usage.ts
|
|
970
|
-
import { appendFileSync, mkdirSync } from "fs";
|
|
971
|
-
import { homedir as homedir3 } from "os";
|
|
972
|
-
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
973
|
-
import process13 from "process";
|
|
974
|
-
|
|
975
|
-
// ../kit/src/logs.ts
|
|
976
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
977
|
-
var CLI_FOLDER = "kaynooo-cli";
|
|
978
|
-
|
|
979
|
-
// ../kit/src/usage.ts
|
|
980
|
-
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
981
|
-
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
982
|
-
var LONGEST_NAME = 40;
|
|
983
|
-
var usageError;
|
|
984
|
-
function noteUsageError(message) {
|
|
985
|
-
usageError = message;
|
|
986
|
-
}
|
|
987
|
-
function stateHome(env = process13.env) {
|
|
988
|
-
const dir = env.XDG_STATE_HOME;
|
|
989
|
-
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
990
|
-
}
|
|
991
|
-
function usagePath(env = process13.env) {
|
|
992
|
-
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
993
|
-
}
|
|
994
|
-
function usageRecorded(env = process13.env) {
|
|
995
|
-
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
996
|
-
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
997
|
-
}
|
|
998
|
-
function flagNames(argv) {
|
|
999
|
-
const end = argv.indexOf("--");
|
|
1000
|
-
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1001
|
-
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1002
|
-
}
|
|
1003
|
-
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
1004
|
-
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1005
|
-
usageError = undefined;
|
|
1006
|
-
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
1007
|
-
}
|
|
1008
|
-
function recordUsage(entry, env = process13.env) {
|
|
1009
|
-
if (!usageRecorded(env))
|
|
1010
|
-
return;
|
|
1011
|
-
try {
|
|
1012
|
-
const path = usagePath(env);
|
|
1013
|
-
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1014
|
-
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1015
|
-
`, { mode: 384 });
|
|
1016
|
-
} catch {}
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
// ../kit/src/cli.ts
|
|
1020
|
-
var LEVEL_OPTIONS = {
|
|
1021
|
-
...OUTPUT_OPTIONS,
|
|
1022
|
-
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1023
|
-
};
|
|
1024
|
-
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
1025
|
-
async function commandRows(all, colors) {
|
|
1026
|
-
const commands = shown(all);
|
|
1027
|
-
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
1028
|
-
const groups = new Map([["Commands:", []]]);
|
|
1029
|
-
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
1030
|
-
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
1031
|
-
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
1032
|
-
const rows = groups.get(heading) ?? [];
|
|
1033
|
-
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
1034
|
-
groups.set(heading, rows);
|
|
1035
|
-
}
|
|
1036
|
-
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
1037
|
-
}
|
|
1038
|
-
function shown(commands) {
|
|
1039
|
-
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
1040
|
-
}
|
|
1041
|
-
function takeOutputFlags(argv) {
|
|
1042
|
-
let index = 0;
|
|
1043
|
-
for (;index < argv.length; index++) {
|
|
1044
|
-
const word = argv[index];
|
|
1045
|
-
if (word === "--plain")
|
|
1046
|
-
applyOutput(undefined, true);
|
|
1047
|
-
else if (word.startsWith("--color="))
|
|
1048
|
-
applyOutput(word.slice("--color=".length), undefined);
|
|
1049
|
-
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
1050
|
-
applyOutput(argv[++index], undefined);
|
|
1051
|
-
else
|
|
1052
|
-
break;
|
|
1053
|
-
}
|
|
1054
|
-
return argv.slice(index);
|
|
1055
|
-
}
|
|
1056
|
-
async function resolveSummary(summary) {
|
|
1057
|
-
return typeof summary === "string" ? summary : summary();
|
|
1058
|
-
}
|
|
1059
|
-
function scopeOf(commands, extra, aliases) {
|
|
1060
|
-
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
1061
|
-
}
|
|
1062
|
-
async function expand(scope, words) {
|
|
1063
|
-
if (scope.lazy.length === 0)
|
|
1064
|
-
return scope;
|
|
1065
|
-
const commands = { ...scope.commands };
|
|
1066
|
-
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
1067
|
-
for (const [name, command] of Object.entries(added))
|
|
1068
|
-
commands[name] ??= command;
|
|
1069
|
-
}
|
|
1070
|
-
return { ...scope, commands, lazy: [] };
|
|
1071
|
-
}
|
|
1072
|
-
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
1073
|
-
const colors = paint(stream);
|
|
1074
|
-
const prefix = path.join(" ");
|
|
1075
|
-
const summary = await resolveSummary(lazySummary);
|
|
1076
|
-
if (wantsHelpJson())
|
|
1077
|
-
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
1078
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1079
|
-
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
1080
|
-
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
1081
|
-
return [
|
|
1082
|
-
header(colors, summary),
|
|
1083
|
-
"",
|
|
1084
|
-
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
1085
|
-
"",
|
|
1086
|
-
...await commandRows(commands, colors),
|
|
1087
|
-
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
1088
|
-
"",
|
|
1089
|
-
colors.bold("Options:"),
|
|
1090
|
-
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
1091
|
-
...exampleRows(examples ?? [], colors),
|
|
1092
|
-
"",
|
|
1093
|
-
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
1094
|
-
].join(`
|
|
1095
|
-
`);
|
|
1096
|
-
}
|
|
1097
|
-
function printError(prefix, message, hint, cause) {
|
|
1098
|
-
const colors = paint(process14.stderr);
|
|
1099
|
-
const styled = takesControlCodes(process14.stderr);
|
|
1100
|
-
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1101
|
-
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1102
|
-
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1103
|
-
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1104
|
-
}
|
|
1105
|
-
function printJsonError(message, hint, cause) {
|
|
1106
|
-
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1107
|
-
}
|
|
1108
|
-
function wantsJson(argv) {
|
|
1109
|
-
const end = argv.indexOf("--");
|
|
1110
|
-
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1111
|
-
}
|
|
1112
|
-
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1113
|
-
if (error instanceof HelpShown)
|
|
1114
|
-
return 0;
|
|
1115
|
-
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1116
|
-
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1117
|
-
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1118
|
-
if (error instanceof Exit && error.code === 2)
|
|
1119
|
-
noteUsageError(error.message);
|
|
1120
|
-
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1121
|
-
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1122
|
-
return error instanceof Exit ? error.code : 1;
|
|
1123
|
-
}
|
|
1124
|
-
async function dispatch(level, typed, { version, redact }) {
|
|
1125
|
-
const prefix = level.path.join(" ");
|
|
1126
|
-
let argv;
|
|
1127
|
-
try {
|
|
1128
|
-
argv = takeOutputFlags(typed);
|
|
1129
|
-
} catch (error) {
|
|
1130
|
-
return reportThrown(prefix, error);
|
|
1131
|
-
}
|
|
1132
|
-
const [name, ...args] = argv;
|
|
1133
|
-
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
1134
|
-
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
1135
|
-
try {
|
|
1136
|
-
return await fallback.run([]);
|
|
1137
|
-
} catch (error) {
|
|
1138
|
-
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
1139
|
-
}
|
|
1140
|
-
}
|
|
1141
|
-
if (name === undefined && level.path.length > 1) {
|
|
1142
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
|
|
1143
|
-
return 2;
|
|
1144
|
-
}
|
|
1145
|
-
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1146
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
|
|
1147
|
-
return 0;
|
|
1148
|
-
}
|
|
1149
|
-
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1150
|
-
console.log(version);
|
|
1151
|
-
return 0;
|
|
1152
|
-
}
|
|
1153
|
-
let command = level.commands[level.aliases?.[name] ?? name];
|
|
1154
|
-
let rest = args;
|
|
1155
|
-
let ran = name;
|
|
1156
|
-
if (command === undefined && level.lazy.length > 0) {
|
|
1157
|
-
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
1158
|
-
command = level.commands[level.aliases?.[name] ?? name];
|
|
1159
|
-
}
|
|
1160
|
-
if (command === undefined && level.defaultCommand !== undefined) {
|
|
1161
|
-
command = level.commands[level.defaultCommand];
|
|
1162
|
-
rest = argv;
|
|
1163
|
-
ran = level.defaultCommand;
|
|
1164
|
-
}
|
|
1165
|
-
if (command === undefined) {
|
|
1166
|
-
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
1167
|
-
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
1168
|
-
return 2;
|
|
1169
|
-
}
|
|
1170
|
-
if ("commands" in command) {
|
|
1171
|
-
const { summary } = command;
|
|
1172
|
-
return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
|
|
1173
|
-
}
|
|
1174
|
-
try {
|
|
1175
|
-
return await command.run(rest);
|
|
1176
|
-
} catch (error) {
|
|
1177
|
-
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
1178
|
-
}
|
|
1179
|
-
}
|
|
1180
|
-
var COMPLETE = "__complete";
|
|
1181
|
-
var FILES = "__files__";
|
|
1182
|
-
async function completingOf(run) {
|
|
1183
|
-
completion.active = true;
|
|
1184
|
-
try {
|
|
1185
|
-
await run([]);
|
|
1186
|
-
} catch (error) {
|
|
1187
|
-
if (error instanceof Completing)
|
|
1188
|
-
return error;
|
|
1189
|
-
} finally {
|
|
1190
|
-
completion.active = false;
|
|
1191
|
-
}
|
|
1192
|
-
return new Completing({});
|
|
1193
|
-
}
|
|
1194
|
-
async function optionsOf(run) {
|
|
1195
|
-
return (await completingOf(run)).options;
|
|
1196
|
-
}
|
|
1197
|
-
function candidateLine(candidate) {
|
|
1198
|
-
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1199
|
-
}
|
|
1200
|
-
function positionalBeingTyped(before, { options, positionals }) {
|
|
1201
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1202
|
-
const typed = [];
|
|
1203
|
-
let at = 0;
|
|
1204
|
-
while (at < before.length) {
|
|
1205
|
-
const word = before[at];
|
|
1206
|
-
if (word === "--") {
|
|
1207
|
-
typed.push(...before.slice(at + 1));
|
|
1208
|
-
break;
|
|
1209
|
-
}
|
|
1210
|
-
if (!word.startsWith("-"))
|
|
1211
|
-
typed.push(word);
|
|
1212
|
-
else if (takesValue(word))
|
|
1213
|
-
at++;
|
|
1214
|
-
at++;
|
|
1215
|
-
}
|
|
1216
|
-
const last = positionals.at(-1);
|
|
1217
|
-
if (typed.length < positionals.length)
|
|
1218
|
-
return { name: positionals[typed.length], typed };
|
|
1219
|
-
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1220
|
-
}
|
|
1221
|
-
async function leafCandidates(run, words) {
|
|
1222
|
-
const completing = await completingOf(run);
|
|
1223
|
-
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1224
|
-
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1225
|
-
const flag = words.at(-2);
|
|
1226
|
-
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1227
|
-
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1228
|
-
if (option?.type === "string") {
|
|
1229
|
-
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1230
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1231
|
-
}
|
|
1232
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1233
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1234
|
-
}
|
|
1235
|
-
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1236
|
-
const [word = "", ...rest] = words;
|
|
1237
|
-
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1238
|
-
let { commands, aliases } = scope;
|
|
1239
|
-
let command = commands[aliases?.[word] ?? word];
|
|
1240
|
-
if (listing || command === undefined) {
|
|
1241
|
-
({ commands, aliases } = await expand(scope, [...before, ...words]));
|
|
1242
|
-
command = commands[aliases?.[word] ?? word];
|
|
1243
|
-
}
|
|
1244
|
-
if (listing) {
|
|
1245
|
-
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1246
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1247
|
-
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1248
|
-
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1249
|
-
return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
|
|
1250
|
-
}
|
|
1251
|
-
if (command === undefined) {
|
|
1252
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1253
|
-
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
1254
|
-
}
|
|
1255
|
-
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1256
|
-
}
|
|
1257
|
-
async function printCandidates(found) {
|
|
1258
|
-
for (const line of await found)
|
|
1259
|
-
console.log(line);
|
|
1260
|
-
return 0;
|
|
1261
|
-
}
|
|
1262
|
-
function packageVersion(entry = Bun.main) {
|
|
1263
|
-
let resolved = entry;
|
|
1264
|
-
try {
|
|
1265
|
-
resolved = realpathSync2(entry);
|
|
1266
|
-
} catch {}
|
|
1267
|
-
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1268
|
-
try {
|
|
1269
|
-
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
1270
|
-
if (typeof version === "string")
|
|
1271
|
-
return version;
|
|
1272
|
-
} catch {}
|
|
1273
|
-
if (dirname3(dir) === dir)
|
|
1274
|
-
return "0.0.0";
|
|
1275
|
-
}
|
|
1276
|
-
}
|
|
1277
|
-
async function runCli(cli, argv = scriptArgs()) {
|
|
1278
|
-
const version = cli.version ?? packageVersion();
|
|
1279
|
-
if (argv[0] === COMPLETE)
|
|
1280
|
-
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1281
|
-
const started = performance.now();
|
|
1282
|
-
const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
|
|
1283
|
-
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1284
|
-
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1285
|
-
if (cli.usage !== false) {
|
|
1286
|
-
try {
|
|
1287
|
-
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1288
|
-
} catch {}
|
|
1289
|
-
}
|
|
1290
|
-
return code;
|
|
1291
|
-
}
|
|
1292
|
-
function commandPath(scope, argv) {
|
|
1293
|
-
const path = [];
|
|
1294
|
-
let level = scope;
|
|
1295
|
-
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1296
|
-
const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
|
|
1297
|
-
const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
|
|
1298
|
-
if (command === undefined)
|
|
1299
|
-
break;
|
|
1300
|
-
path.push(word);
|
|
1301
|
-
if (!("commands" in command))
|
|
1302
|
-
break;
|
|
1303
|
-
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
1304
|
-
}
|
|
1305
|
-
return path.length === 0 ? undefined : path.join(" ");
|
|
1306
|
-
}
|
|
1307
|
-
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1308
|
-
if (argv[0] === COMPLETE)
|
|
1309
|
-
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1310
|
-
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1311
|
-
console.log(version ?? packageVersion());
|
|
1312
|
-
return 0;
|
|
1313
|
-
}
|
|
1314
|
-
let code;
|
|
1315
|
-
const started = performance.now();
|
|
1316
|
-
try {
|
|
1317
|
-
code = await run(argv);
|
|
1318
|
-
} catch (error) {
|
|
1319
|
-
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1320
|
-
}
|
|
1321
|
-
notifyEnd(name, code, performance.now() - started);
|
|
1322
|
-
if (usage !== false) {
|
|
1323
|
-
try {
|
|
1324
|
-
recordUsage(usageEntry(name, undefined, argv, code));
|
|
1325
|
-
} catch {}
|
|
1326
|
-
}
|
|
1327
|
-
return code;
|
|
1328
|
-
}
|
|
1329
|
-
// ../kit/src/folders.ts
|
|
1330
|
-
var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
1331
|
-
function ignoredFolders(extra = [], where = {}) {
|
|
1332
|
-
const configured = readUserConfig("config", where).ignore;
|
|
1333
|
-
const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
|
|
1334
|
-
return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
|
|
1335
|
-
}
|
|
1336
|
-
// ../kit/src/limit.ts
|
|
1337
|
-
function limitOptions(fallback) {
|
|
1338
|
-
return {
|
|
1339
|
-
limit: { type: "string", short: "n", description: `show at most this many rows, the rest counted (${fallback})` },
|
|
1340
|
-
full: { type: "boolean", description: "show every row" }
|
|
1341
|
-
};
|
|
1342
|
-
}
|
|
1343
|
-
function limitOf(values, fallback) {
|
|
1344
|
-
if (values.full === true && values.limit !== undefined)
|
|
1345
|
-
badUsage("--limit and --full exclude each other");
|
|
1346
|
-
if (values.full === true || values.json === true && values.limit === undefined)
|
|
1347
|
-
return Number.POSITIVE_INFINITY;
|
|
1348
|
-
return wholeNumber(values.limit, "limit", fallback);
|
|
1349
|
-
}
|
|
1350
|
-
function moreFooter(more) {
|
|
1351
|
-
return `${more} more, rerun with --full`;
|
|
1352
|
-
}
|
|
1353
|
-
function capped(rows, limit) {
|
|
1354
|
-
const more = rows.length - limit;
|
|
1355
|
-
return more > 0 ? { shown: rows.slice(0, limit), footer: moreFooter(more) } : { shown: [...rows], footer: undefined };
|
|
1356
|
-
}
|
|
1357
|
-
// ../kit/src/secrets.ts
|
|
1358
|
-
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1359
|
-
// ../kit/src/sessions.ts
|
|
1360
|
-
var {Glob } = globalThis.Bun;
|
|
1361
|
-
var SESSION_FILES = new Glob("*.json");
|
|
1362
|
-
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1363
|
-
// src/todo-scan.ts
|
|
1364
|
-
import { join as join7 } from "path";
|
|
1365
|
-
import process16 from "process";
|
|
1366
|
-
|
|
1367
|
-
// src/files.ts
|
|
1368
|
-
import { existsSync as existsSync4, readdirSync, statSync as statSync2 } from "fs";
|
|
1369
|
-
import { join as join6, relative } from "path";
|
|
1370
|
-
var MAX_BYTES = 2000000;
|
|
1371
|
-
var SNIFF_BYTES = 8000;
|
|
1372
|
-
function walk(dir, found, ignored) {
|
|
1373
|
-
let entries;
|
|
1374
|
-
try {
|
|
1375
|
-
entries = readdirSync(dir, { withFileTypes: true });
|
|
1376
|
-
} catch {
|
|
1377
|
-
return found;
|
|
1378
|
-
}
|
|
1379
|
-
for (const entry of entries) {
|
|
1380
|
-
if (entry.name.startsWith(".") || ignored.has(entry.name))
|
|
1381
|
-
continue;
|
|
1382
|
-
if (entry.isDirectory())
|
|
1383
|
-
walk(join6(dir, entry.name), found, ignored);
|
|
1384
|
-
else if (entry.isFile())
|
|
1385
|
-
found.push(join6(dir, entry.name));
|
|
1386
|
-
}
|
|
1387
|
-
return found;
|
|
1388
|
-
}
|
|
1389
|
-
async function listFiles(paths, cwd) {
|
|
1390
|
-
const listed = await runCommand(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...paths], { cwd });
|
|
1391
|
-
if (listed.code === 0)
|
|
1392
|
-
return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync4(join6(cwd, path))).sort();
|
|
1393
|
-
const roots = paths.length === 0 ? [cwd] : paths.map((path) => join6(cwd, path));
|
|
1394
|
-
const ignored = ignoredFolders();
|
|
1395
|
-
return roots.flatMap((root) => statSync2(root, { throwIfNoEntry: false })?.isFile() === true ? [root] : walk(root, [], ignored)).map((path) => relative(cwd, path)).sort();
|
|
1396
|
-
}
|
|
1397
|
-
async function readText(path) {
|
|
1398
|
-
const file = Bun.file(path);
|
|
1399
|
-
try {
|
|
1400
|
-
if (file.size > MAX_BYTES || (await file.slice(0, SNIFF_BYTES).bytes()).includes(0))
|
|
1401
|
-
return;
|
|
1402
|
-
return await file.text();
|
|
1403
|
-
} catch {
|
|
1404
|
-
return;
|
|
1405
|
-
}
|
|
1406
|
-
}
|
|
1407
|
-
|
|
1408
|
-
// src/todo.ts
|
|
1409
|
-
var COMMENT = /(?<![:\w/])\/\/|\/\*|<!--|(?:^|\s)(?:#|--)(?=\s)|^\s*\*(?=\s|$)/;
|
|
1410
|
-
var MARKUP = /\.(?:md|mdx|markdown|html?|xml)$/i;
|
|
1411
|
-
var MARKUP_COMMENT = /<!--/;
|
|
1412
|
-
var CLOSERS = /\s*(?:\*\/|-->)\s*$/;
|
|
1413
|
-
var MARKER = /^(?:@|\[)?(TODO|FIXME|HACK|XXX)\b/;
|
|
1414
|
-
var QUOTES = ["'", '"', "`"];
|
|
1415
|
-
var ESCAPE2 = /\\./g;
|
|
1416
|
-
var AFTER_FIRST_LINE = /\n[\s\S]*/;
|
|
1417
|
-
var REF = /(?<![\w./-])(\w[\w.-]*\/(?!\.+#)[\w.][\w.-]*)#(\d+)\b/g;
|
|
1418
|
-
function isQuoted(line, index) {
|
|
1419
|
-
const before = line.slice(0, index).replaceAll(ESCAPE2, "");
|
|
1420
|
-
return QUOTES.some((quote) => before.split(quote).length % 2 === 0);
|
|
1421
|
-
}
|
|
1422
|
-
var BLAME_HEADER = /^[0-9a-f]{40} \d+ (\d+)/;
|
|
1423
|
-
var DAY_S = 86400;
|
|
1424
|
-
async function commitTimes(path, cwd) {
|
|
1425
|
-
const blamed = await runCommand(["git", "blame", "--porcelain", "--", path], { cwd });
|
|
1426
|
-
const times = new Map;
|
|
1427
|
-
if (blamed.code !== 0)
|
|
1428
|
-
return times;
|
|
1429
|
-
const bySha = new Map;
|
|
1430
|
-
let sha = "";
|
|
1431
|
-
let line = 0;
|
|
1432
|
-
for (const row of stdoutOf(blamed.chunks).split(`
|
|
1433
|
-
`)) {
|
|
1434
|
-
const header = BLAME_HEADER.exec(row);
|
|
1435
|
-
if (header !== null) {
|
|
1436
|
-
sha = row.slice(0, 40);
|
|
1437
|
-
line = Number(header[1]);
|
|
1438
|
-
} else if (row.startsWith("committer-time ")) {
|
|
1439
|
-
bySha.set(sha, Number(row.slice("committer-time ".length)));
|
|
1440
|
-
} else if (row.startsWith("\t")) {
|
|
1441
|
-
times.set(line, bySha.get(sha) ?? 0);
|
|
1442
|
-
}
|
|
1443
|
-
}
|
|
1444
|
-
return times;
|
|
1445
|
-
}
|
|
1446
|
-
async function addAges(marks, cwd, now = Date.now() / 1000) {
|
|
1447
|
-
await Promise.all([...Map.groupBy(marks, (mark) => mark.path)].map(async ([path, ofFile]) => {
|
|
1448
|
-
const times = await commitTimes(path, cwd);
|
|
1449
|
-
for (const mark of ofFile) {
|
|
1450
|
-
const time = times.get(mark.line);
|
|
1451
|
-
if (time !== undefined)
|
|
1452
|
-
mark.age = Math.max(0, Math.floor((now - time) / DAY_S));
|
|
1453
|
-
}
|
|
1454
|
-
}));
|
|
1455
|
-
}
|
|
1456
|
-
function marksIn(text, path) {
|
|
1457
|
-
const marks = [];
|
|
1458
|
-
const comment = MARKUP.test(path) ? MARKUP_COMMENT : COMMENT;
|
|
1459
|
-
for (const [i, line] of text.split(`
|
|
1460
|
-
`).entries()) {
|
|
1461
|
-
const opener = comment.exec(line);
|
|
1462
|
-
if (opener === null || isQuoted(line, opener.index))
|
|
1463
|
-
continue;
|
|
1464
|
-
const body = line.slice(opener.index + opener[0].length).replace(CLOSERS, "").trim();
|
|
1465
|
-
const marker = MARKER.exec(body)?.[1];
|
|
1466
|
-
const refs = [...body.matchAll(REF)].map((found) => ({ repo: found[1] ?? "", number: Number(found[2]) }));
|
|
1467
|
-
if (marker !== undefined || refs.length > 0)
|
|
1468
|
-
marks.push({ path, line: i + 1, kind: marker ?? "ref", text: body, refs });
|
|
1469
|
-
}
|
|
1470
|
-
return marks;
|
|
1471
|
-
}
|
|
1472
|
-
function stdoutOf(chunks) {
|
|
1473
|
-
return Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
|
|
1474
|
-
}
|
|
1475
|
-
function refKey(ref) {
|
|
1476
|
-
return `${ref.repo}#${ref.number}`;
|
|
1477
|
-
}
|
|
1478
|
-
async function lookUpOnGitHub(repo, numbers, cwd) {
|
|
1479
|
-
const states = new Map;
|
|
1480
|
-
for (const ran of await Promise.all(numbers.map(async (number) => ({ number, ran: await runCommand(["gh", "api", `repos/${repo}/issues/${number}`, "--jq", ".state"], { cwd }) })))) {
|
|
1481
|
-
if (ran.ran.code !== 0)
|
|
1482
|
-
return ran.ran.text.trim().replace(AFTER_FIRST_LINE, "");
|
|
1483
|
-
states.set(refKey({ repo, number: Number(ran.number) }), stdoutOf(ran.ran.chunks).trim());
|
|
1484
|
-
}
|
|
1485
|
-
return states;
|
|
1486
|
-
}
|
|
1487
|
-
async function lookUp(refs, cwd) {
|
|
1488
|
-
const lookup = { states: new Map, failed: new Map };
|
|
1489
|
-
const byRepo = Map.groupBy(refs, (ref) => ref.repo);
|
|
1490
|
-
for (const [repo, ofRepo] of byRepo) {
|
|
1491
|
-
const numbers = [...new Set(ofRepo.map((ref) => String(ref.number)))];
|
|
1492
|
-
const ran = Bun.which("ft") === null ? undefined : await runCommand(["ft", "issue", ...numbers, "-r", repo, "--json"], { cwd });
|
|
1493
|
-
if (ran === undefined || ran.code !== 0) {
|
|
1494
|
-
const onGitHub = Bun.which("gh") === null ? "gh is not installed" : await lookUpOnGitHub(repo, numbers, cwd);
|
|
1495
|
-
if (typeof onGitHub === "string") {
|
|
1496
|
-
lookup.failed.set(repo, `ft: ${ran === undefined ? "not installed" : ran.text.trim().replace(AFTER_FIRST_LINE, "")}; gh: ${onGitHub}`);
|
|
1497
|
-
} else {
|
|
1498
|
-
for (const [key, state] of onGitHub)
|
|
1499
|
-
lookup.states.set(key, state);
|
|
1500
|
-
}
|
|
1501
|
-
continue;
|
|
1502
|
-
}
|
|
1503
|
-
const parsed = JSON.parse(stdoutOf(ran.chunks));
|
|
1504
|
-
for (const issue of Array.isArray(parsed) ? parsed : [parsed])
|
|
1505
|
-
lookup.states.set(refKey({ repo, number: issue.number }), issue.state);
|
|
1506
|
-
}
|
|
1507
|
-
return lookup;
|
|
1508
|
-
}
|
|
1509
|
-
|
|
1510
|
-
// src/todo-scan.ts
|
|
1511
|
-
var USAGE = `todo-scan [options] [path...]: lists the TODO, FIXME, HACK, XXX and owner/repo#N comments under the paths (here by default), each as <file>:<line>: <comment>, honouring .gitignore
|
|
1512
|
-
|
|
1513
|
-
--older <duration> keeps only the comments whose line last changed longer ago than that (30d, 12w, 6m: git blame dates each one, a file git cannot blame is left out) and shows each one's age.
|
|
1514
|
-
|
|
1515
|
-
--stale keeps only the comments naming a closed issue, each issue's state looked up with ft, or gh for a GitHub repository, and exits 1 when it finds one.
|
|
1516
|
-
|
|
1517
|
-
Lists at most 100 comments, the count of the rest after them (--limit <n>, --full for all); --json is never cut unless --limit is given.`;
|
|
1518
|
-
var EXITS = [[0, "it listed the comments or found no stale one"], [1, "--stale finds one"], [2, "a usage error or when --stale could not look a repository up (ft and gh both failed)"]];
|
|
1519
|
-
var LIST_LIMIT = 100;
|
|
1520
|
-
var DAY_MS2 = 86400000;
|
|
1521
|
-
var OPTIONS = {
|
|
1522
|
-
stale: { type: "boolean", description: "only the comments naming a closed issue, looked up with ft or gh" },
|
|
1523
|
-
older: { type: "string", description: "only the comments whose line last changed longer ago than this duration, from git blame" },
|
|
1524
|
-
...limitOptions(LIST_LIMIT),
|
|
1525
|
-
json: jsonOption("[{path, line, kind, text, refs: [{repo, number, state?}], age?}], age being the days since the line last changed, given with --older or --json when git can date it")
|
|
1526
|
-
};
|
|
1527
|
-
function printLines(lines, footer) {
|
|
1528
|
-
const all = [...lines, ...footer === undefined ? [] : [footer]];
|
|
1529
|
-
if (all.length > 0)
|
|
1530
|
-
console.log(all.join(`
|
|
1531
|
-
`));
|
|
1532
|
-
}
|
|
1533
|
-
async function todoScan(args) {
|
|
1534
|
-
const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, positionals: ["[path...]"], replaces: "grep -rn TODO, then opening each issue it names", examples: ["todo-scan src", ["todo-scan --stale", "only the comments naming a closed issue"]] });
|
|
1535
|
-
const cwd = process16.cwd();
|
|
1536
|
-
const limit = limitOf(values, LIST_LIMIT);
|
|
1537
|
-
const found = [];
|
|
1538
|
-
for (const path of await listFiles(positionals, cwd)) {
|
|
1539
|
-
const text = await readText(join7(cwd, path));
|
|
1540
|
-
if (text !== undefined)
|
|
1541
|
-
found.push(...marksIn(text, path));
|
|
1542
|
-
}
|
|
1543
|
-
const older = values.older === undefined ? undefined : duration(values.older, "older", 0, "m") / DAY_MS2;
|
|
1544
|
-
let marks = found;
|
|
1545
|
-
if (older !== undefined || values.json === true)
|
|
1546
|
-
await addAges(found, cwd);
|
|
1547
|
-
const ageNote = (mark) => older === undefined || mark.age === undefined ? "" : ` [${mark.age}d]`;
|
|
1548
|
-
if (older !== undefined)
|
|
1549
|
-
marks = found.filter((mark) => mark.age !== undefined && mark.age >= older);
|
|
1550
|
-
if (values.stale !== true) {
|
|
1551
|
-
const { shown, footer } = capped(marks, limit);
|
|
1552
|
-
if (values.json === true)
|
|
1553
|
-
printJson(shown);
|
|
1554
|
-
else
|
|
1555
|
-
printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.text}${ageNote(mark)}`), footer);
|
|
1556
|
-
return 0;
|
|
1557
|
-
}
|
|
1558
|
-
const { states, failed } = await lookUp(marks.flatMap((mark) => mark.refs), cwd);
|
|
1559
|
-
for (const [repo, reason] of failed)
|
|
1560
|
-
warn(`could not look ${repo} up`, reason);
|
|
1561
|
-
const stale = marks.filter((mark) => mark.refs.some((ref) => states.get(refKey(ref)) === "closed"));
|
|
1562
|
-
const { shown, footer } = capped(stale, limit);
|
|
1563
|
-
if (values.json === true)
|
|
1564
|
-
printJson(shown.map((mark) => ({ ...mark, refs: mark.refs.map((ref) => ({ ...ref, state: states.get(refKey(ref)) })) })));
|
|
1565
|
-
else
|
|
1566
|
-
printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.refs.filter((ref) => states.get(refKey(ref)) === "closed").map(refKey).join(", ")} closed: ${mark.text}${ageNote(mark)}`), footer);
|
|
1567
|
-
if (stale.length > 0)
|
|
1568
|
-
return 1;
|
|
1569
|
-
return failed.size > 0 ? 2 : 0;
|
|
1570
|
-
}
|
|
1571
|
-
|
|
1572
|
-
// src/todo-scan-cli.ts
|
|
1573
|
-
process17.exitCode = await runMain({ name: "todo-scan", run: todoScan });
|