@kaynooo/cli-guard 0.13.0 → 0.14.4
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 +5 -5
- package/dist/cli.js +1092 -401
- package/package.json +11 -11
package/dist/cli.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
2
|
// @bun
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
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
|
+
};
|
|
12
14
|
|
|
13
15
|
// ../kit/src/mode.ts
|
|
14
16
|
import process2 from "process";
|
|
15
|
-
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
16
|
-
var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
17
17
|
function isSet(value) {
|
|
18
18
|
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
19
19
|
}
|
|
@@ -27,12 +27,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
|
|
|
27
27
|
return "terminal";
|
|
28
28
|
return isSet(env.CI) ? "ci" : "pipe";
|
|
29
29
|
}
|
|
30
|
+
var MODES, AGENT_VARIABLES;
|
|
31
|
+
var init_mode = __esm(() => {
|
|
32
|
+
MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
33
|
+
AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
34
|
+
});
|
|
30
35
|
|
|
31
|
-
//
|
|
32
|
-
import process6 from "process";
|
|
33
|
-
|
|
34
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
35
|
-
var G = /^[a-f0-9]+$/i;
|
|
36
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
36
37
|
function b(r) {
|
|
37
38
|
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
38
39
|
if (!G.test(e))
|
|
@@ -43,11 +44,6 @@ function b(r) {
|
|
|
43
44
|
throw Error(`Invalid hex color length: ${e.length}`);
|
|
44
45
|
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
45
46
|
}
|
|
46
|
-
var 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") => {
|
|
47
|
-
let [l, n, c] = b(r);
|
|
48
|
-
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
49
|
-
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
50
|
-
var h = new Set(["", "1", "2", "3", "true"]);
|
|
51
47
|
function C(r, e = globalThis.process?.env ?? {}) {
|
|
52
48
|
if (e.FORCE_COLOR !== undefined)
|
|
53
49
|
return h.has(e.FORCE_COLOR);
|
|
@@ -84,13 +80,21 @@ function f(r, e = []) {
|
|
|
84
80
|
function Fe(r = {}) {
|
|
85
81
|
return f(r);
|
|
86
82
|
}
|
|
87
|
-
var
|
|
83
|
+
var G, B, h, o;
|
|
84
|
+
var init_chunk_x450vn3m = __esm(() => {
|
|
85
|
+
G = /^[a-f0-9]+$/i;
|
|
86
|
+
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") => {
|
|
87
|
+
let [l, n, c] = b(r);
|
|
88
|
+
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
89
|
+
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
90
|
+
h = new Set(["", "1", "2", "3", "true"]);
|
|
91
|
+
o = Fe();
|
|
92
|
+
});
|
|
88
93
|
|
|
89
|
-
//
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
import process5 from "process";
|
|
94
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
|
|
95
|
+
var init_colors = __esm(() => {
|
|
96
|
+
init_chunk_x450vn3m();
|
|
97
|
+
});
|
|
94
98
|
|
|
95
99
|
// ../kit/src/config.ts
|
|
96
100
|
import { existsSync } from "fs";
|
|
@@ -106,15 +110,21 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
|
106
110
|
return;
|
|
107
111
|
}
|
|
108
112
|
}
|
|
113
|
+
var init_config = __esm(() => {
|
|
114
|
+
init_args();
|
|
115
|
+
});
|
|
109
116
|
|
|
110
117
|
// ../kit/src/user-config.ts
|
|
111
118
|
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
112
119
|
import { homedir } from "os";
|
|
113
|
-
import { join as join2 } from "path";
|
|
120
|
+
import { isAbsolute, join as join2 } from "path";
|
|
114
121
|
import process4 from "process";
|
|
122
|
+
function xdgFolder(value, fallback) {
|
|
123
|
+
return value !== undefined && isAbsolute(value) ? value : fallback;
|
|
124
|
+
}
|
|
115
125
|
function configBase(where = {}) {
|
|
116
126
|
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
117
|
-
return xdg
|
|
127
|
+
return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
|
|
118
128
|
}
|
|
119
129
|
function userConfigPath(bin, where = {}) {
|
|
120
130
|
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
@@ -141,36 +151,18 @@ function configuredNumber(bin, key, fallback, where = {}, legacy = []) {
|
|
|
141
151
|
const value = readUserConfig(bin, where, legacy)[key];
|
|
142
152
|
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
|
|
143
153
|
}
|
|
154
|
+
var init_user_config = () => {};
|
|
144
155
|
|
|
145
156
|
// ../kit/src/theme.ts
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
151
|
-
bins: {},
|
|
152
|
-
gradient: ["#c084fc", "#67e8f9"]
|
|
153
|
-
};
|
|
154
|
-
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" };
|
|
155
|
-
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" };
|
|
156
|
-
var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
157
|
-
var PRESETS = {
|
|
158
|
-
default: {},
|
|
159
|
-
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
160
|
-
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
161
|
-
ascii: { glyphs: ASCII }
|
|
162
|
-
};
|
|
163
|
-
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"]);
|
|
164
|
-
var HEX = /^#[0-9a-f]{6}$/i;
|
|
165
|
-
var CONTROL = /\p{Cc}/u;
|
|
166
|
-
var MAX_FILE_BYTES = 64 * 1024;
|
|
167
|
-
var SPACES = /\s+/;
|
|
157
|
+
import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
|
|
158
|
+
import { homedir as homedir2 } from "os";
|
|
159
|
+
import { join as join3, resolve as resolve2 } from "path";
|
|
160
|
+
import process5 from "process";
|
|
168
161
|
function isColorSpec(spec) {
|
|
169
162
|
if (typeof spec === "number")
|
|
170
163
|
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
171
164
|
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
172
165
|
}
|
|
173
|
-
var CUBE = [0, 95, 135, 175, 215, 255];
|
|
174
166
|
function cubeLevel(channel) {
|
|
175
167
|
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
176
168
|
}
|
|
@@ -275,7 +267,6 @@ function applyFile(theme, file, where, warn) {
|
|
|
275
267
|
function endsWalk(home) {
|
|
276
268
|
return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
|
|
277
269
|
}
|
|
278
|
-
var warned = new Set;
|
|
279
270
|
function warnOnce(message) {
|
|
280
271
|
if (warned.has(message))
|
|
281
272
|
return;
|
|
@@ -312,8 +303,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
|
|
|
312
303
|
}
|
|
313
304
|
return { theme, sources, preset };
|
|
314
305
|
}
|
|
315
|
-
var current;
|
|
316
|
-
var currentKey = "";
|
|
317
306
|
function activeTheme() {
|
|
318
307
|
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
319
308
|
if (current === undefined || key !== currentKey) {
|
|
@@ -322,8 +311,38 @@ function activeTheme() {
|
|
|
322
311
|
}
|
|
323
312
|
return current;
|
|
324
313
|
}
|
|
314
|
+
var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
|
|
315
|
+
var init_theme = __esm(() => {
|
|
316
|
+
init_config();
|
|
317
|
+
init_user_config();
|
|
318
|
+
ENDS = new Map;
|
|
319
|
+
DEFAULT = {
|
|
320
|
+
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" },
|
|
321
|
+
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" },
|
|
322
|
+
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
323
|
+
bins: {},
|
|
324
|
+
gradient: ["#c084fc", "#67e8f9"]
|
|
325
|
+
};
|
|
326
|
+
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" };
|
|
327
|
+
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" };
|
|
328
|
+
ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
329
|
+
PRESETS = {
|
|
330
|
+
default: {},
|
|
331
|
+
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
332
|
+
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
333
|
+
ascii: { glyphs: ASCII }
|
|
334
|
+
};
|
|
335
|
+
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"]);
|
|
336
|
+
HEX = /^#[0-9a-f]{6}$/i;
|
|
337
|
+
CONTROL = /\p{Cc}/u;
|
|
338
|
+
MAX_FILE_BYTES = 64 * 1024;
|
|
339
|
+
SPACES = /\s+/;
|
|
340
|
+
CUBE = [0, 95, 135, 175, 215, 255];
|
|
341
|
+
warned = new Set;
|
|
342
|
+
});
|
|
325
343
|
|
|
326
344
|
// ../kit/src/style.ts
|
|
345
|
+
import process6 from "process";
|
|
327
346
|
function takesControlCodes(stream, env = process6.env) {
|
|
328
347
|
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
329
348
|
}
|
|
@@ -334,17 +353,22 @@ function role(name, stream, env = process6.env) {
|
|
|
334
353
|
const colors = paint(stream, env);
|
|
335
354
|
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
336
355
|
}
|
|
337
|
-
var STATUS_WORDS
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
356
|
+
var STATUS_WORDS, STATUS_OF;
|
|
357
|
+
var init_style = __esm(() => {
|
|
358
|
+
init_colors();
|
|
359
|
+
init_mode();
|
|
360
|
+
init_theme();
|
|
361
|
+
STATUS_WORDS = {
|
|
362
|
+
passed: ["passed", "success", "succeeded", "ok"],
|
|
363
|
+
failed: ["failed", "failure", "error", "errored"],
|
|
364
|
+
running: ["running", "in_progress", "started", "holding"],
|
|
365
|
+
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
366
|
+
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
367
|
+
};
|
|
368
|
+
STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
369
|
+
});
|
|
345
370
|
|
|
346
371
|
// ../kit/src/format.ts
|
|
347
|
-
var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
348
372
|
function formatSeconds(total) {
|
|
349
373
|
let rest = Math.max(0, Math.round(total));
|
|
350
374
|
const amounts = UNITS.map(([unit, size]) => {
|
|
@@ -365,15 +389,38 @@ function upTo(text, separator) {
|
|
|
365
389
|
const end = text.indexOf(separator);
|
|
366
390
|
return end === -1 ? text : text.slice(0, end);
|
|
367
391
|
}
|
|
368
|
-
var ESCAPE
|
|
392
|
+
var UNITS, ESCAPE;
|
|
393
|
+
var init_format = __esm(() => {
|
|
394
|
+
init_mode();
|
|
395
|
+
init_style();
|
|
396
|
+
UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
397
|
+
ESCAPE = String.fromCharCode(27);
|
|
398
|
+
});
|
|
369
399
|
|
|
370
400
|
// ../kit/src/help.ts
|
|
371
401
|
import process7 from "process";
|
|
372
|
-
var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
373
|
-
var USAGE_PREFIX = /^usage:\s*/i;
|
|
374
|
-
var FULL_STOP = /\.$/;
|
|
375
402
|
function usageLine(usage, colors = paint(process7.stdout)) {
|
|
376
|
-
|
|
403
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
404
|
+
`);
|
|
405
|
+
const blank = lines.indexOf("");
|
|
406
|
+
const synopses = blank === -1 ? lines : lines.slice(0, blank);
|
|
407
|
+
const details = blank === -1 ? [] : lines.slice(blank + 1);
|
|
408
|
+
const colon = synopses[0].indexOf(": ");
|
|
409
|
+
const inline = synopses[0].slice(colon + 2);
|
|
410
|
+
const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
|
|
411
|
+
if (colon !== -1)
|
|
412
|
+
synopses[0] = synopses[0].slice(0, colon);
|
|
413
|
+
const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
|
|
414
|
+
`)}`;
|
|
415
|
+
const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
|
|
416
|
+
const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
|
|
417
|
+
return [head, ...lead, ...rest].join(`
|
|
418
|
+
`);
|
|
419
|
+
}
|
|
420
|
+
function prose(line, colors) {
|
|
421
|
+
if (colors.cyan("x") === "x")
|
|
422
|
+
return line;
|
|
423
|
+
return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
|
|
377
424
|
}
|
|
378
425
|
function helpText(usage, options, colors = paint(process7.stdout), { examples = [], exits = [] } = {}) {
|
|
379
426
|
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
@@ -408,7 +455,6 @@ function exampleRows(examples, colors = paint(process7.stdout)) {
|
|
|
408
455
|
return [];
|
|
409
456
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
410
457
|
}
|
|
411
|
-
var MAX_INLINE_CHOICES = 24;
|
|
412
458
|
function optionRows(options, colors = paint(process7.stdout)) {
|
|
413
459
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
414
460
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
@@ -423,6 +469,15 @@ function optionRows(options, colors = paint(process7.stdout)) {
|
|
|
423
469
|
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
424
470
|
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
425
471
|
}
|
|
472
|
+
var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
|
|
473
|
+
var init_help = __esm(() => {
|
|
474
|
+
init_mode();
|
|
475
|
+
init_style();
|
|
476
|
+
OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
477
|
+
USAGE_PREFIX = /^usage:\s*/i;
|
|
478
|
+
FULL_STOP = /\.$/;
|
|
479
|
+
PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
|
|
480
|
+
});
|
|
426
481
|
|
|
427
482
|
// ../kit/src/text.ts
|
|
428
483
|
function distance(a, b) {
|
|
@@ -450,6 +505,8 @@ function closest(name, names) {
|
|
|
450
505
|
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
451
506
|
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
452
507
|
}
|
|
508
|
+
var init_text = () => {};
|
|
509
|
+
|
|
453
510
|
// ../kit/src/input.ts
|
|
454
511
|
import process8 from "process";
|
|
455
512
|
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
@@ -463,40 +520,23 @@ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
|
463
520
|
fail(`no file ${path}`);
|
|
464
521
|
return file.text();
|
|
465
522
|
}
|
|
523
|
+
var init_input = __esm(() => {
|
|
524
|
+
init_args();
|
|
525
|
+
});
|
|
466
526
|
|
|
467
527
|
// ../kit/src/args.ts
|
|
468
|
-
|
|
528
|
+
import process9 from "process";
|
|
529
|
+
import { parseArgs } from "util";
|
|
469
530
|
function jsonOption(holds) {
|
|
470
531
|
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
471
532
|
}
|
|
472
|
-
class Exit extends Error {
|
|
473
|
-
code;
|
|
474
|
-
hint;
|
|
475
|
-
constructor(message, code, hint) {
|
|
476
|
-
super(message);
|
|
477
|
-
this.code = code;
|
|
478
|
-
this.hint = hint;
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
533
|
function fail(message, code = 2, hint) {
|
|
482
534
|
throw new Exit(message, code, hint);
|
|
483
535
|
}
|
|
484
|
-
|
|
485
|
-
class UsageError extends Exit {
|
|
486
|
-
constructor(message, hint) {
|
|
487
|
-
super(message, 2, hint);
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
536
|
function badUsage(message) {
|
|
491
537
|
throw new UsageError(message);
|
|
492
538
|
}
|
|
493
539
|
|
|
494
|
-
class HelpShown extends Exit {
|
|
495
|
-
constructor() {
|
|
496
|
-
super("help shown", 0);
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
|
|
500
540
|
class Completing {
|
|
501
541
|
options;
|
|
502
542
|
positionals;
|
|
@@ -507,11 +547,6 @@ class Completing {
|
|
|
507
547
|
this.candidates = candidates;
|
|
508
548
|
}
|
|
509
549
|
}
|
|
510
|
-
var completion = { active: false };
|
|
511
|
-
var OUTPUT_OPTIONS = {
|
|
512
|
-
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
513
|
-
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
514
|
-
};
|
|
515
550
|
function applyOutput(color, plain, env = process9.env) {
|
|
516
551
|
const when = plain === true ? "never" : color ?? "auto";
|
|
517
552
|
if (when === "auto")
|
|
@@ -665,7 +700,6 @@ function parseError(error) {
|
|
|
665
700
|
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
666
701
|
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
667
702
|
}
|
|
668
|
-
var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
669
703
|
function nearestOption(message, options, allowNegative) {
|
|
670
704
|
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
671
705
|
if (typed === undefined)
|
|
@@ -681,6 +715,69 @@ function nearestOption(message, options, allowNegative) {
|
|
|
681
715
|
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
682
716
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
683
717
|
}
|
|
718
|
+
var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
|
|
719
|
+
var init_args = __esm(() => {
|
|
720
|
+
init_format();
|
|
721
|
+
init_help();
|
|
722
|
+
init_text();
|
|
723
|
+
init_help();
|
|
724
|
+
init_input();
|
|
725
|
+
DASHES = /^-+/;
|
|
726
|
+
EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
|
|
727
|
+
Exit = class Exit extends Error {
|
|
728
|
+
code;
|
|
729
|
+
hint;
|
|
730
|
+
[EXIT] = true;
|
|
731
|
+
constructor(message, code, hint) {
|
|
732
|
+
super(message);
|
|
733
|
+
this.code = code;
|
|
734
|
+
this.hint = hint;
|
|
735
|
+
}
|
|
736
|
+
static [Symbol.hasInstance](value) {
|
|
737
|
+
if (this !== Exit)
|
|
738
|
+
return Function.prototype[Symbol.hasInstance].call(this, value);
|
|
739
|
+
return typeof value === "object" && value !== null && value[EXIT] === true;
|
|
740
|
+
}
|
|
741
|
+
};
|
|
742
|
+
UsageError = class UsageError extends Exit {
|
|
743
|
+
constructor(message, hint) {
|
|
744
|
+
super(message, 2, hint);
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
HelpShown = class HelpShown extends Exit {
|
|
748
|
+
constructor() {
|
|
749
|
+
super("help shown", 0);
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
completion = { active: false };
|
|
753
|
+
OUTPUT_OPTIONS = {
|
|
754
|
+
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
755
|
+
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
756
|
+
};
|
|
757
|
+
UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
758
|
+
});
|
|
759
|
+
|
|
760
|
+
// ../kit/src/folders.ts
|
|
761
|
+
function ignoredFolders(extra = [], where = {}) {
|
|
762
|
+
const configured = readUserConfig("config", where).ignore;
|
|
763
|
+
const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
|
|
764
|
+
return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
|
|
765
|
+
}
|
|
766
|
+
var SKIPPED_FOLDERS;
|
|
767
|
+
var init_folders = __esm(() => {
|
|
768
|
+
init_user_config();
|
|
769
|
+
SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
770
|
+
});
|
|
771
|
+
|
|
772
|
+
// src/cli.ts
|
|
773
|
+
import { appendFileSync as appendFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync6, rmSync, statSync as statSync2, writeFileSync } from "fs";
|
|
774
|
+
import { homedir as homedir4 } from "os";
|
|
775
|
+
import { dirname as dirname5 } from "path";
|
|
776
|
+
import process18 from "process";
|
|
777
|
+
|
|
778
|
+
// ../kit/src/index.ts
|
|
779
|
+
init_args();
|
|
780
|
+
|
|
684
781
|
// ../kit/src/argv.ts
|
|
685
782
|
import { readFileSync as readFileSync3, realpathSync } from "fs";
|
|
686
783
|
import { resolve as resolve3 } from "path";
|
|
@@ -705,10 +802,23 @@ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), scr
|
|
|
705
802
|
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
706
803
|
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
707
804
|
}
|
|
805
|
+
// ../kit/src/chart.ts
|
|
806
|
+
init_format();
|
|
807
|
+
init_mode();
|
|
808
|
+
init_style();
|
|
809
|
+
init_theme();
|
|
810
|
+
// ../kit/src/ci.ts
|
|
811
|
+
init_args();
|
|
812
|
+
init_format();
|
|
813
|
+
|
|
814
|
+
// ../kit/src/progress.ts
|
|
815
|
+
init_format();
|
|
816
|
+
|
|
708
817
|
// ../kit/src/process.ts
|
|
709
818
|
import { constants } from "os";
|
|
710
819
|
import process11 from "process";
|
|
711
820
|
var KILL_GRACE_MS = 2000;
|
|
821
|
+
var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
|
|
712
822
|
function exitCodeOf(code, signal) {
|
|
713
823
|
if (code !== null)
|
|
714
824
|
return code;
|
|
@@ -716,10 +826,10 @@ function exitCodeOf(code, signal) {
|
|
|
716
826
|
return 128 + signal;
|
|
717
827
|
return signal === null ? 129 : 128 + constants.signals[signal];
|
|
718
828
|
}
|
|
719
|
-
async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
829
|
+
async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
720
830
|
const chunks = [];
|
|
721
831
|
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
|
|
722
|
-
const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
|
|
832
|
+
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 } : {} });
|
|
723
833
|
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
|
|
724
834
|
const timers = [];
|
|
725
835
|
const killGroup = (killing) => {
|
|
@@ -759,12 +869,19 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
|
|
|
759
869
|
stop();
|
|
760
870
|
continue;
|
|
761
871
|
}
|
|
872
|
+
if (state.truncated)
|
|
873
|
+
continue;
|
|
874
|
+
let kept = data;
|
|
762
875
|
if (state.kept + data.length > maxBytes) {
|
|
876
|
+
let cut = maxBytes - state.kept;
|
|
877
|
+
while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
|
|
878
|
+
cut--;
|
|
879
|
+
kept = data.subarray(0, cut);
|
|
763
880
|
state.truncated = true;
|
|
764
|
-
continue;
|
|
765
881
|
}
|
|
766
|
-
state.kept +=
|
|
767
|
-
|
|
882
|
+
state.kept += kept.length;
|
|
883
|
+
if (kept.length > 0)
|
|
884
|
+
chunks.push({ stream: name, data: kept });
|
|
768
885
|
}
|
|
769
886
|
};
|
|
770
887
|
try {
|
|
@@ -781,6 +898,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
|
|
|
781
898
|
const joined = () => Buffer.concat(chunks.map(({ data }) => data));
|
|
782
899
|
let output;
|
|
783
900
|
let text;
|
|
901
|
+
let stdout;
|
|
784
902
|
return {
|
|
785
903
|
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
786
904
|
chunks,
|
|
@@ -791,49 +909,168 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
|
|
|
791
909
|
},
|
|
792
910
|
get text() {
|
|
793
911
|
return text ??= (output ??= joined()).toString();
|
|
912
|
+
},
|
|
913
|
+
get stdout() {
|
|
914
|
+
return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
|
|
794
915
|
}
|
|
795
916
|
};
|
|
796
917
|
}
|
|
797
918
|
|
|
798
919
|
// ../kit/src/progress.ts
|
|
920
|
+
init_style();
|
|
921
|
+
init_theme();
|
|
799
922
|
var ESC = String.fromCharCode(27);
|
|
800
923
|
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
801
924
|
var RESET_STYLE = `${ESC}[0m`;
|
|
802
925
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
926
|
+
|
|
927
|
+
// ../kit/src/ci.ts
|
|
928
|
+
init_style();
|
|
929
|
+
|
|
930
|
+
// ../kit/src/tool.ts
|
|
931
|
+
init_format();
|
|
803
932
|
// ../kit/src/cli.ts
|
|
933
|
+
init_args();
|
|
804
934
|
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
805
935
|
import { dirname as dirname3, join as join5 } from "path";
|
|
806
|
-
import
|
|
936
|
+
import process15 from "process";
|
|
807
937
|
|
|
808
|
-
// ../kit/src/
|
|
938
|
+
// ../kit/src/askpass.ts
|
|
809
939
|
import process12 from "process";
|
|
940
|
+
var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
|
|
941
|
+
async function askpassClient(argv) {
|
|
942
|
+
const socketPath = process12.env[SOCKET_VARIABLE];
|
|
943
|
+
if (socketPath === undefined)
|
|
944
|
+
return;
|
|
945
|
+
const request = { prompt: argv[0] ?? "", ...process12.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
|
|
946
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
947
|
+
let received = "";
|
|
948
|
+
try {
|
|
949
|
+
await Bun.connect({
|
|
950
|
+
unix: socketPath,
|
|
951
|
+
socket: {
|
|
952
|
+
open: (socket) => void socket.write(`${JSON.stringify(request)}
|
|
953
|
+
`),
|
|
954
|
+
data: (_, chunk) => {
|
|
955
|
+
received += chunk.toString();
|
|
956
|
+
},
|
|
957
|
+
close: () => resolve(received),
|
|
958
|
+
error: () => resolve("")
|
|
959
|
+
}
|
|
960
|
+
});
|
|
961
|
+
} catch {
|
|
962
|
+
return 1;
|
|
963
|
+
}
|
|
964
|
+
const reply = await promise;
|
|
965
|
+
if (reply === "")
|
|
966
|
+
return 1;
|
|
967
|
+
const { answer } = JSON.parse(reply);
|
|
968
|
+
if (request.notice === true)
|
|
969
|
+
return 0;
|
|
970
|
+
if (answer === undefined)
|
|
971
|
+
return 1;
|
|
972
|
+
process12.stdout.write(`${answer}
|
|
973
|
+
`);
|
|
974
|
+
return 0;
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
// ../kit/src/completions.ts
|
|
978
|
+
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
979
|
+
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'
|
|
980
|
+
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
981
|
+
set -l current (commandline -ct)
|
|
982
|
+
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
983
|
+
if test "$line" = __files__
|
|
984
|
+
__fish_complete_path $current
|
|
985
|
+
else
|
|
986
|
+
echo $line
|
|
987
|
+
end
|
|
988
|
+
end
|
|
989
|
+
end`;
|
|
990
|
+
var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
991
|
+
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
992
|
+
local -a lines
|
|
993
|
+
COMPREPLY=()
|
|
994
|
+
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
995
|
+
for line in "\${lines[@]}"; do
|
|
996
|
+
if [[ $line == __files__ ]]; then
|
|
997
|
+
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
998
|
+
else
|
|
999
|
+
words+="\${line%%$'\\t'*}"$'\\n'
|
|
1000
|
+
fi
|
|
1001
|
+
done
|
|
1002
|
+
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
1003
|
+
}`;
|
|
1004
|
+
var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1005
|
+
local line
|
|
1006
|
+
local -a described plain
|
|
1007
|
+
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
1008
|
+
if [[ $line == __files__ ]]; then
|
|
1009
|
+
_files
|
|
1010
|
+
elif [[ $line == *$'\\t'* ]]; then
|
|
1011
|
+
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
1012
|
+
else
|
|
1013
|
+
plain+=("$line")
|
|
1014
|
+
fi
|
|
1015
|
+
done
|
|
1016
|
+
(( \${#described} )) && _describe -V value described
|
|
1017
|
+
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
1018
|
+
return 0
|
|
1019
|
+
}`;
|
|
1020
|
+
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
1021
|
+
if (shell === "fish")
|
|
1022
|
+
return `${header}
|
|
1023
|
+
${FISH_FUNCTION}
|
|
1024
|
+
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
1025
|
+
`).join("")}`;
|
|
1026
|
+
if (shell === "bash")
|
|
1027
|
+
return `${header}
|
|
1028
|
+
${BASH_FUNCTION}
|
|
1029
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
1030
|
+
`;
|
|
1031
|
+
return `${header}
|
|
1032
|
+
${ZSH_FUNCTION}
|
|
1033
|
+
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
1034
|
+
`;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
// ../kit/src/notify.ts
|
|
1038
|
+
init_format();
|
|
1039
|
+
init_mode();
|
|
1040
|
+
import process13 from "process";
|
|
810
1041
|
var NOTIFY_AFTER_MS = 1e4;
|
|
811
1042
|
var CANCELLED = 130;
|
|
812
1043
|
function base64(text) {
|
|
813
1044
|
return Buffer.from(text).toString("base64");
|
|
814
1045
|
}
|
|
815
|
-
function notification(title, body, env =
|
|
816
|
-
const id = `kit${
|
|
1046
|
+
function notification(title, body, env = process13.env) {
|
|
1047
|
+
const id = `kit${process13.pid}`;
|
|
817
1048
|
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\\`];
|
|
818
1049
|
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
819
1050
|
}
|
|
820
|
-
function notifyEnd(command, code, ms, { stream =
|
|
1051
|
+
function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
|
|
821
1052
|
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
822
1053
|
return;
|
|
823
1054
|
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
824
1055
|
}
|
|
825
1056
|
|
|
1057
|
+
// ../kit/src/cli.ts
|
|
1058
|
+
init_style();
|
|
1059
|
+
init_text();
|
|
1060
|
+
|
|
826
1061
|
// ../kit/src/usage.ts
|
|
827
1062
|
import { appendFileSync, mkdirSync } from "fs";
|
|
828
1063
|
import { homedir as homedir3 } from "os";
|
|
829
|
-
import { dirname as dirname2,
|
|
830
|
-
import
|
|
1064
|
+
import { dirname as dirname2, join as join4 } from "path";
|
|
1065
|
+
import process14 from "process";
|
|
831
1066
|
|
|
832
1067
|
// ../kit/src/logs.ts
|
|
1068
|
+
init_user_config();
|
|
833
1069
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
834
1070
|
var CLI_FOLDER = "kaynooo-cli";
|
|
835
1071
|
|
|
836
1072
|
// ../kit/src/usage.ts
|
|
1073
|
+
init_user_config();
|
|
837
1074
|
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
838
1075
|
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
839
1076
|
var LONGEST_NAME = 40;
|
|
@@ -841,14 +1078,13 @@ var usageError;
|
|
|
841
1078
|
function noteUsageError(message) {
|
|
842
1079
|
usageError = message;
|
|
843
1080
|
}
|
|
844
|
-
function stateHome(env =
|
|
845
|
-
|
|
846
|
-
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
1081
|
+
function stateHome(env = process14.env) {
|
|
1082
|
+
return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
|
|
847
1083
|
}
|
|
848
|
-
function usagePath(env =
|
|
1084
|
+
function usagePath(env = process14.env) {
|
|
849
1085
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
850
1086
|
}
|
|
851
|
-
function usageRecorded(env =
|
|
1087
|
+
function usageRecorded(env = process14.env) {
|
|
852
1088
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
853
1089
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
854
1090
|
}
|
|
@@ -857,12 +1093,12 @@ function flagNames(argv) {
|
|
|
857
1093
|
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
858
1094
|
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
859
1095
|
}
|
|
860
|
-
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
1096
|
+
function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
|
|
861
1097
|
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
862
1098
|
usageError = undefined;
|
|
863
|
-
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
1099
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
|
|
864
1100
|
}
|
|
865
|
-
function recordUsage(entry, env =
|
|
1101
|
+
function recordUsage(entry, env = process14.env) {
|
|
866
1102
|
if (!usageRecorded(env))
|
|
867
1103
|
return;
|
|
868
1104
|
try {
|
|
@@ -878,7 +1114,11 @@ var LEVEL_OPTIONS = {
|
|
|
878
1114
|
...OUTPUT_OPTIONS,
|
|
879
1115
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
880
1116
|
};
|
|
881
|
-
var TOP_OPTIONS = {
|
|
1117
|
+
var TOP_OPTIONS = {
|
|
1118
|
+
...LEVEL_OPTIONS,
|
|
1119
|
+
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1120
|
+
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1121
|
+
};
|
|
882
1122
|
async function commandRows(all, colors) {
|
|
883
1123
|
const commands = shown(all);
|
|
884
1124
|
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
@@ -913,6 +1153,10 @@ function takeOutputFlags(argv) {
|
|
|
913
1153
|
async function resolveSummary(summary) {
|
|
914
1154
|
return typeof summary === "string" ? summary : summary();
|
|
915
1155
|
}
|
|
1156
|
+
function lookup({ commands, aliases }, word) {
|
|
1157
|
+
const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
|
|
1158
|
+
return Object.hasOwn(commands, name) ? commands[name] : undefined;
|
|
1159
|
+
}
|
|
916
1160
|
function scopeOf(commands, extra, aliases) {
|
|
917
1161
|
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
918
1162
|
}
|
|
@@ -952,8 +1196,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
952
1196
|
`);
|
|
953
1197
|
}
|
|
954
1198
|
function printError(prefix, message, hint, cause) {
|
|
955
|
-
const colors = paint(
|
|
956
|
-
const styled = takesControlCodes(
|
|
1199
|
+
const colors = paint(process15.stderr);
|
|
1200
|
+
const styled = takesControlCodes(process15.stderr);
|
|
957
1201
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
958
1202
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
959
1203
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -996,23 +1240,23 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
996
1240
|
}
|
|
997
1241
|
}
|
|
998
1242
|
if (name === undefined && level.path.length > 1) {
|
|
999
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1243
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
|
|
1000
1244
|
return 2;
|
|
1001
1245
|
}
|
|
1002
1246
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1003
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1247
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
|
|
1004
1248
|
return 0;
|
|
1005
1249
|
}
|
|
1006
1250
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1007
1251
|
console.log(version);
|
|
1008
1252
|
return 0;
|
|
1009
1253
|
}
|
|
1010
|
-
let command = level
|
|
1254
|
+
let command = lookup(level, name);
|
|
1011
1255
|
let rest = args;
|
|
1012
1256
|
let ran = name;
|
|
1013
1257
|
if (command === undefined && level.lazy.length > 0) {
|
|
1014
1258
|
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
1015
|
-
command = level
|
|
1259
|
+
command = lookup(level, name);
|
|
1016
1260
|
}
|
|
1017
1261
|
if (command === undefined && level.defaultCommand !== undefined) {
|
|
1018
1262
|
command = level.commands[level.defaultCommand];
|
|
@@ -1092,18 +1336,19 @@ async function leafCandidates(run, words) {
|
|
|
1092
1336
|
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1093
1337
|
const [word = "", ...rest] = words;
|
|
1094
1338
|
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1095
|
-
let { commands
|
|
1096
|
-
let command =
|
|
1339
|
+
let { commands } = scope;
|
|
1340
|
+
let command = lookup(scope, word);
|
|
1097
1341
|
if (listing || command === undefined) {
|
|
1098
|
-
|
|
1099
|
-
|
|
1342
|
+
const expanded = await expand(scope, [...before, ...words]);
|
|
1343
|
+
commands = expanded.commands;
|
|
1344
|
+
command = lookup(expanded, word);
|
|
1100
1345
|
}
|
|
1101
1346
|
if (listing) {
|
|
1102
1347
|
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1103
1348
|
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1104
1349
|
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1105
1350
|
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1106
|
-
return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line)
|
|
1351
|
+
return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
|
|
1107
1352
|
}
|
|
1108
1353
|
if (command === undefined) {
|
|
1109
1354
|
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
@@ -1111,6 +1356,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
|
|
|
1111
1356
|
}
|
|
1112
1357
|
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1113
1358
|
}
|
|
1359
|
+
var COMPLETIONS = "--completions";
|
|
1360
|
+
function flagValue([flag = "", ...rest]) {
|
|
1361
|
+
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1362
|
+
}
|
|
1363
|
+
function printCompletionScript(name, args) {
|
|
1364
|
+
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1365
|
+
if (shell === undefined || args.length !== 1) {
|
|
1366
|
+
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1367
|
+
return 2;
|
|
1368
|
+
}
|
|
1369
|
+
console.log(completionScript(shell, [name]).trimEnd());
|
|
1370
|
+
return 0;
|
|
1371
|
+
}
|
|
1114
1372
|
async function printCandidates(found) {
|
|
1115
1373
|
for (const line of await found)
|
|
1116
1374
|
console.log(line);
|
|
@@ -1133,15 +1391,20 @@ function packageVersion(entry = Bun.main) {
|
|
|
1133
1391
|
}
|
|
1134
1392
|
async function runCli(cli, argv = scriptArgs()) {
|
|
1135
1393
|
const version = cli.version ?? packageVersion();
|
|
1394
|
+
const answered = await askpassClient(argv);
|
|
1395
|
+
if (answered !== undefined)
|
|
1396
|
+
return answered;
|
|
1136
1397
|
if (argv[0] === COMPLETE)
|
|
1137
1398
|
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1399
|
+
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1400
|
+
return printCompletionScript(cli.name, flagValue(argv));
|
|
1138
1401
|
const started = performance.now();
|
|
1139
1402
|
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 });
|
|
1140
1403
|
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1141
1404
|
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1142
1405
|
if (cli.usage !== false) {
|
|
1143
1406
|
try {
|
|
1144
|
-
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1407
|
+
recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
|
|
1145
1408
|
} catch {}
|
|
1146
1409
|
}
|
|
1147
1410
|
return code;
|
|
@@ -1150,8 +1413,7 @@ function commandPath(scope, argv) {
|
|
|
1150
1413
|
const path = [];
|
|
1151
1414
|
let level = scope;
|
|
1152
1415
|
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1153
|
-
const
|
|
1154
|
-
const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
|
|
1416
|
+
const command = lookup(level, word);
|
|
1155
1417
|
if (command === undefined)
|
|
1156
1418
|
break;
|
|
1157
1419
|
path.push(word);
|
|
@@ -1161,19 +1423,57 @@ function commandPath(scope, argv) {
|
|
|
1161
1423
|
}
|
|
1162
1424
|
return path.length === 0 ? undefined : path.join(" ");
|
|
1163
1425
|
}
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1426
|
+
|
|
1427
|
+
// ../kit/src/index.ts
|
|
1428
|
+
init_config();
|
|
1429
|
+
|
|
1430
|
+
// ../kit/src/excerpt.ts
|
|
1431
|
+
init_text();
|
|
1432
|
+
|
|
1433
|
+
// ../kit/src/index.ts
|
|
1434
|
+
init_folders();
|
|
1435
|
+
init_format();
|
|
1436
|
+
|
|
1437
|
+
// ../kit/src/git.ts
|
|
1438
|
+
init_args();
|
|
1439
|
+
// ../kit/src/limit.ts
|
|
1440
|
+
init_args();
|
|
1441
|
+
|
|
1442
|
+
// ../kit/src/index.ts
|
|
1443
|
+
init_mode();
|
|
1444
|
+
|
|
1445
|
+
// ../kit/src/report.ts
|
|
1446
|
+
init_style();
|
|
1447
|
+
init_text();
|
|
1171
1448
|
// ../kit/src/secrets.ts
|
|
1449
|
+
var SECRET_PART = /token|secret|passw|passphrase|credential|private|dsn|apikey|accesskey|authorization|sess(?:ion)?id|connectionstring|key$/i;
|
|
1172
1450
|
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1451
|
+
var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
|
|
1452
|
+
var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
|
|
1453
|
+
function isSecretWord(word) {
|
|
1454
|
+
const lower = word.toLowerCase();
|
|
1455
|
+
return SECRET_WORDS.has(lower) || lower.endsWith("pass") && !NOT_PASSWORDS.has(lower);
|
|
1456
|
+
}
|
|
1457
|
+
function isSecretName(name) {
|
|
1458
|
+
return SECRET_PART.test(name) || name.split(WORD_BREAKS).some(isSecretWord);
|
|
1459
|
+
}
|
|
1173
1460
|
// ../kit/src/sessions.ts
|
|
1174
1461
|
var {Glob } = globalThis.Bun;
|
|
1175
1462
|
var SESSION_FILES = new Glob("*.json");
|
|
1176
1463
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1464
|
+
|
|
1465
|
+
// ../kit/src/index.ts
|
|
1466
|
+
init_style();
|
|
1467
|
+
init_text();
|
|
1468
|
+
init_theme();
|
|
1469
|
+
init_user_config();
|
|
1470
|
+
|
|
1471
|
+
// ../kit/src/watch.ts
|
|
1472
|
+
init_args();
|
|
1473
|
+
init_input();
|
|
1474
|
+
init_style();
|
|
1475
|
+
// ../kit/src/workspace-root.ts
|
|
1476
|
+
init_user_config();
|
|
1177
1477
|
// ../kit/src/shell.ts
|
|
1178
1478
|
var SEPARATORS = new Set([`
|
|
1179
1479
|
`, ";", "|"]);
|
|
@@ -1181,7 +1481,7 @@ var PLAIN_BREAKERS = new Set(["<", ">", "(", ")", "&", "|"]);
|
|
|
1181
1481
|
var GLOB_CHARS = new Set(["*", "?", "["]);
|
|
1182
1482
|
var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
|
|
1183
1483
|
var WHITESPACE = /\s/;
|
|
1184
|
-
var ASSIGNMENT = /^\w
|
|
1484
|
+
var ASSIGNMENT = /^\w+(?:\[[^\]]*\])?\+?=/;
|
|
1185
1485
|
var TRAILING_SLASHES = /\/+$/;
|
|
1186
1486
|
var TRAILING_CR = /\r$/;
|
|
1187
1487
|
var LEADING_TILDE = /^~(?=\/|$)/;
|
|
@@ -1194,14 +1494,17 @@ var REDIRECT_START = /^\d*[<>]|^&>/;
|
|
|
1194
1494
|
var SAFE_WORD = /^[\w@%+=:,./-]+$/;
|
|
1195
1495
|
var LEADING_HEX = /^[\da-f]*/i;
|
|
1196
1496
|
var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
|
|
1197
|
-
var HEREDOC = /^<<(-?)[ \t]*(?:'
|
|
1497
|
+
var HEREDOC = /^<<(-?)[ \t]*((?:'[^']*'|"(?:\\.|[^"\\])*"|\\.|[^\s;&|<>()'"\\-])(?:'[^']*'|"(?:\\.|[^"\\])*"|\\.|[^\s;&|<>()'"\\])*)/;
|
|
1498
|
+
var DELIMITER_QUOTING = /'([^']*)'|"((?:\\.|[^"\\])*)"|\\(.)/g;
|
|
1499
|
+
var DOUBLE_QUOTED_ESCAPE = /\\([$`"\\])/g;
|
|
1198
1500
|
var ANSI_QUOTE = "$'";
|
|
1199
1501
|
var ANSI_ESCAPES = { n: `
|
|
1200
1502
|
`, t: "\t", r: "\r", a: "\x07", b: "\b", f: "\f", v: "\v", e: "\x1B", E: "\x1B", "\\": "\\", "'": "'", '"': '"', "?": "?" };
|
|
1201
1503
|
var ANSI_DIGITS = { x: 2, u: 4, U: 8 };
|
|
1202
1504
|
var OCTAL = /^[0-7]{1,3}/;
|
|
1203
1505
|
var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
|
|
1204
|
-
var
|
|
1506
|
+
var LEADING_REDIRECT = /^(?:\d+|\{\w+\})?(?:<<<|<<-?|<>|<&|<(?!\()|>>|>&|>\||>|&>>|&>)/;
|
|
1507
|
+
var FISH_COMBINERS = new Set(["and", "or", "not"]);
|
|
1205
1508
|
var MAX_DEPTH = 8;
|
|
1206
1509
|
var MAX_BRACES = 256;
|
|
1207
1510
|
var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
|
|
@@ -1219,6 +1522,7 @@ var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
|
1219
1522
|
function wrapper(short = "", long = [], operands = 0, runsString = false) {
|
|
1220
1523
|
return { short, long, operands, runsString };
|
|
1221
1524
|
}
|
|
1525
|
+
var RUNNER = { ...wrapper(), afterDashes: true };
|
|
1222
1526
|
var WRAPPERS = new Map([
|
|
1223
1527
|
["command", wrapper()],
|
|
1224
1528
|
["builtin", wrapper()],
|
|
@@ -1240,7 +1544,23 @@ var WRAPPERS = new Map([
|
|
|
1240
1544
|
["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
|
|
1241
1545
|
["unbuffer", wrapper()],
|
|
1242
1546
|
["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
|
|
1243
|
-
["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
|
|
1547
|
+
["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])],
|
|
1548
|
+
["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"])],
|
|
1549
|
+
["ltrace", wrapper("aeFlnopsuxX", ["--output", "--user", "--library", "--config", "--align", "--indent"])],
|
|
1550
|
+
["taskset", wrapper("", [], 1)],
|
|
1551
|
+
["fakeroot", wrapper("lsib", ["--lib", "--faked"])],
|
|
1552
|
+
["sshpass", wrapper("pfdP")],
|
|
1553
|
+
["coproc", wrapper()],
|
|
1554
|
+
["proxychains", wrapper("f")],
|
|
1555
|
+
["proxychains4", wrapper("f")],
|
|
1556
|
+
["torsocks", wrapper("upaP", ["--user", "--pass", "--address", "--port"])],
|
|
1557
|
+
["chrt", wrapper("TPD", ["--sched-runtime", "--sched-period", "--sched-deadline"], 1)],
|
|
1558
|
+
["unshare", wrapper("SGRw", ["--setuid", "--setgid", "--root", "--wd", "--map-user", "--map-group", "--map-users", "--map-groups", "--propagation", "--setgroups"])],
|
|
1559
|
+
["nsenter", wrapper("tSG", ["--target", "--setuid", "--setgid"])],
|
|
1560
|
+
["out", RUNNER],
|
|
1561
|
+
["slot", RUNNER],
|
|
1562
|
+
["waitfor", RUNNER],
|
|
1563
|
+
["base", RUNNER]
|
|
1244
1564
|
]);
|
|
1245
1565
|
function closerOf(quote) {
|
|
1246
1566
|
return quote === ANSI_QUOTE ? "'" : quote;
|
|
@@ -1297,6 +1617,10 @@ function splitCommand(command) {
|
|
|
1297
1617
|
i++;
|
|
1298
1618
|
continue;
|
|
1299
1619
|
}
|
|
1620
|
+
if (quote === '"' && isSubstitutionAt(command, i)) {
|
|
1621
|
+
i = substitutionEnd(command, i);
|
|
1622
|
+
continue;
|
|
1623
|
+
}
|
|
1300
1624
|
if (quote !== null) {
|
|
1301
1625
|
if (char === closerOf(quote))
|
|
1302
1626
|
quote = null;
|
|
@@ -1332,9 +1656,15 @@ function splitCommand(command) {
|
|
|
1332
1656
|
i = end - 1;
|
|
1333
1657
|
continue;
|
|
1334
1658
|
}
|
|
1335
|
-
|
|
1659
|
+
if (command.startsWith("<<<", i)) {
|
|
1660
|
+
i += 2;
|
|
1661
|
+
continue;
|
|
1662
|
+
}
|
|
1663
|
+
const heredoc = char === "<" && command[i + 1] === "<" && !LET_PIECE.test(command.slice(start, i)) ? HEREDOC.exec(command.slice(i)) : null;
|
|
1336
1664
|
if (heredoc) {
|
|
1337
|
-
|
|
1665
|
+
const raw = heredoc[2] ?? "";
|
|
1666
|
+
const word = raw.replace(DELIMITER_QUOTING, (_, single, double, escaped) => single ?? double?.replace(DOUBLE_QUOTED_ESCAPE, (__, kept) => kept) ?? escaped ?? "");
|
|
1667
|
+
heredocs.push({ word, stripsTabs: heredoc[1] === "-", isQuoted: word !== raw });
|
|
1338
1668
|
i += heredoc[0].length - 1;
|
|
1339
1669
|
continue;
|
|
1340
1670
|
}
|
|
@@ -1389,7 +1719,10 @@ function isPlain(text) {
|
|
|
1389
1719
|
}
|
|
1390
1720
|
return quote === null;
|
|
1391
1721
|
}
|
|
1392
|
-
function
|
|
1722
|
+
function parenBalance(text) {
|
|
1723
|
+
return balance(text, "(", ")");
|
|
1724
|
+
}
|
|
1725
|
+
function balance(text, open, close) {
|
|
1393
1726
|
let depth = 0;
|
|
1394
1727
|
let unmatched = 0;
|
|
1395
1728
|
let quote = null;
|
|
@@ -1406,18 +1739,18 @@ function unmatchedClosers(text) {
|
|
|
1406
1739
|
quote = null;
|
|
1407
1740
|
else if (quote === null && (char === '"' || char === "'"))
|
|
1408
1741
|
quote = char;
|
|
1409
|
-
else if (quote === null && char ===
|
|
1742
|
+
else if (quote === null && char === open)
|
|
1410
1743
|
depth++;
|
|
1411
|
-
else if (quote === null && char ===
|
|
1744
|
+
else if (quote === null && char === close && depth > 0)
|
|
1412
1745
|
depth--;
|
|
1413
|
-
else if (quote === null && char ===
|
|
1746
|
+
else if (quote === null && char === close)
|
|
1414
1747
|
unmatched++;
|
|
1415
1748
|
}
|
|
1416
|
-
return unmatched;
|
|
1749
|
+
return { opened: depth, closed: unmatched };
|
|
1417
1750
|
}
|
|
1418
1751
|
function withoutSubshell(text) {
|
|
1419
1752
|
let result = text.trim();
|
|
1420
|
-
let closers =
|
|
1753
|
+
let closers = parenBalance(result).closed;
|
|
1421
1754
|
while (result.startsWith("("))
|
|
1422
1755
|
result = result.slice(1).trimStart();
|
|
1423
1756
|
while (closers > 0 && result.endsWith(")")) {
|
|
@@ -1426,6 +1759,12 @@ function withoutSubshell(text) {
|
|
|
1426
1759
|
}
|
|
1427
1760
|
return result;
|
|
1428
1761
|
}
|
|
1762
|
+
function isSubstitutionAt(text, i) {
|
|
1763
|
+
return text[i] === "`" || text[i] === "$" && text[i + 1] === "(";
|
|
1764
|
+
}
|
|
1765
|
+
function substitutionEnd(text, i) {
|
|
1766
|
+
return text[i] === "`" ? closingBackquote(text, i) : closingParen(text, i + 1);
|
|
1767
|
+
}
|
|
1429
1768
|
function closingParen(text, open) {
|
|
1430
1769
|
let depth = 0;
|
|
1431
1770
|
let quote = null;
|
|
@@ -1433,6 +1772,8 @@ function closingParen(text, open) {
|
|
|
1433
1772
|
const char = text[i] ?? "";
|
|
1434
1773
|
if (char === "\\" && quote !== "'") {
|
|
1435
1774
|
i++;
|
|
1775
|
+
} else if (quote === '"' && isSubstitutionAt(text, i)) {
|
|
1776
|
+
i = substitutionEnd(text, i);
|
|
1436
1777
|
} else if (quote !== null) {
|
|
1437
1778
|
if (char === closerOf(quote))
|
|
1438
1779
|
quote = null;
|
|
@@ -1519,11 +1860,12 @@ function words(text) {
|
|
|
1519
1860
|
let quote = null;
|
|
1520
1861
|
for (let i = 0;i < text.length; i++) {
|
|
1521
1862
|
const char = text[i] ?? "";
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
if (isContinuation)
|
|
1863
|
+
if (char === "\\" && quote !== "'" && text[i + 1] === `
|
|
1864
|
+
`) {
|
|
1525
1865
|
i++;
|
|
1526
|
-
|
|
1866
|
+
continue;
|
|
1867
|
+
}
|
|
1868
|
+
if (quote === null && WHITESPACE.test(char)) {
|
|
1527
1869
|
if (isStarted)
|
|
1528
1870
|
found.push({ text: current, isProse, hasGlob, hasBrace });
|
|
1529
1871
|
current = "";
|
|
@@ -1533,8 +1875,6 @@ function words(text) {
|
|
|
1533
1875
|
hasBrace = false;
|
|
1534
1876
|
continue;
|
|
1535
1877
|
}
|
|
1536
|
-
if (isContinuation)
|
|
1537
|
-
continue;
|
|
1538
1878
|
isStarted = true;
|
|
1539
1879
|
if (char === "\\" && quote === ANSI_QUOTE) {
|
|
1540
1880
|
const [decoded, last] = ansiEscape(text, i);
|
|
@@ -1592,14 +1932,23 @@ function skipOptions(tokens, spec) {
|
|
|
1592
1932
|
tokens.shift();
|
|
1593
1933
|
}
|
|
1594
1934
|
function parseCommand(text) {
|
|
1595
|
-
const
|
|
1935
|
+
const found = words(text);
|
|
1936
|
+
const tokens = found.map((word) => word.text);
|
|
1937
|
+
const braced = new Set(found.filter((word) => word.hasBrace).map((word) => word.text));
|
|
1596
1938
|
const assignments = [];
|
|
1597
1939
|
const strings = [];
|
|
1598
1940
|
let isWrapped = false;
|
|
1941
|
+
let opened = 0;
|
|
1599
1942
|
for (;; ) {
|
|
1600
1943
|
const first = tokens[0] ?? "";
|
|
1601
1944
|
const spec = WRAPPERS.get(first.split("/").pop() ?? "");
|
|
1602
|
-
|
|
1945
|
+
const expanded = braced.has(first) ? braceExpand(first) : [];
|
|
1946
|
+
if (expanded.length > 1) {
|
|
1947
|
+
tokens.splice(0, 1, ...expanded);
|
|
1948
|
+
braced.delete(first);
|
|
1949
|
+
} else if (LEADING_REDIRECT.test(first)) {
|
|
1950
|
+
tokens.splice(0, first.replace(LEADING_REDIRECT, "") === "" ? 2 : 1);
|
|
1951
|
+
} else if (first === "function" && tokens.length > 1) {
|
|
1603
1952
|
isWrapped = true;
|
|
1604
1953
|
tokens.splice(0, 2);
|
|
1605
1954
|
if (tokens[0] === "()")
|
|
@@ -1613,13 +1962,14 @@ function parseCommand(text) {
|
|
|
1613
1962
|
} else if (OPENERS.test(first)) {
|
|
1614
1963
|
isWrapped = true;
|
|
1615
1964
|
const rest = first.replace(OPENERS, "");
|
|
1965
|
+
opened += first.length - rest.length;
|
|
1616
1966
|
if (rest === "")
|
|
1617
1967
|
tokens.shift();
|
|
1618
1968
|
else
|
|
1619
1969
|
tokens[0] = rest;
|
|
1620
1970
|
} else if (ASSIGNMENT.test(first)) {
|
|
1621
1971
|
assignments.push(tokens.shift() ?? "");
|
|
1622
|
-
} else if (KEYWORDS.has(first)) {
|
|
1972
|
+
} else if (KEYWORDS.has(first) || FISH_COMBINERS.has(first)) {
|
|
1623
1973
|
isWrapped = true;
|
|
1624
1974
|
tokens.shift();
|
|
1625
1975
|
} else if (first === "case") {
|
|
@@ -1629,8 +1979,12 @@ function parseCommand(text) {
|
|
|
1629
1979
|
} else if (tokens.length > 1 && CASE_LABEL.test(first)) {
|
|
1630
1980
|
isWrapped = true;
|
|
1631
1981
|
tokens.shift();
|
|
1632
|
-
} else if (
|
|
1633
|
-
tokens.
|
|
1982
|
+
} else if (spec?.afterDashes === true) {
|
|
1983
|
+
const dashes = tokens.indexOf("--");
|
|
1984
|
+
if (dashes === -1)
|
|
1985
|
+
break;
|
|
1986
|
+
isWrapped = true;
|
|
1987
|
+
tokens.splice(0, dashes + 1);
|
|
1634
1988
|
} else if (spec !== undefined) {
|
|
1635
1989
|
isWrapped = true;
|
|
1636
1990
|
tokens.shift();
|
|
@@ -1641,7 +1995,7 @@ function parseCommand(text) {
|
|
|
1641
1995
|
break;
|
|
1642
1996
|
}
|
|
1643
1997
|
}
|
|
1644
|
-
const closers = CLOSERS.exec(text.trimEnd())?.[0].length ?? 0;
|
|
1998
|
+
const closers = Math.min(CLOSERS.exec(text.trimEnd())?.[0].length ?? 0, opened + parenBalance(text).closed + balance(text, "{", "}").closed);
|
|
1645
1999
|
const word = tokens.at(-1) ?? "";
|
|
1646
2000
|
const trimmed = word.length - (CLOSERS.exec(word)?.[0].length ?? 0);
|
|
1647
2001
|
const last = word.slice(0, Math.max(trimmed, word.length - closers));
|
|
@@ -1671,7 +2025,13 @@ function commandStrings(tokens) {
|
|
|
1671
2025
|
isValue = false;
|
|
1672
2026
|
continue;
|
|
1673
2027
|
}
|
|
2028
|
+
if (name === "fish" && option.startsWith("--init-command=")) {
|
|
2029
|
+
found.push(option.slice("--init-command=".length));
|
|
2030
|
+
continue;
|
|
2031
|
+
}
|
|
1674
2032
|
if (SHELL_VALUE_OPTIONS.has(option) || name === "fish" && FISH_VALUE_OPTIONS.has(option)) {
|
|
2033
|
+
if (name === "fish" && FISH_VALUE_OPTIONS.has(option))
|
|
2034
|
+
found.push(tokens[j + 1] ?? "");
|
|
1675
2035
|
isValue = true;
|
|
1676
2036
|
continue;
|
|
1677
2037
|
}
|
|
@@ -1922,6 +2282,33 @@ var DEFINITION_MODIFIERS = new Set(["or", "replace", "temporary", "temp", "unlog
|
|
|
1922
2282
|
var SERVER_OBJECTS = new Set(["database", "user", "role", "server", "tablespace", "extension", "system", "subscription", "publication", "logfile", "instance", "resource"]);
|
|
1923
2283
|
var FILE_WORDS = new Set(["infile", "outfile", "dumpfile"]);
|
|
1924
2284
|
var SEQUENCE_FUNCTIONS = new Set(["nextval", "setval"]);
|
|
2285
|
+
function foreignDatabases(statement, database) {
|
|
2286
|
+
const found = [];
|
|
2287
|
+
for (const [index, token] of statement.entries()) {
|
|
2288
|
+
if ((token.kind === "word" || token.kind === "quoted") && !isPunct(statement[index - 1], "@") && isPunct(statement[index + 1], ".") && !isPunct(statement[index - 1], ".") && token.text.toLowerCase() !== database.toLowerCase())
|
|
2289
|
+
found.push(token.text);
|
|
2290
|
+
}
|
|
2291
|
+
return found;
|
|
2292
|
+
}
|
|
2293
|
+
var EXISTENCE_WORDS = new Set(["if", "not", "exists"]);
|
|
2294
|
+
function otherDatabases(sql, dialect, database) {
|
|
2295
|
+
const found = [];
|
|
2296
|
+
for (const statement of splitStatements(tokenize2(sql, dialect))) {
|
|
2297
|
+
if (dialect === "mysql")
|
|
2298
|
+
found.push(...foreignDatabases(statement, database));
|
|
2299
|
+
const first = statement[0]?.text ?? "";
|
|
2300
|
+
const kind = statement.findIndex((token, index) => index > 0 && !DEFINITION_MODIFIERS.has(token.text));
|
|
2301
|
+
const isDatabase = DEFINITION_STARTS.has(first) && (statement[kind]?.text === "database" || dialect === "mysql" && statement[kind]?.text === "schema");
|
|
2302
|
+
let named;
|
|
2303
|
+
if (first === "use")
|
|
2304
|
+
named = statement[1];
|
|
2305
|
+
else if (isDatabase)
|
|
2306
|
+
named = statement.slice(kind + 1).find((token) => !EXISTENCE_WORDS.has(token.text));
|
|
2307
|
+
if (named !== undefined && named.kind !== "punct" && named.text.toLowerCase() !== database.toLowerCase())
|
|
2308
|
+
found.push(named.text);
|
|
2309
|
+
}
|
|
2310
|
+
return found;
|
|
2311
|
+
}
|
|
1925
2312
|
|
|
1926
2313
|
// ../db/src/guard.ts
|
|
1927
2314
|
var LOCK_KIND = /^(?:update|share|no|key)$/;
|
|
@@ -2006,7 +2393,12 @@ var KNOWN_LONGS = [...STATEMENT_LONGS, ...FILE_LONGS, ...DATABASE_LONGS, ...VALU
|
|
|
2006
2393
|
var LIST_OPTIONS = new Set(["-l", "--list"]);
|
|
2007
2394
|
var REDIRECT_ONLY2 = /^\d*(?:>|>>|>&|&>|>\||<&|<>)$/;
|
|
2008
2395
|
var REDIRECT_START2 = /^\d*>|^&>/;
|
|
2009
|
-
var
|
|
2396
|
+
var URL_START = /^[a-z][a-z\d+.-]*:\/\//i;
|
|
2397
|
+
var URL_PATH = /^[a-z][a-z\d+.-]*:\/\/[^/?]*\/?([^?]*)/i;
|
|
2398
|
+
var CONNINFO = /^\s*\w+\s*=/;
|
|
2399
|
+
var CONNINFO_PAIR = /\s*(\w+)\s*=\s*(?:'((?:\\[\s\S]|[^'\\])*)'|(?!')((?:\\[\s\S]?|[^\s\\])*))/gy;
|
|
2400
|
+
var ESCAPED = /\\([\s\S]?)/g;
|
|
2401
|
+
var UNREAD_CONNINFO = "a conninfo string not read to its end";
|
|
2010
2402
|
var WRITING_CONSOLE = /^(?:doctrine:(?:migrations:(?:migrate|execute|rollup)|schema:(?:update|create|drop)|database:(?:create|drop)|fixtures:load)|migrate(?::\w+)?|db:(?:seed|wipe))$/;
|
|
2011
2403
|
var TEST_SCOPED = /(?:^|[^a-z])test/i;
|
|
2012
2404
|
var ASSIGNMENT2 = /^([A-Z_]\w*)=/i;
|
|
@@ -2017,6 +2409,7 @@ var SHOT_STACK = /\.worktrees\/[^/\s]+\/shot(?:\/|$)|--shot(?:-|$)/;
|
|
|
2017
2409
|
var DEVICE_PATH = /^\/(?:dev|proc|sys)\//;
|
|
2018
2410
|
var STDIN_PATHS = new Set(["-", "/dev/stdin"]);
|
|
2019
2411
|
var SQL_WRITE = "Statements that write (INSERT, UPDATE, DELETE, DDL, migrations, fixtures) are handed over: list the exact command for the user to run. Only a clearly test-only database runs them directly.";
|
|
2412
|
+
var SQL_OTHER_DATABASE = "A write naming another database than the test one the client connects to (a qualified name, USE, CREATE or DROP DATABASE) reaches past it: hand the exact command over for the user to run.";
|
|
2020
2413
|
var SHELL_SYNTAX = /[$`]/;
|
|
2021
2414
|
function sqlUnreadable(path) {
|
|
2022
2415
|
let cause = "missing when the command is checked, or too large";
|
|
@@ -2032,8 +2425,49 @@ function hasWrite(statement) {
|
|
|
2032
2425
|
function programOf(word) {
|
|
2033
2426
|
return word.split("/").pop() ?? "";
|
|
2034
2427
|
}
|
|
2428
|
+
function percentDecoded(text) {
|
|
2429
|
+
try {
|
|
2430
|
+
return decodeURIComponent(text);
|
|
2431
|
+
} catch {
|
|
2432
|
+
return text;
|
|
2433
|
+
}
|
|
2434
|
+
}
|
|
2435
|
+
function queryDatabase(operand) {
|
|
2436
|
+
const query = operand.indexOf("?");
|
|
2437
|
+
let database;
|
|
2438
|
+
if (query === -1)
|
|
2439
|
+
return;
|
|
2440
|
+
for (const pair of operand.slice(query + 1).split("&")) {
|
|
2441
|
+
const equals = pair.indexOf("=");
|
|
2442
|
+
if (equals !== -1 && percentDecoded(pair.slice(0, equals)) === "dbname")
|
|
2443
|
+
database = pair.slice(equals + 1);
|
|
2444
|
+
}
|
|
2445
|
+
return database;
|
|
2446
|
+
}
|
|
2447
|
+
function urlDatabase(url) {
|
|
2448
|
+
const raw = queryDatabase(url) ?? URL_PATH.exec(url)?.[1];
|
|
2449
|
+
return raw === undefined || raw === "" ? undefined : percentDecoded(raw);
|
|
2450
|
+
}
|
|
2035
2451
|
function databaseOf(operand) {
|
|
2036
|
-
|
|
2452
|
+
if (URL_START.test(operand)) {
|
|
2453
|
+
const whole = urlDatabase(operand);
|
|
2454
|
+
const fragment = operand.indexOf("#");
|
|
2455
|
+
if (fragment === -1)
|
|
2456
|
+
return whole;
|
|
2457
|
+
const cut = urlDatabase(operand.slice(0, fragment));
|
|
2458
|
+
return whole !== undefined && TEST_SCOPED.test(whole) ? cut : whole;
|
|
2459
|
+
}
|
|
2460
|
+
if (!CONNINFO.test(operand))
|
|
2461
|
+
return operand;
|
|
2462
|
+
let database;
|
|
2463
|
+
let end = 0;
|
|
2464
|
+
for (const match of operand.matchAll(CONNINFO_PAIR)) {
|
|
2465
|
+
const [whole, key, quoted, bare] = match;
|
|
2466
|
+
end = match.index + whole.length;
|
|
2467
|
+
if (key === "dbname")
|
|
2468
|
+
database = (quoted ?? bare ?? "").replaceAll(ESCAPED, "$1");
|
|
2469
|
+
}
|
|
2470
|
+
return operand.slice(end).trim() === "" ? database : UNREAD_CONNINFO;
|
|
2037
2471
|
}
|
|
2038
2472
|
function fullOption(option) {
|
|
2039
2473
|
if (KNOWN_LONGS.includes(option) || option.length < 4)
|
|
@@ -2042,7 +2476,7 @@ function fullOption(option) {
|
|
|
2042
2476
|
return candidates.length === 1 ? candidates[0] : option;
|
|
2043
2477
|
}
|
|
2044
2478
|
function clientInput(name, args) {
|
|
2045
|
-
const input = { statements: [], files: [],
|
|
2479
|
+
const input = { statements: [], files: [], operands: [] };
|
|
2046
2480
|
const valueShorts = VALUE_SHORTS[name] ?? "";
|
|
2047
2481
|
let isOperands = false;
|
|
2048
2482
|
for (let i = 0;i < args.length; i++) {
|
|
@@ -2073,7 +2507,7 @@ function clientInput(name, args) {
|
|
|
2073
2507
|
else if (option === "--file")
|
|
2074
2508
|
input.files.push(value);
|
|
2075
2509
|
else if (DATABASE_LONGS.has(option))
|
|
2076
|
-
input.
|
|
2510
|
+
input.database = databaseOf(value);
|
|
2077
2511
|
if (attached === undefined && (STATEMENT_LONGS.has(option) || option === "--file" || DATABASE_LONGS.has(option) || VALUE_LONGS.has(option)))
|
|
2078
2512
|
i++;
|
|
2079
2513
|
} else if (arg === "-cmd" && name === "sqlite3") {
|
|
@@ -2091,7 +2525,7 @@ function clientInput(name, args) {
|
|
|
2091
2525
|
else if (FILE_SHORTS[name]?.includes(letter) === true)
|
|
2092
2526
|
input.files.push(value);
|
|
2093
2527
|
else if (DATABASE_SHORTS.has(letter))
|
|
2094
|
-
input.
|
|
2528
|
+
input.database = databaseOf(value);
|
|
2095
2529
|
break;
|
|
2096
2530
|
}
|
|
2097
2531
|
} else {
|
|
@@ -2100,8 +2534,8 @@ function clientInput(name, args) {
|
|
|
2100
2534
|
}
|
|
2101
2535
|
if (name === "sqlite3")
|
|
2102
2536
|
input.statements.push(...input.operands.slice(1));
|
|
2103
|
-
else if (input.operands[0] !== undefined)
|
|
2104
|
-
input.
|
|
2537
|
+
else if (input.database === undefined && input.operands[0] !== undefined)
|
|
2538
|
+
input.database = databaseOf(input.operands[0]);
|
|
2105
2539
|
return input;
|
|
2106
2540
|
}
|
|
2107
2541
|
function isTestWord(word) {
|
|
@@ -2116,11 +2550,33 @@ function targetWords(words) {
|
|
|
2116
2550
|
function isTestScoped(words, client, input) {
|
|
2117
2551
|
if (client === -1)
|
|
2118
2552
|
return targetWords(words).some(isTestWord);
|
|
2119
|
-
|
|
2553
|
+
const named = input?.database;
|
|
2554
|
+
const before = targetWords(words.slice(0, client)).filter((word) => named === undefined || !ASSIGNMENT2.test(word));
|
|
2555
|
+
return before.some(isTestWord) || named !== undefined && TEST_SCOPED.test(named);
|
|
2120
2556
|
}
|
|
2121
2557
|
async function fileText(path, read) {
|
|
2122
2558
|
return DEVICE_PATH.test(path) ? null : read(path);
|
|
2123
2559
|
}
|
|
2560
|
+
function clientDialect(name) {
|
|
2561
|
+
if (IS_MYSQL.has(name))
|
|
2562
|
+
return "mysql";
|
|
2563
|
+
return name === "sqlite3" ? undefined : "postgres";
|
|
2564
|
+
}
|
|
2565
|
+
async function clientStatements(pieces, index, input, read) {
|
|
2566
|
+
const before = index === 0 ? null : parseCommand(pieces[index - 1]?.command ?? "");
|
|
2567
|
+
const isPiped = pieces[index - 1]?.separator === "|";
|
|
2568
|
+
const paths = input.files.filter((path) => !STDIN_PATHS.has(path));
|
|
2569
|
+
const files = [...paths, ...isPiped && before?.program === "cat" ? before.args.filter((arg) => !arg.startsWith("-")) : []];
|
|
2570
|
+
const texts = await Promise.all(files.map(async (path) => fileText(path, read)));
|
|
2571
|
+
const unreadable = texts.indexOf(null);
|
|
2572
|
+
const statements = [
|
|
2573
|
+
...input.statements,
|
|
2574
|
+
...pieces[index]?.heredocs ?? [],
|
|
2575
|
+
isPiped && before !== null && PRINTERS2.has(before.program) ? before.args.join(" ") : "",
|
|
2576
|
+
...texts.map((text) => text ?? "")
|
|
2577
|
+
];
|
|
2578
|
+
return { statements, unreadable: unreadable === -1 ? undefined : files[unreadable] };
|
|
2579
|
+
}
|
|
2124
2580
|
async function sqlViolation(command, read) {
|
|
2125
2581
|
const pieces = splitCommand(command);
|
|
2126
2582
|
let inShotStack = false;
|
|
@@ -2131,28 +2587,26 @@ async function sqlViolation(command, read) {
|
|
|
2131
2587
|
inShotStack = SHOT_STACK.test(args[0] ?? "");
|
|
2132
2588
|
const client = words.findIndex((word) => SQL_CLIENTS.has(programOf(word)));
|
|
2133
2589
|
const input = client === -1 ? null : clientInput(programOf(words[client] ?? ""), words.slice(client + 1));
|
|
2134
|
-
if (inShotStack
|
|
2590
|
+
if (inShotStack)
|
|
2135
2591
|
continue;
|
|
2592
|
+
if (isTestScoped(words, client, input)) {
|
|
2593
|
+
const dialect = clientDialect(programOf(words[client] ?? ""));
|
|
2594
|
+
if (input !== null && dialect !== undefined) {
|
|
2595
|
+
const { statements } = await clientStatements(pieces, index, input, read);
|
|
2596
|
+
if (statements.some((statement) => hasWrite(statement) && otherDatabases(statement, dialect, input.database ?? "").length > 0))
|
|
2597
|
+
return SQL_OTHER_DATABASE;
|
|
2598
|
+
}
|
|
2599
|
+
continue;
|
|
2600
|
+
}
|
|
2136
2601
|
if (WRITING_TOOLS.has(program) && !words.some((word) => LIST_OPTIONS.has(word)))
|
|
2137
2602
|
return SQL_WRITE;
|
|
2138
2603
|
if (CONSOLE_PROGRAMS.has(program) && words.some((word) => WRITING_CONSOLE.test(word)))
|
|
2139
2604
|
return SQL_WRITE;
|
|
2140
2605
|
if (input === null)
|
|
2141
2606
|
continue;
|
|
2142
|
-
const
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
const files = [...paths, ...isPiped && before?.program === "cat" ? before.args.filter((arg) => !arg.startsWith("-")) : []];
|
|
2146
|
-
const texts = await Promise.all(files.map(async (path) => fileText(path, read)));
|
|
2147
|
-
const unreadable = texts.indexOf(null);
|
|
2148
|
-
if (unreadable !== -1)
|
|
2149
|
-
return sqlUnreadable(files[unreadable] ?? "");
|
|
2150
|
-
const statements = [
|
|
2151
|
-
...input.statements,
|
|
2152
|
-
...piece.heredocs,
|
|
2153
|
-
isPiped && before !== null && PRINTERS2.has(before.program) ? before.args.join(" ") : "",
|
|
2154
|
-
...texts.map((text) => text ?? "")
|
|
2155
|
-
];
|
|
2607
|
+
const { statements, unreadable } = await clientStatements(pieces, index, input, read);
|
|
2608
|
+
if (unreadable !== undefined)
|
|
2609
|
+
return sqlUnreadable(unreadable);
|
|
2156
2610
|
if (statements.some(hasWrite))
|
|
2157
2611
|
return SQL_WRITE;
|
|
2158
2612
|
}
|
|
@@ -2160,11 +2614,12 @@ async function sqlViolation(command, read) {
|
|
|
2160
2614
|
}
|
|
2161
2615
|
|
|
2162
2616
|
// ../env/src/guard-dumps.ts
|
|
2617
|
+
import { basename } from "path";
|
|
2163
2618
|
var OPENER = /^[({]+/;
|
|
2164
2619
|
var DUMP_FLAGS = /^-[a-z]*[px]/;
|
|
2165
2620
|
var GIT_PATCHES = new Set(["diff", "log", "show", "whatchanged", "format-patch", "grep"]);
|
|
2166
2621
|
var GIT_NO_PATCH = new Set(["--stat", "--numstat", "--shortstat", "--name-only", "--name-status", "--summary", "-s", "--no-patch", "--check", "--quiet"]);
|
|
2167
|
-
var GIT_VALUE_OPTIONS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"]);
|
|
2622
|
+
var GIT_VALUE_OPTIONS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env", "--attr-source"]);
|
|
2168
2623
|
var GIT_PATCH_FLAGS = new Set(["-p", "-u", "--patch", "-c", "--cc", "--patch-with-stat", "--patch-with-raw"]);
|
|
2169
2624
|
var GIT_EXCLUDE = /^:(?:!|\^|\(exclude\))/;
|
|
2170
2625
|
var ENV_PRINTERS = new Set(["env", "printenv"]);
|
|
@@ -2173,6 +2628,7 @@ var SHELLS2 = new Set(["sh", "bash", "zsh", "ash"]);
|
|
|
2173
2628
|
var SHELL_COMMAND_FLAG = /^-[abd-z]*c[a-z]*$/;
|
|
2174
2629
|
var DOCKER_VALUE_OPTIONS = new Set(["-f", "--file", "-p", "--project-name", "--profile", "--env-file", "--project-directory", "--ansi", "--progress", "--parallel", "-H", "--host", "-c", "--context", "--config", "-l", "--log-level"]);
|
|
2175
2630
|
var EXEC_VALUE_OPTIONS = new Set(["-e", "--env", "--env-file", "-u", "--user", "-w", "--workdir", "--index", "--detach-keys"]);
|
|
2631
|
+
var RUN_VALUE_OPTIONS = new Set([...EXEC_VALUE_OPTIONS, "-a", "--attach", "--add-host", "--annotation", "--blkio-weight", "--cap-add", "--cap-drop", "--cgroup-parent", "--cgroupns", "--cidfile", "-c", "--cpu-shares", "--cpus", "--cpuset-cpus", "--cpuset-mems", "--cpu-period", "--cpu-quota", "--device", "--dns", "--dns-option", "--dns-search", "--domainname", "--entrypoint", "--env-from-file", "--expose", "--gpus", "--group-add", "--health-cmd", "--health-interval", "--health-retries", "--health-start-period", "--health-timeout", "-h", "--hostname", "--ip", "--ip6", "--ipc", "--isolation", "-l", "--label", "--label-file", "--link", "--log-driver", "--log-opt", "--mac-address", "-m", "--memory", "--memory-reservation", "--memory-swap", "--mount", "--name", "--network", "--net", "--network-alias", "--pid", "--pids-limit", "--platform", "-p", "--publish", "--pull", "--restart", "--runtime", "--security-opt", "--shm-size", "--stop-signal", "--stop-timeout", "--storage-opt", "--sysctl", "--tmpfs", "--ulimit", "--userns", "--uts", "-v", "--volume", "--volumes-from"]);
|
|
2176
2632
|
var CONFIG_LISTS = new Set(["--services", "--volumes", "--profiles", "--images", "--networks", "--hash", "-q", "--quiet"]);
|
|
2177
2633
|
var FORMAT_OPTIONS = new Set(["-f", "--format"]);
|
|
2178
2634
|
var WHOLE_FORMAT = /Env|\{\{\s*json\s+\.\s*\}\}|^json$/;
|
|
@@ -2186,11 +2642,19 @@ function firstOperand(words, valueOptions) {
|
|
|
2186
2642
|
}
|
|
2187
2643
|
return words.length;
|
|
2188
2644
|
}
|
|
2645
|
+
function isEnvPrinter(program) {
|
|
2646
|
+
return ENV_PRINTERS.has(basename(program));
|
|
2647
|
+
}
|
|
2189
2648
|
function printsEnv([program = "", ...args]) {
|
|
2190
2649
|
const flags = args.findIndex((arg) => !arg.startsWith("-") || SHELL_COMMAND_FLAG.test(arg));
|
|
2191
|
-
if (SHELLS2.has(program) && SHELL_COMMAND_FLAG.test(args[flags] ?? ""))
|
|
2192
|
-
return splitCommand(args[flags + 1] ?? "").some((piece) =>
|
|
2193
|
-
return
|
|
2650
|
+
if (SHELLS2.has(basename(program)) && SHELL_COMMAND_FLAG.test(args[flags] ?? ""))
|
|
2651
|
+
return splitCommand(args[flags + 1] ?? "").some((piece) => isEnvPrinter(tokenize(piece.command)[0] ?? ""));
|
|
2652
|
+
return isEnvPrinter(program);
|
|
2653
|
+
}
|
|
2654
|
+
function runPrintsEnv(after) {
|
|
2655
|
+
const entrypoint = after.find((_, i) => after[i - 1] === "--entrypoint") ?? after.find((word) => word.startsWith("--entrypoint="))?.slice("--entrypoint=".length);
|
|
2656
|
+
const command = after.slice(firstOperand(after, RUN_VALUE_OPTIONS) + 1);
|
|
2657
|
+
return printsEnv(entrypoint === undefined || entrypoint === "" ? command : [entrypoint, ...command]);
|
|
2194
2658
|
}
|
|
2195
2659
|
function dumpsContainerEnv(program, args) {
|
|
2196
2660
|
if (!DOCKER.has(program))
|
|
@@ -2200,9 +2664,11 @@ function dumpsContainerEnv(program, args) {
|
|
|
2200
2664
|
const isCompose = program === "docker-compose" || rest[0] === "compose";
|
|
2201
2665
|
if (program === "docker" && isCompose)
|
|
2202
2666
|
rest = afterOptions(rest.slice(1));
|
|
2203
|
-
const [subcommand = "", ...after] = rest;
|
|
2667
|
+
const [subcommand = "", ...after] = !isCompose && rest[0] === "container" && ["exec", "run"].includes(rest[1] ?? "") ? rest.slice(1) : rest;
|
|
2204
2668
|
if (subcommand === "exec")
|
|
2205
2669
|
return printsEnv(after.slice(firstOperand(after, EXEC_VALUE_OPTIONS) + 1));
|
|
2670
|
+
if (subcommand === "run")
|
|
2671
|
+
return runPrintsEnv(after);
|
|
2206
2672
|
if (isCompose)
|
|
2207
2673
|
return subcommand === "config" && !after.some((word) => CONFIG_LISTS.has(word));
|
|
2208
2674
|
if (subcommand !== "inspect" && (subcommand !== "container" || after[0] !== "inspect"))
|
|
@@ -2218,7 +2684,7 @@ function dumpsEnvironment(program, args, tokens) {
|
|
|
2218
2684
|
return isBare && args.some((arg) => DUMP_FLAGS.test(arg));
|
|
2219
2685
|
if (program === "set")
|
|
2220
2686
|
return args.length === 0;
|
|
2221
|
-
return program === "" && tokens.some((token) => token.replace(OPENER, "") === "env");
|
|
2687
|
+
return program === "" && tokens.some((token) => basename(token.replace(OPENER, "")) === "env");
|
|
2222
2688
|
}
|
|
2223
2689
|
function printsTrackedEnv(program, args) {
|
|
2224
2690
|
if (program !== "git")
|
|
@@ -2254,7 +2720,20 @@ function isWeak(value, before) {
|
|
|
2254
2720
|
return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16);
|
|
2255
2721
|
}
|
|
2256
2722
|
function keyed(names, value) {
|
|
2257
|
-
return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, "dgi");
|
|
2723
|
+
return new RegExp(`(?<![\\w-])["']?(?<name>(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?)["']?${KEY_VALUE_GAP}${value}`, "dgi");
|
|
2724
|
+
}
|
|
2725
|
+
var ANY_NAME = `(?<![\\w.-])["']?(?<name>[a-z_][\\w.-]{0,60})["']?`;
|
|
2726
|
+
var PASSWORD_NAME = new RegExp(`${STRONG_NAME}|pass|pwd`, "i");
|
|
2727
|
+
var SETTING_SUFFIX = /[_.-](?:TTL|FILE|PATH|DIR|NAME|URL|TIMEOUT|EXPIRY|EXPIRES|LIFETIME|LENGTH|ENABLED|ALGORITHM|HEADER|PREFIX|COUNT|MAX|MIN)$/i;
|
|
2728
|
+
var NUMBER = /^\d+$/;
|
|
2729
|
+
var COUNT_NAME = /(?:^|[_.-])(?:max|min|num)[_.-]|^tokens$/i;
|
|
2730
|
+
function isSetting(value, name) {
|
|
2731
|
+
return SETTING_SUFFIX.test(name) || COUNT_NAME.test(name) && NUMBER.test(value);
|
|
2732
|
+
}
|
|
2733
|
+
function isPlainNamed(value, before, name = "") {
|
|
2734
|
+
if (!isSecretName(name) || isSetting(value, name) || value.length < 4 || value.includes("-----BEGIN "))
|
|
2735
|
+
return true;
|
|
2736
|
+
return PASSWORD_NAME.test(name) ? isProse(value, before) : isWeak(value, before);
|
|
2258
2737
|
}
|
|
2259
2738
|
var TOKEN_FORMATS = [
|
|
2260
2739
|
{ kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
|
|
@@ -2275,10 +2754,13 @@ var TOKEN_FORMATS = [
|
|
|
2275
2754
|
{ kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
|
|
2276
2755
|
{ kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
|
|
2277
2756
|
{ kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
|
|
2278
|
-
{ kind: "password", pattern: keyed(STRONG_NAME, `([^\\s"'&;,]{4,})`), skip: isProse },
|
|
2279
|
-
{ kind: "password", pattern: keyed(WEAK_NAME, `([^\\s"'&;,]{4,})`), skip: isWeak },
|
|
2280
|
-
{ kind: "password", pattern: keyed(STRONG_NAME, `(["'])((?:\\\\.|(?!\\
|
|
2281
|
-
{ kind: "password", pattern: keyed(WEAK_NAME, `(["'])((?:\\\\.|(?!\\
|
|
2757
|
+
{ kind: "password", pattern: keyed(STRONG_NAME, `([^\\s"'&;,]{4,})`), skip: (value, before, name = "") => isSetting(value, name) || isProse(value, before) },
|
|
2758
|
+
{ kind: "password", pattern: keyed(WEAK_NAME, `([^\\s"'&;,]{4,})`), skip: (value, before, name = "") => isSetting(value, name) || isWeak(value, before) },
|
|
2759
|
+
{ kind: "password", pattern: keyed(STRONG_NAME, `(["'])((?:\\\\.|(?!\\2)[^\\\\\\n]){4,})\\2`), skip: (value, _, name = "") => isSetting(value, name) || isPlaceholder(value) },
|
|
2760
|
+
{ kind: "password", pattern: keyed(WEAK_NAME, `(["'])((?:\\\\.|(?!\\2)[^\\\\\\n]){4,})\\2`), skip: (value, before, name = "") => isSetting(value, name) || isWeak(value, before) },
|
|
2761
|
+
{ kind: "password", pattern: new RegExp(`${ANY_NAME}${KEY_VALUE_GAP}([^\\s"'&;,]{4,})`, "dgi"), skip: isPlainNamed },
|
|
2762
|
+
{ kind: "password", pattern: new RegExp(`${ANY_NAME}${KEY_VALUE_GAP}(["'])((?:\\\\.|(?!\\2)[^\\\\\\n]){4,})\\2`, "dgi"), skip: isPlainNamed },
|
|
2763
|
+
{ kind: "password", pattern: /^\s*(?:export\s+)?(?<name>[A-Za-z_]\w{0,60})=(?!["'])(\S(?:.*\S)?)/dg, skip: isPlainNamed }
|
|
2282
2764
|
];
|
|
2283
2765
|
|
|
2284
2766
|
// ../env/src/files.ts
|
|
@@ -2467,7 +2949,7 @@ var INTERPRETERS = new Set(["bun", "deno", "node", "python", "python3", "ruby",
|
|
|
2467
2949
|
var CODE_OPTIONS = new Set(["-e", "-c", "-p", "-E", "-pe", "-r", "--eval", "--print", "--command"]);
|
|
2468
2950
|
var CAN_REACH_FILES = /read|write|open|exec|spawn|system|popen|import|require|eval|load|fetch|glob|stream|source|getline|constructor|file(?!s\b)|\bcat\b|\b(?:Bun|Deno|fs|os|io|sh|bash|process|globalThis|window|Function|qx)\b|\$\s*[`({]|`/i;
|
|
2469
2951
|
var DECLARERS = new Set(["export", "declare", "local", "readonly", "typeset"]);
|
|
2470
|
-
var HARMLESS = new Set(["ev", "
|
|
2952
|
+
var HARMLESS = new Set(["ev", "ls", "stat", "test", "[", "[[", "touch"]);
|
|
2471
2953
|
var GIT_HARMLESS = new Set(["check-ignore", "ls-files", "status"]);
|
|
2472
2954
|
function variablesOf(command) {
|
|
2473
2955
|
const variables = new Map;
|
|
@@ -2528,7 +3010,7 @@ function namesEnv(piece, variables) {
|
|
|
2528
3010
|
}
|
|
2529
3011
|
|
|
2530
3012
|
// ../env/src/guard-pipes.ts
|
|
2531
|
-
var XARGS_SAFE = new Set(["ls", "stat", "wc", "test", "[", "touch", "echo", "printf", "basename", "dirname", "ev", "
|
|
3013
|
+
var XARGS_SAFE = new Set(["ls", "stat", "wc", "test", "[", "touch", "echo", "printf", "basename", "dirname", "ev", ""]);
|
|
2532
3014
|
var PARALLEL_VALUE_OPTIONS = new Set(["-j", "--jobs", "-P", "--max-procs", "-S", "--sshlogin", "-C", "--colsep", "-n", "--max-args", "-N", "-d", "--delimiter", "-E", "-I", "--timeout", "--delay", "--joblog", "--results", "--tmpdir", "-a", "--arg-file", "--halt", "--retries", "--tag-string"]);
|
|
2533
3015
|
var IDENTIFIER = /^[A-Z_]\w*$/i;
|
|
2534
3016
|
var READ_VALUE_OPTIONS = new Set(["-a", "-d", "-i", "-n", "-N", "-p", "-t", "-u"]);
|
|
@@ -2575,7 +3057,7 @@ function loopReadsListedEnv(pieces, index, variables) {
|
|
|
2575
3057
|
|
|
2576
3058
|
// ../env/src/guard.ts
|
|
2577
3059
|
var ENV_DUMP = /(?:console\.\w+|JSON\.stringify|Object\.(?:entries|keys|values)|print)\(\s*process\.env\s*[,)]/;
|
|
2578
|
-
var USE_EV = '.env files hold secrets that must never reach the transcript, so they are not read, edited or printed directly. Use `ev` instead: `ev list`, `ev get KEY` (masked), `ev grep <regex>` for the keys matching it, `ev show <rev>:<file>` for one at a git revision, `printf %s "$value" | ev set KEY [file]` (`--empty` for an empty value), `ev unset KEY`, `ev cp KEY --from .env --to .env.local`, `ev mv KEY --from .env --to .env.local`, `ev diff a b`, `ev missing`; and pipe output that may carry a secret through `redact`, as `docker compose exec <svc> printenv | redact` or `docker compose config | redact`. If `ev` is missing: `bun install -g @kaynooo/cli-env`.';
|
|
3060
|
+
var USE_EV = '.env files hold secrets that must never reach the transcript, so they are not read, edited or printed directly. Use `ev` instead: `ev list`, `ev get KEY` (masked), `ev grep <regex>` for the keys matching it, `ev show <rev>:<file>` for one at a git revision, `printf %s "$value" | ev set KEY [file]` (`--empty` for an empty value), `ev unset KEY`, `ev cp KEY --from .env --to .env.local`, `ev mv KEY --from .env --to .env.local`, `ev diff a b`, `ev missing`; and pipe output that may carry a secret through `ev redact`, as `docker compose exec <svc> printenv | ev redact` or `docker compose config | ev redact`. If `ev` is missing: `bun install -g @kaynooo/cli-env`.';
|
|
2579
3061
|
var USE_EV_SEARCH = "To search them, `ev grep <regex>` prints the matching keys, masked. `grep -l`, `-L` and `-c` (file names and counts) are allowed, and a tree-wide search can run as `rg <regex>`, which skips gitignored files, or `grep -r --exclude='.env*' <regex> .`.";
|
|
2580
3062
|
function touchingPieces(command, options = {}) {
|
|
2581
3063
|
const pieces = splitCommand(command);
|
|
@@ -2590,7 +3072,8 @@ function touchingPieces(command, options = {}) {
|
|
|
2590
3072
|
if (!isDump)
|
|
2591
3073
|
return false;
|
|
2592
3074
|
for (let at = index;pieces[at]?.separator === "|"; at++) {
|
|
2593
|
-
|
|
3075
|
+
const next = parseCommand(pieces[at + 1]?.command ?? "");
|
|
3076
|
+
if (next.program === "ev" && next.args[0] === "redact")
|
|
2594
3077
|
return false;
|
|
2595
3078
|
}
|
|
2596
3079
|
return true;
|
|
@@ -2791,12 +3274,152 @@ function wrap(command) {
|
|
|
2791
3274
|
// ../pkg/src/added.ts
|
|
2792
3275
|
import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync5 } from "fs";
|
|
2793
3276
|
import { dirname as dirname4, join as join6 } from "path";
|
|
2794
|
-
import
|
|
3277
|
+
import process17 from "process";
|
|
3278
|
+
|
|
3279
|
+
// ../pkg/src/pin.ts
|
|
3280
|
+
var LOCKFILES = [
|
|
3281
|
+
["bun.lock", "bun"],
|
|
3282
|
+
["bun.lockb", "bun"],
|
|
3283
|
+
["pnpm-lock.yaml", "pnpm"],
|
|
3284
|
+
["yarn.lock", "yarn"],
|
|
3285
|
+
["package-lock.json", "npm"]
|
|
3286
|
+
];
|
|
3287
|
+
var NPM_INSTALLS = ["install", "i", "in", "ins", "inst", "insta", "instal", "isnt", "isnta", "isntal", "isntall"];
|
|
3288
|
+
var NPM_TEST_INSTALLS = ["it", "install-test", "cit", "clean-install-test", "install-ci-test"];
|
|
3289
|
+
var ACTIONS = {
|
|
3290
|
+
bun: actions({ install: ["install", "i"], add: ["add", "a"], remove: ["remove", "rm"], update: ["update"] }),
|
|
3291
|
+
pnpm: actions({ install: ["install", "i"], add: ["add"], remove: ["remove", "rm"], update: ["update", "up"] }),
|
|
3292
|
+
yarn: new Map([...actions({ install: ["", "install"], add: ["add"], remove: ["remove"], update: ["upgrade"] }), ["upgrade-interactive", null], ["import", null]]),
|
|
3293
|
+
npm: new Map([...actions({
|
|
3294
|
+
install: NPM_INSTALLS,
|
|
3295
|
+
add: ["add"],
|
|
3296
|
+
frozen: ["ci", "clean-install", "ic", "install-clean", "isntall-clean"],
|
|
3297
|
+
remove: ["uninstall", "unlink", "remove", "rm", "r", "un"],
|
|
3298
|
+
update: ["update", "u", "up", "upgrade", "udpate"]
|
|
3299
|
+
}), ...NPM_TEST_INSTALLS.map((name) => [name, null])])
|
|
3300
|
+
};
|
|
3301
|
+
var COMMANDS = {
|
|
3302
|
+
bun: { install: "install", frozen: "install --frozen-lockfile", add: "add", remove: "remove", update: "update" },
|
|
3303
|
+
pnpm: { install: "install", frozen: "install --frozen-lockfile", add: "add", remove: "remove", update: "update" },
|
|
3304
|
+
yarn: { install: "install", add: "add", remove: "remove" },
|
|
3305
|
+
npm: { install: "install", frozen: "ci", add: "install", remove: "uninstall", update: "update" }
|
|
3306
|
+
};
|
|
3307
|
+
var OPTIONS = {
|
|
3308
|
+
bun: { dev: "--dev", exact: "--exact" },
|
|
3309
|
+
pnpm: { dev: "--save-dev", exact: "--save-exact" },
|
|
3310
|
+
yarn: { dev: "--dev", exact: "--exact" },
|
|
3311
|
+
npm: { dev: "--save-dev", exact: "--save-exact" }
|
|
3312
|
+
};
|
|
3313
|
+
var OPTION_FLAGS = new Map([
|
|
3314
|
+
["-D", "dev"],
|
|
3315
|
+
["--save-dev", "dev"],
|
|
3316
|
+
["--dev", "dev"],
|
|
3317
|
+
["-E", "exact"],
|
|
3318
|
+
["--save-exact", "exact"],
|
|
3319
|
+
["--exact", "exact"]
|
|
3320
|
+
]);
|
|
3321
|
+
var DIR_FLAGS = new Set(["--cwd", "-C", "--dir", "--prefix"]);
|
|
3322
|
+
var VALUE_FLAGS = new Set([...DIR_FLAGS, "--filter", "-F"]);
|
|
3323
|
+
var PLAIN_WORD2 = /^[\w=@./:+-]+$/;
|
|
3324
|
+
var AROUND_START = /^[\s(]*/;
|
|
3325
|
+
var AROUND_END = /[\s)]*$/;
|
|
3326
|
+
function actions(byAction) {
|
|
3327
|
+
return new Map(Object.entries(byAction).flatMap(([action, names]) => names.map((name) => [name, action])));
|
|
3328
|
+
}
|
|
3329
|
+
function isManager(program) {
|
|
3330
|
+
return Object.hasOwn(ACTIONS, program);
|
|
3331
|
+
}
|
|
3332
|
+
function translate(from, to, subcommand, rest) {
|
|
3333
|
+
const packages = rest.filter((arg) => !arg.startsWith("-"));
|
|
3334
|
+
const flags = rest.filter((arg) => arg.startsWith("-"));
|
|
3335
|
+
const listed = ACTIONS[from].get(subcommand);
|
|
3336
|
+
const action = listed === "install" && packages.length > 0 ? "add" : listed;
|
|
3337
|
+
const command = action ? COMMANDS[to][action] : undefined;
|
|
3338
|
+
if (!action || command === undefined || !packages.every((name) => PLAIN_WORD2.test(name)))
|
|
3339
|
+
return null;
|
|
3340
|
+
const options = [];
|
|
3341
|
+
for (const flag of flags) {
|
|
3342
|
+
const option = OPTION_FLAGS.get(flag) ?? (from === "bun" && flag === "-d" ? "dev" : undefined);
|
|
3343
|
+
if (option === undefined || action !== "add")
|
|
3344
|
+
return null;
|
|
3345
|
+
options.push(OPTIONS[to][option]);
|
|
3346
|
+
}
|
|
3347
|
+
return [to, command, ...options, ...packages].join(" ");
|
|
3348
|
+
}
|
|
3349
|
+
function installRequests(command, cwd, home) {
|
|
3350
|
+
const requests = [];
|
|
3351
|
+
const outer = [];
|
|
3352
|
+
for (const piece of splitCommand(command)) {
|
|
3353
|
+
const { opened, closed } = parenBalance(piece.command);
|
|
3354
|
+
for (let count = 0;count < opened; count++)
|
|
3355
|
+
outer.push(cwd);
|
|
3356
|
+
const request = requestOf(piece, cwd, home);
|
|
3357
|
+
if (typeof request === "string")
|
|
3358
|
+
cwd = request;
|
|
3359
|
+
else if (request !== undefined)
|
|
3360
|
+
requests.push(request);
|
|
3361
|
+
for (let count = 0;count < closed; count++)
|
|
3362
|
+
cwd = outer.pop() ?? cwd;
|
|
3363
|
+
}
|
|
3364
|
+
return requests;
|
|
3365
|
+
}
|
|
3366
|
+
function requestOf(piece, cwd, home) {
|
|
3367
|
+
const { program, args, assignments, isWrapped } = parseCommand(piece.command);
|
|
3368
|
+
if (program === "cd" && args[0] !== undefined)
|
|
3369
|
+
return resolvePath(cwd, args[0], home);
|
|
3370
|
+
if (!isManager(program))
|
|
3371
|
+
return;
|
|
3372
|
+
let dir = cwd;
|
|
3373
|
+
let subcommand = "";
|
|
3374
|
+
let rest = [];
|
|
3375
|
+
let hasLeadingFlag = false;
|
|
3376
|
+
for (let i = 0;i < args.length; i++) {
|
|
3377
|
+
const arg = args[i] ?? "";
|
|
3378
|
+
const equals = arg.indexOf("=");
|
|
3379
|
+
const flag = equals === -1 ? arg : arg.slice(0, equals);
|
|
3380
|
+
const value = equals === -1 ? undefined : arg.slice(equals + 1);
|
|
3381
|
+
const isLeading = subcommand === "";
|
|
3382
|
+
if (DIR_FLAGS.has(flag) && value !== undefined && value !== "") {
|
|
3383
|
+
dir = resolvePath(cwd, value, home);
|
|
3384
|
+
} else if (VALUE_FLAGS.has(arg)) {
|
|
3385
|
+
if (DIR_FLAGS.has(arg) && args[i + 1] !== undefined)
|
|
3386
|
+
dir = resolvePath(cwd, args[i + 1] ?? "", home);
|
|
3387
|
+
i++;
|
|
3388
|
+
} else if (isLeading && !arg.startsWith("-")) {
|
|
3389
|
+
subcommand = arg;
|
|
3390
|
+
rest = args.slice(i + 1);
|
|
3391
|
+
continue;
|
|
3392
|
+
}
|
|
3393
|
+
hasLeadingFlag ||= isLeading;
|
|
3394
|
+
}
|
|
3395
|
+
return ACTIONS[program].has(subcommand) ? { piece, program, subcommand, rest, dir, assignments, isRewritable: !hasLeadingFlag && !isWrapped && piece.command === piece.text } : undefined;
|
|
3396
|
+
}
|
|
3397
|
+
function bareCommand(text) {
|
|
3398
|
+
return text.replace(AROUND_START, "").replace(AROUND_END, "");
|
|
3399
|
+
}
|
|
3400
|
+
function mismatchFor(request, pinned) {
|
|
3401
|
+
const { piece, program, subcommand, rest, isRewritable, assignments } = request;
|
|
3402
|
+
if (!pinned || pinned.managers.has(program))
|
|
3403
|
+
return null;
|
|
3404
|
+
const expected = [...pinned.managers];
|
|
3405
|
+
const only = expected.length === 1 ? expected[0] : undefined;
|
|
3406
|
+
const canRewrite = only !== undefined && isRewritable && assignments.every((word) => PLAIN_WORD2.test(word));
|
|
3407
|
+
const translated = canRewrite ? translate(program, only, subcommand, rest) : null;
|
|
3408
|
+
const leading = AROUND_START.exec(piece.text)?.[0] ?? "";
|
|
3409
|
+
const trailing = AROUND_END.exec(piece.text)?.[0] ?? "";
|
|
3410
|
+
return {
|
|
3411
|
+
piece,
|
|
3412
|
+
rewrite: translated === null ? null : `${leading}${[...assignments, translated].join(" ")}${trailing}`,
|
|
3413
|
+
reason: `${pinned.dir} is pinned to ${expected.join(" or ")} by its lockfile, so \`${`${program} ${subcommand}`.trim()}\` would install with the wrong package manager.`
|
|
3414
|
+
};
|
|
3415
|
+
}
|
|
3416
|
+
|
|
3417
|
+
// ../pkg/src/added.ts
|
|
2795
3418
|
var REDIRECT2 = /^\d*[<>]/;
|
|
2796
3419
|
var BARE_REDIRECT = /^\d*(?:[<>]|>>)$/;
|
|
2797
3420
|
var ADDS = {
|
|
2798
3421
|
bun: new Set(["add", "a", "install", "i"]),
|
|
2799
|
-
npm: new Set([
|
|
3422
|
+
npm: new Set([...NPM_INSTALLS, ...NPM_TEST_INSTALLS, "add"]),
|
|
2800
3423
|
pnpm: new Set(["add", "i", "install"]),
|
|
2801
3424
|
yarn: new Set(["add"])
|
|
2802
3425
|
};
|
|
@@ -2808,8 +3431,9 @@ var RUNS = {
|
|
|
2808
3431
|
};
|
|
2809
3432
|
var RUNNERS = new Set(["bunx", "npx"]);
|
|
2810
3433
|
var PACKAGE_FLAGS = new Set(["-p", "--package"]);
|
|
2811
|
-
var
|
|
2812
|
-
var
|
|
3434
|
+
var VALUE_FLAGS2 = new Set(["--cwd", "--filter", "-F", "-c", "--call", "--workspace", "--registry", "--prefix", "-C", "--dir", "--config", "--cache-dir", "--loglevel", "--tag", "--save-prefix", "--userconfig", "--omit", "--include", "--fetch-timeout", "--fetch-retries", "--install-strategy", "--cache", "--linker", ...PACKAGE_FLAGS]);
|
|
3435
|
+
var OWN_VALUE_FLAGS = { npm: new Set(["-w"]) };
|
|
3436
|
+
var NOT_REGISTRY = /^(?:[./]|~(?:\/|$)|file:|link:|portal:|workspace:|catalog:|git[+:]|github:|gitlab:|bitbucket:|https?:)|\.tgz$|^[\w.-]+\/[\w.-]+(?:#.*)?$/;
|
|
2813
3437
|
var NPM_ALIAS = /^(?:@[^/]+\/)?[^@]+@npm:(.+)$/;
|
|
2814
3438
|
var PUBLISH = /\b(?:ft|cli\.ts)\s+release\b|\b(?:bun|npm|pnpm|yarn)\s+publish\b|\bjust\s+(?:patch|minor|major)\b/;
|
|
2815
3439
|
var EXACT_SPEC = /^(?:@[^/]+\/)?[^@]+@\d+\.\d+\.\d+(?:[-+][\w.+-]+)?$/;
|
|
@@ -2823,7 +3447,7 @@ function manifestName(folder) {
|
|
|
2823
3447
|
}
|
|
2824
3448
|
function ownPackages() {
|
|
2825
3449
|
const names = new Set;
|
|
2826
|
-
let folder =
|
|
3450
|
+
let folder = process17.cwd();
|
|
2827
3451
|
while (true) {
|
|
2828
3452
|
const name = manifestName(folder);
|
|
2829
3453
|
if (name !== undefined)
|
|
@@ -2862,13 +3486,17 @@ function piecePackages(program, sub, args, rest) {
|
|
|
2862
3486
|
return runnerPackages(rest);
|
|
2863
3487
|
if (!ADDS[program]?.has(sub))
|
|
2864
3488
|
return [];
|
|
2865
|
-
return rest.flatMap((word, index) => isSkipped(word, rest[index - 1] ?? "") ? [] : registryName(word));
|
|
3489
|
+
return rest.flatMap((word, index) => isSkipped(word, rest[index - 1] ?? "", program) ? [] : registryName(word));
|
|
2866
3490
|
}
|
|
2867
|
-
function isSkipped(word, previous) {
|
|
2868
|
-
return word.startsWith("-") || REDIRECT2.test(word) ||
|
|
3491
|
+
function isSkipped(word, previous, program = "") {
|
|
3492
|
+
return word.startsWith("-") || REDIRECT2.test(word) || VALUE_FLAGS2.has(previous) || OWN_VALUE_FLAGS[program]?.has(previous) === true || BARE_REDIRECT.test(previous);
|
|
2869
3493
|
}
|
|
2870
3494
|
function registryName(word) {
|
|
2871
|
-
|
|
3495
|
+
const at = word.indexOf("@", 1);
|
|
3496
|
+
const spec = at === -1 ? word : word.slice(at + 1);
|
|
3497
|
+
if (NOT_REGISTRY.test(word) || at !== -1 && !spec.startsWith("npm:") && NOT_REGISTRY.test(spec))
|
|
3498
|
+
return [];
|
|
3499
|
+
return [NPM_ALIAS.exec(word)?.[1] ?? word];
|
|
2872
3500
|
}
|
|
2873
3501
|
function runnerPackages(words) {
|
|
2874
3502
|
const named = [];
|
|
@@ -2886,133 +3514,54 @@ function runnerPackages(words) {
|
|
|
2886
3514
|
return named.flatMap(registryName);
|
|
2887
3515
|
}
|
|
2888
3516
|
|
|
2889
|
-
// ../pkg/src/pin.ts
|
|
2890
|
-
var LOCKFILES = [
|
|
2891
|
-
["bun.lock", "bun"],
|
|
2892
|
-
["bun.lockb", "bun"],
|
|
2893
|
-
["pnpm-lock.yaml", "pnpm"],
|
|
2894
|
-
["yarn.lock", "yarn"],
|
|
2895
|
-
["package-lock.json", "npm"]
|
|
2896
|
-
];
|
|
2897
|
-
var ACTIONS = {
|
|
2898
|
-
bun: actions({ install: ["install", "i"], add: ["add", "a"], remove: ["remove", "rm"], update: ["update"] }),
|
|
2899
|
-
pnpm: actions({ install: ["install", "i"], add: ["add"], remove: ["remove", "rm"], update: ["update", "up"] }),
|
|
2900
|
-
yarn: new Map([...actions({ install: ["", "install"], add: ["add"], remove: ["remove"], update: ["upgrade"] }), ["upgrade-interactive", null], ["import", null]]),
|
|
2901
|
-
npm: actions({
|
|
2902
|
-
install: ["install", "i", "in", "ins", "inst", "insta", "instal", "isnt", "isnta", "isntal", "isntall"],
|
|
2903
|
-
add: ["add"],
|
|
2904
|
-
frozen: ["ci", "clean-install", "ic", "install-clean", "isntall-clean"],
|
|
2905
|
-
remove: ["uninstall", "unlink", "remove", "rm", "r", "un"],
|
|
2906
|
-
update: ["update", "u", "up", "upgrade", "udpate"]
|
|
2907
|
-
})
|
|
2908
|
-
};
|
|
2909
|
-
var COMMANDS = {
|
|
2910
|
-
bun: { install: "install", frozen: "install --frozen-lockfile", add: "add", remove: "remove", update: "update" },
|
|
2911
|
-
pnpm: { install: "install", frozen: "install --frozen-lockfile", add: "add", remove: "remove", update: "update" },
|
|
2912
|
-
yarn: { install: "install", add: "add", remove: "remove" },
|
|
2913
|
-
npm: { install: "install", frozen: "ci", add: "install", remove: "uninstall", update: "update" }
|
|
2914
|
-
};
|
|
2915
|
-
var OPTIONS = {
|
|
2916
|
-
bun: { dev: "--dev", exact: "--exact" },
|
|
2917
|
-
pnpm: { dev: "--save-dev", exact: "--save-exact" },
|
|
2918
|
-
yarn: { dev: "--dev", exact: "--exact" },
|
|
2919
|
-
npm: { dev: "--save-dev", exact: "--save-exact" }
|
|
2920
|
-
};
|
|
2921
|
-
var OPTION_FLAGS = new Map([
|
|
2922
|
-
["-D", "dev"],
|
|
2923
|
-
["--save-dev", "dev"],
|
|
2924
|
-
["--dev", "dev"],
|
|
2925
|
-
["-E", "exact"],
|
|
2926
|
-
["--save-exact", "exact"],
|
|
2927
|
-
["--exact", "exact"]
|
|
2928
|
-
]);
|
|
2929
|
-
var DIR_FLAGS = new Set(["--cwd", "-C", "--dir", "--prefix"]);
|
|
2930
|
-
var VALUE_FLAGS2 = new Set([...DIR_FLAGS, "--filter", "-F"]);
|
|
2931
|
-
var PLAIN_WORD2 = /^[\w=@./:+-]+$/;
|
|
2932
|
-
function actions(byAction) {
|
|
2933
|
-
return new Map(Object.entries(byAction).flatMap(([action, names]) => names.map((name) => [name, action])));
|
|
2934
|
-
}
|
|
2935
|
-
function isManager(program) {
|
|
2936
|
-
return Object.hasOwn(ACTIONS, program);
|
|
2937
|
-
}
|
|
2938
|
-
function translate(from, to, subcommand, rest) {
|
|
2939
|
-
const packages = rest.filter((arg) => !arg.startsWith("-"));
|
|
2940
|
-
const flags = rest.filter((arg) => arg.startsWith("-"));
|
|
2941
|
-
const listed = ACTIONS[from].get(subcommand);
|
|
2942
|
-
const action = listed === "install" && packages.length > 0 ? "add" : listed;
|
|
2943
|
-
const command = action ? COMMANDS[to][action] : undefined;
|
|
2944
|
-
if (!action || command === undefined || !packages.every((name) => PLAIN_WORD2.test(name)))
|
|
2945
|
-
return null;
|
|
2946
|
-
const options = [];
|
|
2947
|
-
for (const flag of flags) {
|
|
2948
|
-
const option = OPTION_FLAGS.get(flag) ?? (from === "bun" && flag === "-d" ? "dev" : undefined);
|
|
2949
|
-
if (option === undefined || action !== "add")
|
|
2950
|
-
return null;
|
|
2951
|
-
options.push(OPTIONS[to][option]);
|
|
2952
|
-
}
|
|
2953
|
-
return [to, command, ...options, ...packages].join(" ");
|
|
2954
|
-
}
|
|
2955
|
-
function installRequests(command, cwd, home) {
|
|
2956
|
-
const requests = [];
|
|
2957
|
-
for (const piece of splitCommand(command)) {
|
|
2958
|
-
const { program, args, assignments, isWrapped } = parseCommand(piece.command);
|
|
2959
|
-
if (program === "cd" && args[0] !== undefined) {
|
|
2960
|
-
cwd = resolvePath(cwd, args[0], home);
|
|
2961
|
-
continue;
|
|
2962
|
-
}
|
|
2963
|
-
if (!isManager(program))
|
|
2964
|
-
continue;
|
|
2965
|
-
let dir = cwd;
|
|
2966
|
-
let subcommand = "";
|
|
2967
|
-
let rest = [];
|
|
2968
|
-
let hasLeadingFlag = false;
|
|
2969
|
-
for (let i = 0;i < args.length; i++) {
|
|
2970
|
-
const arg = args[i] ?? "";
|
|
2971
|
-
const equals = arg.indexOf("=");
|
|
2972
|
-
const flag = equals === -1 ? arg : arg.slice(0, equals);
|
|
2973
|
-
const value = equals === -1 ? undefined : arg.slice(equals + 1);
|
|
2974
|
-
if (DIR_FLAGS.has(flag) && value !== undefined && value !== "") {
|
|
2975
|
-
dir = resolvePath(cwd, value, home);
|
|
2976
|
-
} else if (VALUE_FLAGS2.has(arg)) {
|
|
2977
|
-
if (DIR_FLAGS.has(arg) && args[i + 1] !== undefined)
|
|
2978
|
-
dir = resolvePath(cwd, args[i + 1] ?? "", home);
|
|
2979
|
-
i++;
|
|
2980
|
-
} else if (!arg.startsWith("-")) {
|
|
2981
|
-
subcommand = arg;
|
|
2982
|
-
rest = args.slice(i + 1);
|
|
2983
|
-
break;
|
|
2984
|
-
}
|
|
2985
|
-
hasLeadingFlag = true;
|
|
2986
|
-
}
|
|
2987
|
-
if (ACTIONS[program].has(subcommand))
|
|
2988
|
-
requests.push({ piece, program, subcommand, rest, dir, assignments, isRewritable: !hasLeadingFlag && !isWrapped && piece.command === piece.text });
|
|
2989
|
-
}
|
|
2990
|
-
return requests;
|
|
2991
|
-
}
|
|
2992
|
-
function mismatchFor(request, pinned) {
|
|
2993
|
-
const { piece, program, subcommand, rest, isRewritable, assignments } = request;
|
|
2994
|
-
if (!pinned || pinned.managers.has(program))
|
|
2995
|
-
return null;
|
|
2996
|
-
const expected = [...pinned.managers];
|
|
2997
|
-
const only = expected.length === 1 ? expected[0] : undefined;
|
|
2998
|
-
const canRewrite = only !== undefined && isRewritable && assignments.every((word) => PLAIN_WORD2.test(word));
|
|
2999
|
-
const translated = canRewrite ? translate(program, only, subcommand, rest) : null;
|
|
3000
|
-
const leading = piece.text.slice(0, piece.text.length - piece.text.trimStart().length);
|
|
3001
|
-
const trailing = piece.text.slice(piece.text.trimEnd().length);
|
|
3002
|
-
return {
|
|
3003
|
-
piece,
|
|
3004
|
-
rewrite: translated === null ? null : `${leading}${[...assignments, translated].join(" ")}${trailing}`,
|
|
3005
|
-
reason: `${pinned.dir} is pinned to ${expected.join(" or ")} by its lockfile, so \`${`${program} ${subcommand}`.trim()}\` would install with the wrong package manager.`
|
|
3006
|
-
};
|
|
3007
|
-
}
|
|
3008
|
-
|
|
3009
3517
|
// src/git.ts
|
|
3010
|
-
var GLOBAL_VALUE_OPTIONS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env"]);
|
|
3518
|
+
var GLOBAL_VALUE_OPTIONS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env", "--attr-source"]);
|
|
3011
3519
|
var READ_ONLY_STASH = new Set(["list", "show"]);
|
|
3012
3520
|
var WHOLE_TREE = new Set(["-A", "--all", "-u", "--update", "--no-ignore-removal", ".", "./", ":/", "*"]);
|
|
3013
3521
|
var COMMIT_VALUE_SHORTS = new Set(["m", "F", "c", "C", "t"]);
|
|
3522
|
+
var COMMIT_ATTACHED_SHORTS = new Set(["u", "S"]);
|
|
3014
3523
|
var COMMIT_VALUE_LONGS = new Set(["--message", "--file", "--reuse-message", "--reedit-message", "--template", "--author", "--date", "--fixup", "--squash", "--cleanup", "--trailer", "--pathspec-from-file"]);
|
|
3524
|
+
var LONG_OPTIONS = {
|
|
3525
|
+
add: ["--all", "--update", "--no-ignore-removal", "--dry-run", "--patch", "--intent-to-add", "--force", "--pathspec-from-file"],
|
|
3526
|
+
branch: ["--delete", "--force", "--move", "--copy", "--list", "--show-current"],
|
|
3527
|
+
checkout: ["--force", "--patch", "--ours", "--theirs", "--merge", "--detach", "--orphan", "--track", "--quiet", "--progress", "--pathspec-from-file"],
|
|
3528
|
+
clean: ["--force", "--dry-run", "--quiet", "--exclude", "--interactive"],
|
|
3529
|
+
commit: ["--all", "--signoff", ...COMMIT_VALUE_LONGS, "--amend", "--no-verify", "--edit", "--no-edit", "--quiet", "--patch", "--include", "--only", "--interactive", "--dry-run", "--allow-empty", "--allow-empty-message", "--reset-author", "--gpg-sign", "--status", "--verbose"],
|
|
3530
|
+
push: ["--force", "--mirror", "--delete", "--tags", "--follow-tags", "--force-with-lease", "--force-if-includes", "--atomic", "--all", "--branches", "--prune", "--dry-run", "--set-upstream", "--no-verify", "--porcelain", "--quiet", "--verbose", "--progress", "--push-option", "--repo", "--recurse-submodules", "--signed", "--thin"],
|
|
3531
|
+
reset: ["--hard", "--soft", "--mixed", "--merge", "--keep", "--patch", "--quiet", "--recurse-submodules", "--pathspec-from-file"],
|
|
3532
|
+
restore: ["--staged", "--worktree", "--patch", "--source", "--ours", "--theirs", "--merge", "--quiet", "--progress", "--overlay", "--no-overlay", "--ignore-unmerged", "--pathspec-from-file"],
|
|
3533
|
+
rm: ["--cached", "--dry-run", "--force", "--quiet", "--ignore-unmatch", "--sparse", "--pathspec-from-file"],
|
|
3534
|
+
switch: ["--force", "--discard-changes", "--create", "--force-create", "--detach", "--guess", "--merge", "--orphan", "--track", "--quiet", "--progress"]
|
|
3535
|
+
};
|
|
3015
3536
|
var SHORT_CLUSTER = /^-[A-Z]+$/i;
|
|
3537
|
+
var LONG_VALUES = new Set([...COMMIT_VALUE_LONGS, "--source", "--push-option", "--repo", "--exclude"]);
|
|
3538
|
+
function takesNextWord(name, word) {
|
|
3539
|
+
if (name !== "commit" || !SHORT_CLUSTER.test(word))
|
|
3540
|
+
return false;
|
|
3541
|
+
const letters = [...word.slice(1)];
|
|
3542
|
+
const at = letters.findIndex((letter) => COMMIT_VALUE_SHORTS.has(letter) || COMMIT_ATTACHED_SHORTS.has(letter));
|
|
3543
|
+
return at === letters.length - 1 && COMMIT_VALUE_SHORTS.has(letters[at] ?? "");
|
|
3544
|
+
}
|
|
3545
|
+
function fullLongOptions(name, rest) {
|
|
3546
|
+
const known = LONG_OPTIONS[name] ?? [];
|
|
3547
|
+
const words = [...rest];
|
|
3548
|
+
for (let i = 0;i < words.length; i++) {
|
|
3549
|
+
const word = words[i] ?? "";
|
|
3550
|
+
if (word === "--")
|
|
3551
|
+
break;
|
|
3552
|
+
if (!word.startsWith("--")) {
|
|
3553
|
+
if (takesNextWord(name, word))
|
|
3554
|
+
i++;
|
|
3555
|
+
continue;
|
|
3556
|
+
}
|
|
3557
|
+
const [spelled = "", ...value] = word.split("=");
|
|
3558
|
+
const option = known.includes(spelled) || spelled.length <= 2 ? spelled : known.find((each) => each.startsWith(spelled)) ?? spelled;
|
|
3559
|
+
words[i] = value.length > 0 ? `${option}=${value.join("=")}` : option;
|
|
3560
|
+
if (value.length === 0 && LONG_VALUES.has(option))
|
|
3561
|
+
i++;
|
|
3562
|
+
}
|
|
3563
|
+
return words;
|
|
3564
|
+
}
|
|
3016
3565
|
var SHORT_OPTIONS = /^-[A-Z]/i;
|
|
3017
3566
|
var STAGES_ALL = /[Au]/;
|
|
3018
3567
|
var ALL_TAGS = new Set(["--tags", "--follow-tags"]);
|
|
@@ -3021,7 +3570,7 @@ var RISKY_CONFIG = /^(?:alias\.|core\.(?:sshcommand|hookspath|pager|editor|fsmon
|
|
|
3021
3570
|
var RISKY_ENV = /^GIT_(?:CONFIG_(?:COUNT|PARAMETERS)|EXTERNAL_DIFF|ASKPASS|PROXY_COMMAND|PAGER)=/;
|
|
3022
3571
|
var READS_CONFIG = new Set(["--get", "--get-all", "--get-regexp", "--list", "-l", "--unset", "--unset-all", "--show-origin", "--show-scope"]);
|
|
3023
3572
|
var STAGE_BY_PATH = `Stage by path: the tree carries unrelated work and peer sessions edit it live. ${USE_GC}`;
|
|
3024
|
-
var STASH = "Never `git stash`: a pop with nothing saved applies someone else's old stash. To prove a test fails without your change, `proof --keep <test> -- <cmd>` runs it at HEAD in a temporary worktree and again here; `base -- <cmd>` runs any command at HEAD (`--ref <rev>` another commit),
|
|
3573
|
+
var STASH = "Never `git stash`: a pop with nothing saved applies someone else's old stash. To prove a test fails without your change, `base proof --keep <test> -- <cmd>` runs it at HEAD in a temporary worktree and again here; `base -- <cmd>` runs any command at HEAD (`--ref <rev>` another commit), its changes left out of the run. To set edits aside before a cherry-pick, a rebase or a checkout, commit them with `gc` first, or do the other work in `git worktree add`.";
|
|
3025
3574
|
var ADD_ALL = `\`git add\` over the whole tree is refused. ${STAGE_BY_PATH}`;
|
|
3026
3575
|
var COMMIT_ALL = `\`git commit -a\` stages the whole tree and is refused. ${STAGE_BY_PATH}`;
|
|
3027
3576
|
var PUSH = "`git push` and `gp` run only when the user asked for a push in their latest prompt: say the commit is ready and let them ask.";
|
|
@@ -3029,7 +3578,7 @@ var CONFIG_OVERRIDE = "Never set git config that runs a program or defines a com
|
|
|
3029
3578
|
var TAGS_APART = "A tag goes out with its branch in one `git push --atomic origin <branch> <tag>`, never a separate `git push --tags`.";
|
|
3030
3579
|
function gitCommandOf(program, args) {
|
|
3031
3580
|
if (program === "gp")
|
|
3032
|
-
return { name: "push", rest: args.includes("--") ? args.slice(args.indexOf("--") + 1) : [] };
|
|
3581
|
+
return { name: "push", rest: fullLongOptions("push", args.includes("--") ? args.slice(args.indexOf("--") + 1) : []) };
|
|
3033
3582
|
return program === "git" ? subcommandOf(args) : undefined;
|
|
3034
3583
|
}
|
|
3035
3584
|
function subcommandOf(args) {
|
|
@@ -3038,7 +3587,7 @@ function subcommandOf(args) {
|
|
|
3038
3587
|
if (GLOBAL_VALUE_OPTIONS.has(arg))
|
|
3039
3588
|
i++;
|
|
3040
3589
|
else if (!arg.startsWith("-"))
|
|
3041
|
-
return { name: arg, rest: args.slice(i + 1) };
|
|
3590
|
+
return { name: arg, rest: fullLongOptions(arg, args.slice(i + 1)) };
|
|
3042
3591
|
}
|
|
3043
3592
|
return { name: "", rest: [] };
|
|
3044
3593
|
}
|
|
@@ -3087,6 +3636,8 @@ function commitsAll(args) {
|
|
|
3087
3636
|
for (const [index, flag] of [...arg.slice(1)].entries()) {
|
|
3088
3637
|
if (flag === "a")
|
|
3089
3638
|
return true;
|
|
3639
|
+
if (COMMIT_ATTACHED_SHORTS.has(flag))
|
|
3640
|
+
break;
|
|
3090
3641
|
if (!COMMIT_VALUE_SHORTS.has(flag))
|
|
3091
3642
|
continue;
|
|
3092
3643
|
if (index === arg.length - 2)
|
|
@@ -3182,6 +3733,8 @@ function sourceOf(args, text) {
|
|
|
3182
3733
|
if (!SHORT_OPTIONS.test(arg))
|
|
3183
3734
|
continue;
|
|
3184
3735
|
for (const [index, flag] of [...arg.slice(1)].entries()) {
|
|
3736
|
+
if (COMMIT_ATTACHED_SHORTS.has(flag))
|
|
3737
|
+
break;
|
|
3185
3738
|
if (flag === "s")
|
|
3186
3739
|
source.hasTrailerFlag = true;
|
|
3187
3740
|
if (!COMMIT_VALUE_SHORTS.has(flag))
|
|
@@ -3275,6 +3828,7 @@ var RECURSIVE_LETTER = /r/i;
|
|
|
3275
3828
|
var HOME_PREFIX = /^(?:~|\$HOME|\$\{HOME(?::?[-?=+][^}]*)?\}?)(?=\/|$)/;
|
|
3276
3829
|
var CURRENT_DIRECTORY = /^(?:\$PWD|\$\{PWD\}?|\$\(pwd\)?|`pwd`?)(?=\/|$)/;
|
|
3277
3830
|
var ABSOLUTE_HOME = /^(?:home\/[^/]+|root)\/([^/]+)$/;
|
|
3831
|
+
var SYSTEM_FOLDERS = new Set(["bin", "boot", "dev", "etc", "home", "lib", "lib32", "lib64", "media", "mnt", "opt", "proc", "run", "sbin", "srv", "sys", "usr", "var"]);
|
|
3278
3832
|
var EXEC_FLAGS = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
3279
3833
|
var REMOVER = /(?:^|\/)rm$/;
|
|
3280
3834
|
var TRAILING_SLASH = /\/$/;
|
|
@@ -3283,7 +3837,7 @@ var INTERPRETERS2 = new Set(["python", "node", "bun", "perl", "ruby"]);
|
|
|
3283
3837
|
var VERSION_SUFFIX = /[\d.]+$/;
|
|
3284
3838
|
var PASS_THROUGH = new Set(["tee", "cat", "pv", "tr", "sed"]);
|
|
3285
3839
|
var COMMIT_FIRST = "Commit what you want to keep with `gc` first.";
|
|
3286
|
-
var SAFE_BASE = "`base -- <cmd>` runs a command at HEAD
|
|
3840
|
+
var SAFE_BASE = "`base -- <cmd>` runs a command at HEAD in a temporary worktree, its changes left out, and `git worktree add` gives a clean tree.";
|
|
3287
3841
|
var RESET_HARD = `Never \`git reset --hard\`: it throws away uncommitted work, and peer sessions edit this tree live. ${COMMIT_FIRST} \`git reset --soft\` or \`--mixed\` moves HEAD and keeps the changes; ${SAFE_BASE}`;
|
|
3288
3842
|
var DISCARD_TREE = `Never discard the whole working tree (\`git checkout -- .\`, \`git checkout -f\`, \`git restore .\`, \`git rm -r .\`, \`git switch -f\`): it throws away uncommitted work, and peer sessions edit this tree live. ${COMMIT_FIRST} Restore named paths only, and \`git restore --staged\` just unstages. ${SAFE_BASE}`;
|
|
3289
3843
|
var CLEAN = `Never \`git clean -f\`: it deletes untracked files that peer sessions or the user have not committed yet. \`git clean -n\` lists what it would remove; delete named files yourself.`;
|
|
@@ -3292,12 +3846,17 @@ var REMOTE_DELETE = "Never delete a remote branch or tag with `git push --delete
|
|
|
3292
3846
|
var BRANCH_DELETE = "Never `git branch -D`: it drops commits no other branch holds. `git branch -d` deletes a merged branch only; ask the user before dropping an unmerged one.";
|
|
3293
3847
|
var REBASE = `Never start a \`git rebase\`: it rewrites history and stops halfway on conflicts in a tree others edit. ${COMMIT_FIRST} \`git cherry-pick\` or \`git merge\` keep history, and \`git worktree add\` gives a clean tree to do it in. \`--continue\` and \`--abort\` stay allowed.`;
|
|
3294
3848
|
var REWRITE_HISTORY = "Never `git filter-branch` or `git filter-repo`: they rewrite every commit of the repository. Ask the user to run it themselves.";
|
|
3295
|
-
var BROAD_RM = "Never `rm -r` on `/`, `~`, `$HOME
|
|
3849
|
+
var BROAD_RM = "Never `rm -r` on `/`, `~`, `$HOME` or the home by its path, `.`, `..`, `*`, a top-level directory or a system folder's child such as `/usr/lib`: it deletes far more than the task. Name the exact directory, such as `dist` or `node_modules`.";
|
|
3296
3850
|
var PROTECTED_RM = "Never `rm -r` on a `.git` directory, on `~/Workspace` itself or on a dot-directory of the home (`~/.ssh`, `$HOME/.claude`, `~/.config`): it deletes a repository's whole history, every project, or the credentials and settings of the machine. Remove the named files inside, or ask the user to run it.";
|
|
3297
|
-
var FIND_DELETE_HOME = 'Never `find ~ -delete` or `find / -exec rm` (also `$HOME`): it deletes matches across the whole home or disk. Start `find` in the project folder or `.` and name the pattern, such as `find . -name "*.tmp" -delete`.';
|
|
3851
|
+
var FIND_DELETE_HOME = 'Never `find ~ -delete` or `find / -exec rm` (also `$HOME` or the home by its path): it deletes matches across the whole home or disk. Start `find` in the project folder or `.` and name the pattern, such as `find . -name "*.tmp" -delete`.';
|
|
3298
3852
|
var REFLOG_EXPIRE = "Never `git reflog expire`, `git gc --prune=now` or `git update-ref -d`: they drop the reflog, unreachable commits or a ref, the only way back from a bad reset or rebase. Let git prune on its own schedule, and ask the user to run one when it is really wanted.";
|
|
3299
3853
|
var DOCKER_PRUNE_ALL = "Never `docker system prune -a` (`--all`): it removes every image not used by a running container, volumes of other projects' stacks included with --volumes. `docker system prune` without -a drops only dangling data; remove named images with `docker rmi`.";
|
|
3300
|
-
var
|
|
3854
|
+
var PINNED_RUN = "`dl <url>` downloads it and prints its path and sha256; read that file, then `dl <url> --exec --sha256 <sha>` runs exactly what was read.";
|
|
3855
|
+
var PIPE_TO_SHELL = `Never run what \`curl\`/\`wget\` fetches straight in a shell (\`| sh\`, \`bash <(curl ...)\`, \`eval "$(curl ...)"\`): it runs code nobody read. ${PINNED_RUN} Or hand the command to the user.`;
|
|
3856
|
+
var UNPINNED_EXEC = `Never \`dl --exec --yes\` a script no \`--sha256\` or \`--sums\` pins: it runs code nobody read. ${PINNED_RUN}`;
|
|
3857
|
+
function isLongPrefix(arg, option) {
|
|
3858
|
+
return arg.length > 2 && option.startsWith(arg);
|
|
3859
|
+
}
|
|
3301
3860
|
function hasOption(args, long, shorts) {
|
|
3302
3861
|
for (const arg of args) {
|
|
3303
3862
|
if (arg === "--")
|
|
@@ -3307,7 +3866,7 @@ function hasOption(args, long, shorts) {
|
|
|
3307
3866
|
}
|
|
3308
3867
|
return false;
|
|
3309
3868
|
}
|
|
3310
|
-
function isBroadPath(path) {
|
|
3869
|
+
function isBroadPath(path, homePath) {
|
|
3311
3870
|
const arg = path.replace(CURRENT_DIRECTORY, ".");
|
|
3312
3871
|
const home = HOME_PREFIX.exec(arg);
|
|
3313
3872
|
const isAbsolute = home === null && arg.startsWith("/");
|
|
@@ -3324,11 +3883,14 @@ function isBroadPath(path) {
|
|
|
3324
3883
|
parts.pop();
|
|
3325
3884
|
if (home !== null)
|
|
3326
3885
|
return parts.length === 0;
|
|
3327
|
-
|
|
3886
|
+
if (!isAbsolute)
|
|
3887
|
+
return parts.every((part) => part === "..");
|
|
3888
|
+
const isHome = homePath !== undefined && `/${parts.join("/")}` === homePath.replace(TRAILING_SLASH, "");
|
|
3889
|
+
return parts.length <= 1 || isHome || parts.length === 2 && SYSTEM_FOLDERS.has(parts[0] ?? "");
|
|
3328
3890
|
}
|
|
3329
3891
|
function recursiveTargets(args) {
|
|
3330
3892
|
const options = args.slice(0, args.includes("--") ? args.indexOf("--") : args.length);
|
|
3331
|
-
const isRecursive = options.some((arg) => arg
|
|
3893
|
+
const isRecursive = options.some((arg) => isLongPrefix(arg, "--recursive") || SHORT_CLUSTER.test(arg) && RECURSIVE_LETTER.test(arg));
|
|
3332
3894
|
return isRecursive ? args.filter((arg, i) => !arg.startsWith("-") || args.includes("--") && i > args.indexOf("--")) : [];
|
|
3333
3895
|
}
|
|
3334
3896
|
function isProtectedPath(path) {
|
|
@@ -3340,18 +3902,18 @@ function isProtectedPath(path) {
|
|
|
3340
3902
|
const child = home === null ? absolute?.[1] : homeChild;
|
|
3341
3903
|
return last === ".git" || child !== undefined && (child === "Workspace" || child.startsWith(".") && child !== "..");
|
|
3342
3904
|
}
|
|
3343
|
-
function deletesFromHome(args) {
|
|
3905
|
+
function deletesFromHome(args, home) {
|
|
3344
3906
|
const firstOption = args.findIndex((arg) => arg.startsWith("-") || arg === "(" || arg === "!");
|
|
3345
3907
|
const starts = firstOption === -1 ? args : args.slice(0, firstOption);
|
|
3346
3908
|
const deletes = args.includes("-delete") || args.some((arg, i) => EXEC_FLAGS.has(arg) && REMOVER.test(args[i + 1] ?? ""));
|
|
3347
|
-
return deletes && starts.some((start) => start === "/" || start
|
|
3909
|
+
return deletes && starts.some((start) => start === "/" || [HOME_PREFIX.exec(start)?.[0], home?.replace(TRAILING_SLASH, "")].includes(start.replace(TRAILING_SLASH, "")));
|
|
3348
3910
|
}
|
|
3349
3911
|
function dockerPrunesAll(args) {
|
|
3350
3912
|
const system = args.indexOf("system");
|
|
3351
3913
|
return system !== -1 && args[system + 1] === "prune" && hasOption(args.slice(system + 2), ["--all"], "a");
|
|
3352
3914
|
}
|
|
3353
|
-
function removesBroadly(args) {
|
|
3354
|
-
return args.
|
|
3915
|
+
function removesBroadly(args, home) {
|
|
3916
|
+
return args.some((arg) => isLongPrefix(arg, "--no-preserve-root")) || recursiveTargets(args).some((path) => isBroadPath(path, home));
|
|
3355
3917
|
}
|
|
3356
3918
|
function checksOutTree(rest, operands) {
|
|
3357
3919
|
if (rest.includes("--"))
|
|
@@ -3414,16 +3976,23 @@ function runsDownload(command) {
|
|
|
3414
3976
|
return (SHELLS.has(program) || EVALUATORS.has(program)) && FETCH_SUBSTITUTION.test(piece.command);
|
|
3415
3977
|
});
|
|
3416
3978
|
}
|
|
3417
|
-
function
|
|
3979
|
+
function runsUnpinned(args) {
|
|
3980
|
+
const own = args.includes("--") ? args.slice(0, args.indexOf("--")) : args;
|
|
3981
|
+
const given = (name) => own.some((arg) => arg === name || arg.startsWith(`${name}=`));
|
|
3982
|
+
return given("--exec") && given("--yes") && !given("--sha256") && !given("--sums");
|
|
3983
|
+
}
|
|
3984
|
+
function destructiveViolation(command, home) {
|
|
3418
3985
|
if (runsDownload(command))
|
|
3419
3986
|
return PIPE_TO_SHELL;
|
|
3420
3987
|
for (const piece of splitCommand(command)) {
|
|
3421
3988
|
const { program, args } = parseCommand(piece.command);
|
|
3422
|
-
if (program === "
|
|
3989
|
+
if (program === "dl" && runsUnpinned(args))
|
|
3990
|
+
return UNPINNED_EXEC;
|
|
3991
|
+
if (program === "rm" && removesBroadly(args, home))
|
|
3423
3992
|
return BROAD_RM;
|
|
3424
3993
|
if (program === "rm" && recursiveTargets(args).some(isProtectedPath))
|
|
3425
3994
|
return PROTECTED_RM;
|
|
3426
|
-
if (program === "find" && deletesFromHome(args))
|
|
3995
|
+
if (program === "find" && deletesFromHome(args, home))
|
|
3427
3996
|
return FIND_DELETE_HOME;
|
|
3428
3997
|
if (program === "docker" && dockerPrunesAll(args))
|
|
3429
3998
|
return DOCKER_PRUNE_ALL;
|
|
@@ -3451,10 +4020,10 @@ var ARGV = new RegExp(String.raw`[[(]\s*((?:(?:${QUOTED})\s*,\s*)+(?:${QUOTED}))
|
|
|
3451
4020
|
var LITERAL = new RegExp(QUOTED, "gs");
|
|
3452
4021
|
var RUNS_SHELL = /(?:\b(?:system|exec\w*|spawn\w*|popen|run|call|check_\w+|Popen|getoutput|qx)|\$)\s*(?:\(\s*)?$/;
|
|
3453
4022
|
var SHELL_BACKTICKS = new Set(["perl", "ruby"]);
|
|
3454
|
-
var
|
|
4023
|
+
var ESCAPED2 = new Map([["n", `
|
|
3455
4024
|
`], ["t", " "]]);
|
|
3456
4025
|
function decode(text) {
|
|
3457
|
-
return text.replaceAll(ESCAPE2, (_, char) =>
|
|
4026
|
+
return text.replaceAll(ESCAPE2, (_, char) => ESCAPED2.get(char) ?? char);
|
|
3458
4027
|
}
|
|
3459
4028
|
function literalValue(literal) {
|
|
3460
4029
|
return decode(literal.slice(1, -1));
|
|
@@ -3519,40 +4088,54 @@ var SHELL_PROGRAMS = new Set(["ssh", "scp", "sftp", "mosh", "mosh-client", "auto
|
|
|
3519
4088
|
var SOCKET_PROGRAMS = new Set(["nc", "ncat", "netcat", "telnet", "socat"]);
|
|
3520
4089
|
var URL_PROGRAMS = new Set(["git", "docker", "docker-compose"]);
|
|
3521
4090
|
var DECLARERS2 = new Set(["export", "declare", "typeset"]);
|
|
3522
|
-
var RSYNC_REMOTE = /^(?:[\w.-]+@)?[\w.-]
|
|
4091
|
+
var RSYNC_REMOTE = /^(?:[\w.-]+@)?[\w.-]+:/;
|
|
3523
4092
|
var SCP_ADDRESS = /^[^/:\s-][^/:\s]*:(?!\/\/)/;
|
|
3524
4093
|
var SCP_HOST_ADDRESS = /^(?:[\w.-]+@[\w.-]+|[\w-]+(?:\.[\w-]+)+):(?!\/\/)/;
|
|
3525
4094
|
var GIT_TRANSPORTS = new Set(["clone", "fetch", "pull", "push", "ls-remote"]);
|
|
3526
4095
|
var TRANSPORT_VALUE_OPTIONS = new Set(["--depth", "-b", "--branch", "-o", "--origin", "--push-option", "-c", "--config", "--reference", "--separate-git-dir", "--template", "-j", "--jobs", "--filter", "--shallow-since", "--shallow-exclude", "-u", "--upload-pack", "--receive-pack", "--exec", "--server-option", "--repo", "--deepen"]);
|
|
3527
|
-
var SSH_URL = /^ssh:\/\//;
|
|
3528
4096
|
var SSH_URL_WORD = /^(?:[\w-]+=)?ssh:\/\//;
|
|
3529
4097
|
var LOOPBACK = /(?:^|[:=@[])(?:localhost|127(?:\.\d+){3}|::1)(?:[:\]/]|$)/;
|
|
3530
4098
|
var LISTENS = /^-[A-KM-Z]*L[A-Z]*$/i;
|
|
3531
4099
|
var DOCKER_VALUE_OPTIONS2 = new Set(["-c", "--context", "-H", "--host", "-l", "--log-level", "--config", "--tlscacert", "--tlscert", "--tlskey"]);
|
|
4100
|
+
var DOCKER_SHORT_VALUE = /^-([cHl])(.+)$/;
|
|
4101
|
+
var LOCAL_DAEMON = /^(?:unix|npipe|fd):\/\/|^tcp:\/\/(?:localhost|127(?:\.\d+){3}|\[::1\])(?::\d+)?\/?$/;
|
|
3532
4102
|
var CONTEXT_CHANGES = new Set(["use", "create", "update", "import"]);
|
|
3533
4103
|
var KUBECTL_SERVER = /^(?:--server(?:=|$)|-s$)/;
|
|
3534
4104
|
var REMOTE_VARIABLE = /^GIT_SSH(?:_COMMAND)?=/;
|
|
3535
4105
|
var REMOTE = "Remote servers are off limits (no SSH, no deploys, no remote commands). Hand the user the exact command to run themselves.";
|
|
4106
|
+
function isRemoteDaemon(address) {
|
|
4107
|
+
return address !== "" && !LOCAL_DAEMON.test(address);
|
|
4108
|
+
}
|
|
3536
4109
|
function dockerContext(args) {
|
|
3537
4110
|
let context = null;
|
|
4111
|
+
const hosts = [];
|
|
3538
4112
|
for (let i = 0;i < args.length; i++) {
|
|
3539
4113
|
const arg = args[i] ?? "";
|
|
3540
|
-
|
|
3541
|
-
|
|
3542
|
-
|
|
3543
|
-
|
|
4114
|
+
const equals = arg.indexOf("=");
|
|
4115
|
+
const attached = DOCKER_SHORT_VALUE.exec(arg);
|
|
4116
|
+
let [option, value] = [arg, undefined];
|
|
4117
|
+
if (arg.startsWith("--") && equals !== -1)
|
|
4118
|
+
[option, value] = [arg.slice(0, equals), arg.slice(equals + 1)];
|
|
4119
|
+
else if (attached !== null)
|
|
4120
|
+
[option, value] = [`-${attached[1]}`, attached[2]];
|
|
3544
4121
|
else if (DOCKER_VALUE_OPTIONS2.has(arg))
|
|
3545
|
-
i
|
|
4122
|
+
value = args[++i];
|
|
4123
|
+
if (option === "-c" || option === "--context")
|
|
4124
|
+
context = value ?? null;
|
|
4125
|
+
else if ((option === "-H" || option === "--host") && value !== undefined)
|
|
4126
|
+
hosts.push(value);
|
|
3546
4127
|
else if (!arg.startsWith("-"))
|
|
3547
|
-
return { context, name: arg, rest: args.slice(i + 1) };
|
|
4128
|
+
return { context, hosts, name: arg, rest: args.slice(i + 1) };
|
|
3548
4129
|
}
|
|
3549
|
-
return { context, name: "", rest: [] };
|
|
4130
|
+
return { context, hosts, name: "", rest: [] };
|
|
3550
4131
|
}
|
|
3551
4132
|
function isDockerRemote(args, assignments) {
|
|
3552
|
-
const { context, name, rest } = dockerContext(args);
|
|
4133
|
+
const { context, hosts, name, rest } = dockerContext(args);
|
|
3553
4134
|
const fromEnv = assignments.find((assignment) => assignment.startsWith("DOCKER_CONTEXT="))?.slice("DOCKER_CONTEXT=".length);
|
|
3554
4135
|
if ([context, fromEnv].some((each) => each !== null && each !== undefined && each !== "default"))
|
|
3555
4136
|
return true;
|
|
4137
|
+
if (hosts.some(isRemoteDaemon))
|
|
4138
|
+
return true;
|
|
3556
4139
|
return name === "context" && CONTEXT_CHANGES.has(rest[0] ?? "");
|
|
3557
4140
|
}
|
|
3558
4141
|
function isSocketRemote(args) {
|
|
@@ -3591,7 +4174,7 @@ function isRemote(text) {
|
|
|
3591
4174
|
return args.some((arg) => KUBECTL_SERVER.test(arg));
|
|
3592
4175
|
if ([...assignments, ...declared].some((assignment) => REMOTE_VARIABLE.test(assignment)))
|
|
3593
4176
|
return true;
|
|
3594
|
-
if ([...assignments, ...declared].some((assignment) => assignment.startsWith("DOCKER_HOST=") &&
|
|
4177
|
+
if ([...assignments, ...declared].some((assignment) => assignment.startsWith("DOCKER_HOST=") && isRemoteDaemon(assignment.slice("DOCKER_HOST=".length))))
|
|
3595
4178
|
return true;
|
|
3596
4179
|
if (program === "docker" && isDockerRemote(args, assignments))
|
|
3597
4180
|
return true;
|
|
@@ -3605,10 +4188,23 @@ function remoteViolation(command) {
|
|
|
3605
4188
|
var PYTHON = /^python[\d.]*$/;
|
|
3606
4189
|
var SCRIPT_RUNNERS = new Set(["bun", "node"]);
|
|
3607
4190
|
var EVAL_FLAGS = new Set(["-e", "--eval", "-p", "--print"]);
|
|
3608
|
-
var WRITES = /\bwrite_text\(|\bBun\.write\(|\bwriteFileSync\(|\bwriteFile\(|\bopen\([^)\n]*,\s*['"](?:w|a|r\+)/;
|
|
3609
4191
|
var REPLACE_CALL = /\.(replace|replaceAll)\(/g;
|
|
3610
|
-
var
|
|
4192
|
+
var WRITE_CALL = /\b(?:Bun\.write|writeFileSync|writeFile)\(/g;
|
|
4193
|
+
var READ_CALL = /\b(?:readFileSync|readFile)\(/g;
|
|
4194
|
+
var WRITE_METHOD = /\.(?:write_text|write_bytes)\(/g;
|
|
4195
|
+
var READ_METHOD = /\.(?:text|json|bytes|arrayBuffer|read_text|read_bytes)\(/g;
|
|
4196
|
+
var OPEN_CALL = /(\.)open\(|(?<![\w$.])open\(/g;
|
|
4197
|
+
var HANDLE = /^(?:await\s+)?(?:Bun\.file|(?:pathlib\.)?Path|open)\(/;
|
|
4198
|
+
var HANDLE_BEFORE = /(?:Bun\.file|(?<![\w$])Path|(?<![\w$.])open)$/;
|
|
4199
|
+
var RECEIVER_NAME = /[A-Z_$][\w$.]*$/i;
|
|
4200
|
+
var NAME_BEFORE = /[\w$.]*$/;
|
|
4201
|
+
var OPEN_MODE = /^[rwaxbt+U]+$/;
|
|
4202
|
+
var WRITE_MODE = /[wax+]/;
|
|
4203
|
+
var READ_MODE = /[r+]/;
|
|
4204
|
+
var MODE_KEYWORD = /^mode\s*=\s*/;
|
|
4205
|
+
var WHITESPACE2 = /\s+/g;
|
|
3611
4206
|
var IDENTIFIER2 = /^[A-Z_$][\w$]*/i;
|
|
4207
|
+
var ONLY_IDENTIFIER = /^[A-Z_$][\w$]*$/i;
|
|
3612
4208
|
var COUNT_CHECK = /\.count\(/g;
|
|
3613
4209
|
var COUNT_EQUALS = /^\s*\)\s*==\s*(\d+)/;
|
|
3614
4210
|
var PYTHON_COUNT = /^\s*,\s*(\d+)\s*\)/;
|
|
@@ -3691,14 +4287,109 @@ function valueAt(script, at, regex = false) {
|
|
|
3691
4287
|
const assigned = last === undefined ? undefined : literalAt(script, last.index + last[0].length, regex);
|
|
3692
4288
|
return assigned === undefined ? undefined : { ...assigned, end: at + name.length };
|
|
3693
4289
|
}
|
|
3694
|
-
function
|
|
3695
|
-
const
|
|
3696
|
-
for (
|
|
3697
|
-
|
|
3698
|
-
|
|
3699
|
-
|
|
4290
|
+
function quotedEnd(script, at) {
|
|
4291
|
+
const quote = script[at];
|
|
4292
|
+
for (let i = at + 1;i < script.length; i++) {
|
|
4293
|
+
if (script[i] === "\\")
|
|
4294
|
+
i++;
|
|
4295
|
+
else if (script[i] === quote)
|
|
4296
|
+
return i + 1;
|
|
3700
4297
|
}
|
|
3701
|
-
return
|
|
4298
|
+
return script.length;
|
|
4299
|
+
}
|
|
4300
|
+
function expressionAt(script, at) {
|
|
4301
|
+
let depth = 0;
|
|
4302
|
+
for (let i = at;i < script.length; ) {
|
|
4303
|
+
const char = script[i] ?? "";
|
|
4304
|
+
if (char === "'" || char === '"' || char === "`") {
|
|
4305
|
+
i = quotedEnd(script, i);
|
|
4306
|
+
continue;
|
|
4307
|
+
}
|
|
4308
|
+
if ("([{".includes(char))
|
|
4309
|
+
depth++;
|
|
4310
|
+
else if (")]}".includes(char) && depth-- === 0)
|
|
4311
|
+
return script.slice(at, i);
|
|
4312
|
+
else if (depth === 0 && (char === "," || char === ";" || char === `
|
|
4313
|
+
`))
|
|
4314
|
+
return script.slice(at, i);
|
|
4315
|
+
i++;
|
|
4316
|
+
}
|
|
4317
|
+
return script.slice(at);
|
|
4318
|
+
}
|
|
4319
|
+
function openingParen(script, close) {
|
|
4320
|
+
let depth = 0;
|
|
4321
|
+
for (let i = close;i >= 0; i--) {
|
|
4322
|
+
if (script[i] === ")")
|
|
4323
|
+
depth++;
|
|
4324
|
+
else if (script[i] === "(" && --depth === 0)
|
|
4325
|
+
return i;
|
|
4326
|
+
}
|
|
4327
|
+
return;
|
|
4328
|
+
}
|
|
4329
|
+
function targetAt(script, at, depth = 0) {
|
|
4330
|
+
const start = skip(script, at, SPACE2) ?? at;
|
|
4331
|
+
const literal = literalAt(script, start);
|
|
4332
|
+
if (literal !== undefined)
|
|
4333
|
+
return { key: literal.value, path: literal.value };
|
|
4334
|
+
const text = expressionAt(script, start).trimEnd();
|
|
4335
|
+
const handle = HANDLE.exec(text);
|
|
4336
|
+
if (handle !== null && depth < 8)
|
|
4337
|
+
return targetAt(script, start + handle[0].length, depth + 1);
|
|
4338
|
+
if (ONLY_IDENTIFIER.test(text))
|
|
4339
|
+
return nameTarget(script, text, start, depth);
|
|
4340
|
+
return text === "" ? undefined : { key: text.replaceAll(WHITESPACE2, "") };
|
|
4341
|
+
}
|
|
4342
|
+
function nameTarget(script, name, at, depth) {
|
|
4343
|
+
const assignments = [...script.slice(0, at).matchAll(new RegExp(String.raw`(?<![\w.$])${name.replaceAll("$", String.raw`\$`)}\s*=(?!=)\s*`, "g"))];
|
|
4344
|
+
const last = assignments.at(-1);
|
|
4345
|
+
if (last === undefined || depth >= 8)
|
|
4346
|
+
return { key: name };
|
|
4347
|
+
const from = last.index + last[0].length;
|
|
4348
|
+
const text = expressionAt(script, from).trimEnd();
|
|
4349
|
+
const followed = literalAt(script, from) !== undefined || HANDLE.test(text) || ONLY_IDENTIFIER.test(text);
|
|
4350
|
+
return followed ? targetAt(script, from, depth + 1) ?? { key: name } : { key: name };
|
|
4351
|
+
}
|
|
4352
|
+
function receiverTarget(script, dot) {
|
|
4353
|
+
if (script[dot - 1] === ")") {
|
|
4354
|
+
const open = openingParen(script, dot - 1);
|
|
4355
|
+
if (open === undefined)
|
|
4356
|
+
return;
|
|
4357
|
+
const before = script.slice(0, open);
|
|
4358
|
+
if (HANDLE_BEFORE.test(before))
|
|
4359
|
+
return targetAt(script, open + 1);
|
|
4360
|
+
const name = NAME_BEFORE.exec(before)?.[0] ?? "";
|
|
4361
|
+
return { key: (name + script.slice(open, dot)).replaceAll(WHITESPACE2, "") };
|
|
4362
|
+
}
|
|
4363
|
+
const name = RECEIVER_NAME.exec(script.slice(0, dot))?.[0];
|
|
4364
|
+
if (name === undefined)
|
|
4365
|
+
return;
|
|
4366
|
+
return ONLY_IDENTIFIER.test(name) ? nameTarget(script, name, dot - name.length, 0) : { key: name };
|
|
4367
|
+
}
|
|
4368
|
+
function fileAccess(script) {
|
|
4369
|
+
const reads = new Set;
|
|
4370
|
+
const writes = [];
|
|
4371
|
+
const read = (target) => target !== undefined && reads.add(target.key);
|
|
4372
|
+
for (const call of script.matchAll(WRITE_CALL))
|
|
4373
|
+
writes.push(targetAt(script, call.index + call[0].length));
|
|
4374
|
+
for (const call of script.matchAll(READ_CALL))
|
|
4375
|
+
read(targetAt(script, call.index + call[0].length));
|
|
4376
|
+
for (const call of script.matchAll(WRITE_METHOD))
|
|
4377
|
+
writes.push(receiverTarget(script, call.index));
|
|
4378
|
+
for (const call of script.matchAll(READ_METHOD))
|
|
4379
|
+
read(receiverTarget(script, call.index));
|
|
4380
|
+
for (const call of script.matchAll(OPEN_CALL)) {
|
|
4381
|
+
const after = call.index + call[0].length;
|
|
4382
|
+
const isMethod = call[1] !== undefined;
|
|
4383
|
+
const target = isMethod ? receiverTarget(script, call.index) : targetAt(script, after);
|
|
4384
|
+
const modeAt = isMethod ? after : skip(script, after + expressionAt(script, after).length, COMMA);
|
|
4385
|
+
const mode = modeAt === undefined || script[modeAt] === ")" ? "r" : literalAt(script, skip(script, modeAt, MODE_KEYWORD) ?? modeAt)?.value;
|
|
4386
|
+
const isWrite = mode !== undefined && OPEN_MODE.test(mode) && WRITE_MODE.test(mode);
|
|
4387
|
+
if (isWrite)
|
|
4388
|
+
writes.push(target);
|
|
4389
|
+
if (!isWrite || READ_MODE.test(mode))
|
|
4390
|
+
read(target);
|
|
4391
|
+
}
|
|
4392
|
+
return { reads, writes };
|
|
3702
4393
|
}
|
|
3703
4394
|
function assertedCounts(script) {
|
|
3704
4395
|
const counts = new Map;
|
|
@@ -3942,10 +4633,15 @@ function replaceViolation(command) {
|
|
|
3942
4633
|
}
|
|
3943
4634
|
const isPython = PYTHON.test(program);
|
|
3944
4635
|
const script = isPython || SCRIPT_RUNNERS.has(program) ? inlineScript(program, args, piece.text) : null;
|
|
3945
|
-
if (script === null ||
|
|
4636
|
+
if (script === null || script.search(REPLACE_CALL) === -1)
|
|
4637
|
+
continue;
|
|
4638
|
+
const { reads, writes } = fileAccess(script);
|
|
4639
|
+
const edited = writes.filter((target) => target !== undefined && reads.has(target.key));
|
|
4640
|
+
if (edited.length === 0 && !writes.includes(undefined))
|
|
3946
4641
|
continue;
|
|
3947
|
-
const pairs = scriptPairs(script, isPython);
|
|
3948
|
-
|
|
4642
|
+
const pairs = edited.length === 0 ? undefined : scriptPairs(script, isPython);
|
|
4643
|
+
const paths = new Set(edited.flatMap((target) => target?.path ?? []));
|
|
4644
|
+
return route(`A ${isPython ? "python" : program} script replacing text in a file is what \`sub\` does with a match-count check.`, pairs, [...paths]);
|
|
3949
4645
|
}
|
|
3950
4646
|
return null;
|
|
3951
4647
|
}
|
|
@@ -3990,8 +4686,8 @@ function mismatches(command, { cwd, home, exists }) {
|
|
|
3990
4686
|
return mismatch === null ? [] : [mismatch];
|
|
3991
4687
|
});
|
|
3992
4688
|
}
|
|
3993
|
-
function nestedMismatches(run, context
|
|
3994
|
-
const ownTexts = new Set(
|
|
4689
|
+
function nestedMismatches(run, context) {
|
|
4690
|
+
const ownTexts = new Set(installRequests(run[0] ?? "", context.cwd, context.home).map((request) => bareCommand(request.piece.command)));
|
|
3995
4691
|
return run.slice(1).flatMap((each) => mismatches(each, context)).filter((mismatch) => !ownTexts.has(mismatch.piece.command.trim())).map((mismatch) => ({ ...mismatch, rewrite: null }));
|
|
3996
4692
|
}
|
|
3997
4693
|
async function checkCommand(command, context) {
|
|
@@ -4014,9 +4710,9 @@ async function checkCommand(command, context) {
|
|
|
4014
4710
|
}
|
|
4015
4711
|
};
|
|
4016
4712
|
const readSql = async (path) => Promise.resolve(context.read(absolute(path, context.cwd)));
|
|
4017
|
-
add("remote", await guarded("remote", () => first(run.map(remoteViolation))));
|
|
4713
|
+
add("remote", await guarded("remote", () => first([...run, ...scripted].map(remoteViolation))));
|
|
4018
4714
|
add("git", await guarded("git", () => first([...run, ...scripted].map((each) => gitViolation(each, context.isPushAsked)))));
|
|
4019
|
-
add("destructive", await guarded("destructive", () => first([...run, ...scripted].map(destructiveViolation))));
|
|
4715
|
+
add("destructive", await guarded("destructive", () => first([...run, ...scripted].map((each) => destructiveViolation(each, context.home)))));
|
|
4020
4716
|
const commit = await guarded("commit", () => first(run.map((each) => commitViolation(each, context))));
|
|
4021
4717
|
add("commit", commit === null ? null : `${commit} ${USE_GC}`);
|
|
4022
4718
|
add("sql", await guarded("sql", async () => first(await Promise.all(run.map(async (each) => sqlViolation(each, readSql))))));
|
|
@@ -4028,7 +4724,7 @@ async function checkCommand(command, context) {
|
|
|
4028
4724
|
}));
|
|
4029
4725
|
add("edit", context.canSub ? await guarded("edit", () => first(run.map(replaceViolation))) : null);
|
|
4030
4726
|
const found = mismatches(command, context);
|
|
4031
|
-
const refused = [...found, ...nestedMismatches(run, context
|
|
4727
|
+
const refused = [...found, ...nestedMismatches(run, context)].find((mismatch) => mismatch.rewrite === null || !context.canRewrite);
|
|
4032
4728
|
const rewrite = refused?.rewrite ?? null;
|
|
4033
4729
|
const route = rewrite === null ? "Run it with the pinned manager instead." : `Run \`${rewrite.trim()}\` instead.`;
|
|
4034
4730
|
add("package-manager", refused === undefined ? null : `${refused.reason} ${route}`);
|
|
@@ -4047,21 +4743,18 @@ function checkPath(path) {
|
|
|
4047
4743
|
|
|
4048
4744
|
// src/bins.ts
|
|
4049
4745
|
var BINS = {
|
|
4050
|
-
check: "`check`: runs the repo's check, typecheck, lint and test steps (package.json, composer.json and PHP tool configs, a Justfile, a Makefile) and prints only what failed, each full log saved to a file; a step runs inside the running compose service that mounts its folder (`--in <service>`, `--host`), never starting one; validate a change with it rather than chaining the scripts or `docker compose exec` by hand (`--only lint,test`, `--list`, `--slot`, `--failed` to re-run what failed last
|
|
4051
|
-
fix: "`fix` (the alias of `check --fix`): runs the repo's fixers and formatters (its fix, lint:fix and format scripts, php-cs-fixer, just fmt, go fmt, cargo fmt, ruff), in the compose service like `check`, and lists the files they changed.",
|
|
4746
|
+
check: "`check`: runs the repo's check, typecheck, lint and test steps (package.json, composer.json and PHP tool configs, a Justfile, a Makefile) and prints only what failed, each full log saved to a file; a step runs inside the running compose service that mounts its folder (`--in <service>`, `--host`), never starting one; validate a change with it rather than chaining the scripts or `docker compose exec` by hand (`--only lint,test`, `--list`, `--slot`, `--failed` to re-run what failed last); `check --fix` runs its fixers and formatters instead (its fix, lint:fix and format scripts, php-cs-fixer, just fmt, go fmt, cargo fmt, ruff) and lists the files they changed.",
|
|
4052
4747
|
errs: "`errs [log]`, `errs -- <cmd>`: turns tsc, tsgo, eslint, bun check, bun test, vitest, playwright, phpunit, phpstan and php-cs-fixer output into one `file:line:col: message (rule)` line per error, counting the lines it did not recognise (`--json`); use it instead of reading raw type, lint or test logs.",
|
|
4053
4748
|
db: '`db "<sql>"`: one read-only statement against the Postgres, MySQL or MariaDB in DATABASE_URL (`-e KEY` for another) or, without one, the compose project\'s running database service (`-s <service>`, `-c <container>` for any container, `-d <database>`), credentials never shown; a write runs on a database whose name ends in `_test` and is printed for the user to run otherwise; `db tables`, `db describe <table>`, `db dbs`; use it instead of `docker exec <container> psql` or `mysql`.',
|
|
4054
|
-
ev: "`ev`: .env files read and edited with values masked (`ev list`, `ev get KEY`, `ev grep <regex>`, `ev show <rev>:<file>`, `ev set`, `ev diff`, `ev missing`); `ev audit [dir]` finds env files others can read or git tracks, and compose files writing secrets out; `ev pins [dir]` lists the env vars reaching outside that the tests of an app leave unpinned
|
|
4055
|
-
redact: "`redact`: masks secrets in piped output, `<cmd> | redact`.",
|
|
4749
|
+
ev: "`ev`: .env files read and edited with values masked (`ev list`, `ev get KEY`, `ev grep <regex>`, `ev show <rev>:<file>`, `ev set`, `ev diff`, `ev missing`); `ev audit [dir]` finds env files others can read or git tracks, and compose files writing secrets out; `ev pins [dir]` lists the env vars reaching outside that the tests of an app leave unpinned; `ev redact` masks secrets in piped output, `<cmd> | ev redact`.",
|
|
4056
4750
|
pkg: "`pkg <name>[@version]`: checks an npm package before it is added: whether the name exists or is a near miss of a popular one, the newest version at least two weeks old, licence, install scripts; `bun add`, `npm install`, `pnpm add` and `yarn add` run it first and are refused on what it flags. `pkg bump <@scope/lib> [version]` waits until the registry serves a release, then `bun add --exact`s it in every consumer under ~/Workspace (`--dry-run`), `pkg consumers <name>` lists them; use it instead of a `bun info` and sleep loop and a `bun add` per repo.",
|
|
4057
|
-
stack: "`stack port <name>`: the port a service name always hashes to, for every host port a compose file publishes
|
|
4751
|
+
stack: "`stack port <name>`: the port a service name always hashes to, for every host port a compose file publishes.",
|
|
4058
4752
|
ft: "`ft`: Forgejo CI runs, logs and waits, releases, issue checklists and claims, milestones (`ft milestones`, `ft milestone <m>`, `ft new -m`), in a repo whose origin is on Forgejo.",
|
|
4059
4753
|
sub: "`sub --from <text> --to <text> <file>...`: replaces text, writing nothing unless each match count is as expected (1, `-n N`, `--all`), `--regex`, `--dry-run --diff`; multi-line text goes as SEARCH/REPLACE blocks on stdin from a quoted heredoc (`sub <file> <<'EOF'`, see `sub --help`), no escaping; use it instead of sed -i, a bun -e or python editor.",
|
|
4060
|
-
base: "`base [--ref <rev>] [--keep <path>...] -- <cmd>`: runs a command at HEAD (or a ref) in a temporary worktree, removed afterwards, ignored env files and node_modules/vendor linked; use it instead of git stash
|
|
4061
|
-
proof: "`proof [--ref <rev>] [--keep <path>...] -- <cmd>`: runs the command at HEAD (or a ref) in a temporary worktree, then in the working tree, and exits 0 only when it fails before and passes now, printing the failing side's output; use it to prove a new test fails without your change (`--keep` the test).",
|
|
4754
|
+
base: "`base [--ref <rev>] [--keep <path>...] -- <cmd>`: runs a command at HEAD (or a ref) in a temporary worktree, removed afterwards, ignored env files and node_modules/vendor linked; use it instead of git stash; `base proof` runs it at HEAD (or a ref), then in the working tree, and exits 0 only when it fails before and passes now, printing the failing side's output; use it to prove a new test fails without your change (`--keep` the test).",
|
|
4062
4755
|
gst: "`gst [--log N]`: branch, upstream, changed counts and HEAD in one line, then the changed paths by staged, unstaged and untracked, `gst --repos` one line per repository nested below; use it instead of `git status --short` and `git log --oneline`.",
|
|
4063
4756
|
gc: "`gc <title> [-m <line>]... [--ticket <line>]... -- <path>...`: commits exactly those paths, refusing with nothing staged when the message breaks a commit rule, a path has no change or other files are already staged; use it instead of chaining git add, status and commit.",
|
|
4064
|
-
gp: "`gp [--repos] [dir]...`: pushes the current branch when it is ahead of its upstream, with `-u` to origin when it has none, `--repos` every repository nested below too, `--dry-run` saying what would go, flags for git push after `--`; only when the user asked for a push, like `git push`.",
|
|
4757
|
+
gp: "`gp [--repos] [-b <branch>]... [dir]...`: pushes the current branch, or each `-b` branch, when it is ahead of its upstream, with `-u` to origin when it has none, `--repos` every repository nested below too, `--dry-run` saying what would go, flags for git push after `--`; only when the user asked for a push, like `git push`.",
|
|
4065
4758
|
gb: "`gb [branch]`: switches to a branch, a remote one getting its tracking branch, `gb -c <name>` creating one; without a terminal it lists the branches (`--json`), with how each stands against its upstream and whether it is merged.",
|
|
4066
4759
|
gf: "`gf [--repos] [dir]...`: fetches with prune and fast-forwards the branch onto its upstream, saying what came in; a diverged branch or a tree the fast-forward would overwrite is refused untouched, `--no-pull` fetches only; use it instead of `git pull` and a git fetch per nested repository.",
|
|
4067
4760
|
gm: "`gm [branch]`: merges the branch into the current one, saying fast-forward or merge commit, the commits and the files that came in; a conflict lists every conflicted file with its conflict regions and exits 1, `--dry-run` tries the merge without touching the tree, `--continue`/`--abort`, `--squash`; with no branch it picks one, or lists each with its verdict off a terminal; use it instead of git merge then git diff and reading conflict markers.",
|
|
@@ -4071,11 +4764,10 @@ var BINS = {
|
|
|
4071
4764
|
waitfor: "`waitfor --file <log> --until <regex> [--fail <regex>]`, `--port <n>`, `--url <url>`, `--pid <n>` (`-t 5m`): waits until the line shows, the port listens, the URL answers 2xx or the process exits, exits 1 on a --fail line with the lines around it, 2 on a timeout with the last lines; `waitfor task <id>` waits for a background Bash task and prints its exit code, last lines and failure lines; use it instead of sleep and tail, `until ! pgrep -f` or polling loops.",
|
|
4072
4765
|
slot: "`slot [-l <lock>] -- <cmd>`: waits for one of the machine-wide slots shared by every session (half the CPUs), then runs the command; `--lock <name>` also holds a named lock for what must not run twice (a shared test database), `slot ls` lists holders and waiters; run heavy jobs (phpunit, playwright, vue-tsc, a full test suite) through it instead of a flock wrapper.",
|
|
4073
4766
|
gl: "`gl ci [ref]` waits for the GitLab pipeline covering a commit and prints each failed job's tests (exit 0/1/2), `gl runs`, `gl logs <pipeline> [-j job] [--full]`; use it instead of `glab ci` or `glab api .../pipelines/<id>/jobs` polled in a sleep loop.",
|
|
4074
|
-
|
|
4075
|
-
"todo-scan": "`todo-scan [path...]` lists the TODO, FIXME and owner/repo#N comments as `<file>:<line>: <comment>`, `--stale` only those whose issue is closed (exit 1), through ft; use it to find the workarounds a shipped fix lets you drop.",
|
|
4767
|
+
src: "`src peek <file:from-to>...` prints several spans with line numbers in one call, `src peek --def <symbol>` a whole declaration, `--refs <symbol>` its usages by file, `--outline <file>` the declarations and members, `--around <regex> -C 3` the lines around matches; use it instead of `sed -n N,Mp`, `grep -n` chains and whole-file reads; `src todo-scan [path...]` lists the TODO, FIXME and owner/repo#N comments as `<file>:<line>: <comment>`, `--stale` only those whose issue is closed (exit 1), through ft; use it to find the workarounds a shipped fix lets you drop; `src hotspots [dir] [--since <date>] [-n 20]` ranks the source files by complexity times git churn (commits touching each in the window, 6 months by default), tests and generated files left out, `--json`; use it to pick which complex files are worth splitting first.",
|
|
4076
4768
|
doctor: "`doctor`: checks this host's @kaynooo/cli-* install, one line per check with its fix: each bin's version against the registry, tea's login, the Claude Code hooks, the Bun floor (`--json`); run it when a bin lacks a command or a flag its docs name.",
|
|
4077
4769
|
cli: "`cli list`: every @kaynooo/cli-* bin in one line, what it does and what it is reached for instead of, read from each bin's own --help (`--json` adds the synopsis and examples); run it to find the bin that fits a task.",
|
|
4078
|
-
|
|
4770
|
+
dl: "`dl <url>`: downloads into a new folder and prints the path, size, final URL and sha256, with the diff of a text file since its last download; `--sha256 <hex>` or `--sums <url>` checks it, `-x` extracts, `--bin [name]` installs into ~/.local/bin, `--exec --sha256 <sha>` runs a script exactly as read, `dl ls` lists what it installed or ran; use it instead of `curl | sh`, `curl -LO` and `sha256sum -c`.",
|
|
4079
4771
|
out: "`out -- <cmd>`: folds long output, keeping the errors and saving the full log; run noisy builds, installs, tests and linters through it.",
|
|
4080
4772
|
changelog: "`changelog --dry`: the release notes since the last tag, grouped from the conventional commits, without publishing them; `changelog` publishes them as the Forgejo release of the tag at HEAD, `changelog undo [tag]` takes a release back."
|
|
4081
4773
|
};
|
|
@@ -4182,7 +4874,7 @@ async function hook(event, input, machine) {
|
|
|
4182
4874
|
var LISTED = [
|
|
4183
4875
|
{ name: "remote", refuses: "ssh, scp, rsync and deploys to a remote machine", route: "hand the command to the user" },
|
|
4184
4876
|
{ name: "git", refuses: "stash, whole-tree add and commit, push without being asked, tags", route: "stage by path with `gc`, push only when asked" },
|
|
4185
|
-
{ name: "destructive", refuses: "reset --hard, discarding the tree, clean -f, force push, branch -D, rebase, filter-branch, rm -r on a broad path, curl piped to a shell", route: "commit with `gc` first, `base`, `git worktree add`, `--force-with-lease` only when asked" },
|
|
4877
|
+
{ name: "destructive", refuses: "reset --hard, discarding the tree, clean -f, force push, branch -D, rebase, filter-branch, rm -r on a broad path, curl piped to a shell, dl --exec --yes on an unpinned script", route: "commit with `gc` first, `base`, `git worktree add`, `--force-with-lease` only when asked, `dl <url>` then `dl <url> --exec --sha256 <sha>`" },
|
|
4186
4878
|
{ name: "commit", refuses: "a commit message breaking the format, an unreadable one, trailers", route: "`gc <title> -m <line> -- <path>...`" },
|
|
4187
4879
|
{ name: "sql", refuses: "SQL writes and DDL, a file the client cannot read", route: '`db "<sql>"`, writes on a `*_test` database or handed over' },
|
|
4188
4880
|
{ name: "env", refuses: "reading or printing an env file, a diff of a tracked one", route: "`ev`, and `rg` for a tree-wide search" },
|
|
@@ -4193,11 +4885,10 @@ var LISTED = [
|
|
|
4193
4885
|
var RULES2 = LISTED.map((rule) => ({ runs: "check and hook", ...rule }));
|
|
4194
4886
|
|
|
4195
4887
|
// src/cli.ts
|
|
4196
|
-
var checkUsage = `guard check [options] [<command> | -]
|
|
4888
|
+
var checkUsage = `guard check [options] [<command> | -]: checks a shell command against the rules and names the route to take instead of each one it breaks
|
|
4197
4889
|
|
|
4198
|
-
|
|
4199
|
-
|
|
4200
|
-
The command is read from stdin with - or when none is given; a rule may rewrite it instead (the pinned package manager, a noisy run through out), printed as \`runs as: <command>\`.`;
|
|
4890
|
+
The rules (\`guard rules\` lists them) cover remote machines, git, destructive commands, commit messages, SQL writes, env files, package managers and in-place edits. A clean command prints nothing and exits 0.
|
|
4891
|
+
The command is read from stdin with - or when none is given; a rule may rewrite it instead, printed as \`runs as: <command>\`.`;
|
|
4201
4892
|
var CHECK_EXITS = [[0, "the command is clean"], [1, "a rule is broken"], [2, "a usage error"]];
|
|
4202
4893
|
var checkOptions = {
|
|
4203
4894
|
json: jsonOption("{violations, command, notes, packages} for a hook"),
|
|
@@ -4215,7 +4906,7 @@ var pathOptions = {
|
|
|
4215
4906
|
var hookUsage = `guard hook <${EVENTS.join("|")}>
|
|
4216
4907
|
|
|
4217
4908
|
Answers a Claude Code hook: reads the event JSON on stdin and prints the reply JSON, nothing when the call goes ahead untouched.
|
|
4218
|
-
pre-tool-use refuses a Bash call breaking a rule, an install pkg refuses
|
|
4909
|
+
\`pre-tool-use\` refuses a Bash call breaking a rule, an install \`pkg\` refuses and a file tool reaching an env file; \`user-prompt-submit\` remembers whether the prompt asked for a push; \`session-start\` lists the installed bins.
|
|
4219
4910
|
A failure exits 1, which Claude Code reports without blocking the call.`;
|
|
4220
4911
|
var HOOK_EXITS = [[0, "it answered"], [1, "a failure or an unknown event (never 2, which would block the call)"]];
|
|
4221
4912
|
var MAX_READ = 1e6;
|
|
@@ -4229,7 +4920,7 @@ function readText(path) {
|
|
|
4229
4920
|
}
|
|
4230
4921
|
function report2(violations) {
|
|
4231
4922
|
for (const { rule, message } of violations)
|
|
4232
|
-
console.log(`${role("problem",
|
|
4923
|
+
console.log(`${role("problem", process18.stdout)(rule)}: ${message}`);
|
|
4233
4924
|
}
|
|
4234
4925
|
async function check(args) {
|
|
4235
4926
|
const parsed = parse(args, checkUsage, checkOptions, { exits: CHECK_EXITS });
|
|
@@ -4241,7 +4932,7 @@ ${checkUsage}`);
|
|
|
4241
4932
|
const given = positionals[0] ?? "-";
|
|
4242
4933
|
const command = given === "-" ? await readInput("-", { noStdin: "give the command, or pipe it on stdin" }) : given;
|
|
4243
4934
|
const context = {
|
|
4244
|
-
cwd: values.cwd ??
|
|
4935
|
+
cwd: values.cwd ?? process18.cwd(),
|
|
4245
4936
|
home: homedir4(),
|
|
4246
4937
|
isPushAsked: values["push-asked"] === true,
|
|
4247
4938
|
canRewrite: true,
|
|
@@ -4256,7 +4947,7 @@ ${checkUsage}`);
|
|
|
4256
4947
|
else
|
|
4257
4948
|
report2(verdict.violations);
|
|
4258
4949
|
if (values.json !== true && verdict.command !== command)
|
|
4259
|
-
console.log(`${role("label",
|
|
4950
|
+
console.log(`${role("label", process18.stdout)("runs as:")} ${verdict.command}${verdict.notes.map((note) => `
|
|
4260
4951
|
${note}`).join("")}`);
|
|
4261
4952
|
return verdict.violations.length > 0 ? 1 : 0;
|
|
4262
4953
|
}
|
|
@@ -4287,7 +4978,7 @@ function rules(args) {
|
|
|
4287
4978
|
return 0;
|
|
4288
4979
|
}
|
|
4289
4980
|
for (const rule of RULES2)
|
|
4290
|
-
console.log(`${role("id",
|
|
4981
|
+
console.log(`${role("id", process18.stdout)(rule.name)}${" ".repeat(Math.max(0, 16 - rule.name.length))} ${rule.refuses}
|
|
4291
4982
|
${" ".repeat(16)} -> ${rule.route}${rule.runs === "hook" ? " (hook only)" : ""}`);
|
|
4292
4983
|
return 0;
|
|
4293
4984
|
}
|
|
@@ -4326,7 +5017,7 @@ ${hookUsage}`, 1);
|
|
|
4326
5017
|
console.log(JSON.stringify(reply));
|
|
4327
5018
|
return 0;
|
|
4328
5019
|
}
|
|
4329
|
-
|
|
5020
|
+
process18.exitCode = await runCli({
|
|
4330
5021
|
name: "guard",
|
|
4331
5022
|
usage: false,
|
|
4332
5023
|
about: "the safety rules a Claude Code Bash call is held to, each refusal naming the route",
|