@kaynooo/cli-git 0.14.0 → 0.15.1
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 +34 -1
- package/dist/gb.js +302 -43
- package/dist/gc.js +290 -31
- package/dist/gcl.js +1662 -0
- package/dist/gd.js +1642 -0
- package/dist/gf.js +1624 -0
- package/dist/gp.js +320 -52
- package/dist/gst.js +322 -49
- package/dist/gu.js +1484 -0
- package/package.json +14 -6
package/dist/gu.js
ADDED
|
@@ -0,0 +1,1484 @@
|
|
|
1
|
+
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
|
+
// @bun
|
|
3
|
+
|
|
4
|
+
// src/gu.ts
|
|
5
|
+
import { mkdirSync as mkdirSync2, writeFileSync } from "fs";
|
|
6
|
+
import { join as join7, resolve as resolve5 } from "path";
|
|
7
|
+
import process18 from "process";
|
|
8
|
+
// ../kit/src/args.ts
|
|
9
|
+
import process9 from "process";
|
|
10
|
+
import { parseArgs } from "util";
|
|
11
|
+
|
|
12
|
+
// ../kit/src/format.ts
|
|
13
|
+
import process7 from "process";
|
|
14
|
+
|
|
15
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
|
|
16
|
+
var N = new Map;
|
|
17
|
+
var Nt = /\s+\S*$/;
|
|
18
|
+
var Y = /\s/;
|
|
19
|
+
function ko(t, e, r = "...") {
|
|
20
|
+
let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
|
|
21
|
+
if (t.length <= e)
|
|
22
|
+
return t;
|
|
23
|
+
let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
|
|
24
|
+
if (o && !Y.test(t[c.length] ?? " "))
|
|
25
|
+
c = c.replace(Nt, "") || c;
|
|
26
|
+
if (o)
|
|
27
|
+
c = c.trimEnd();
|
|
28
|
+
return s ? (c + n).slice(0, l) : c + n;
|
|
29
|
+
}
|
|
30
|
+
var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
|
|
31
|
+
var z = new Map;
|
|
32
|
+
|
|
33
|
+
// ../kit/src/mode.ts
|
|
34
|
+
import process2 from "process";
|
|
35
|
+
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
36
|
+
var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
37
|
+
function isSet(value) {
|
|
38
|
+
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
39
|
+
}
|
|
40
|
+
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
41
|
+
const chosen = env.KIT_MODE;
|
|
42
|
+
if (chosen !== undefined && MODES.has(chosen))
|
|
43
|
+
return chosen;
|
|
44
|
+
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
45
|
+
return "agent";
|
|
46
|
+
if (stream.isTTY === true)
|
|
47
|
+
return "terminal";
|
|
48
|
+
return isSet(env.CI) ? "ci" : "pipe";
|
|
49
|
+
}
|
|
50
|
+
function isInteractive(streams = process2) {
|
|
51
|
+
return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// ../kit/src/style.ts
|
|
55
|
+
import process6 from "process";
|
|
56
|
+
|
|
57
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
58
|
+
var G2 = /^[a-f0-9]+$/i;
|
|
59
|
+
function b(r) {
|
|
60
|
+
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
61
|
+
if (!G2.test(e))
|
|
62
|
+
return [0, 0, 0];
|
|
63
|
+
if (e.length === 3 || e.length === 4)
|
|
64
|
+
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
65
|
+
if (e.length !== 6 && e.length !== 8)
|
|
66
|
+
throw Error(`Invalid hex color length: ${e.length}`);
|
|
67
|
+
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
68
|
+
}
|
|
69
|
+
var B2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
|
|
70
|
+
let [l, n, c] = b(r);
|
|
71
|
+
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
72
|
+
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
73
|
+
var h = new Set(["", "1", "2", "3", "true"]);
|
|
74
|
+
function C(r, e = globalThis.process?.env ?? {}) {
|
|
75
|
+
if (e.FORCE_COLOR !== undefined)
|
|
76
|
+
return h.has(e.FORCE_COLOR);
|
|
77
|
+
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
78
|
+
return false;
|
|
79
|
+
return r?.isTTY === true;
|
|
80
|
+
}
|
|
81
|
+
function f(r, e = []) {
|
|
82
|
+
let l = "", n = "";
|
|
83
|
+
for (let t = 0, i = e.length;t < i; t++)
|
|
84
|
+
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
85
|
+
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
86
|
+
return new Proxy(c, { get(t, i) {
|
|
87
|
+
let a = B2[i];
|
|
88
|
+
if (Array.isArray(a)) {
|
|
89
|
+
let s = g.get(i);
|
|
90
|
+
if (s === undefined)
|
|
91
|
+
s = f(r, [...e, a]), g.set(i, s);
|
|
92
|
+
return s;
|
|
93
|
+
}
|
|
94
|
+
if (typeof a === "function")
|
|
95
|
+
return (...s) => {
|
|
96
|
+
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
97
|
+
if (u === undefined) {
|
|
98
|
+
if (g.size >= 64)
|
|
99
|
+
g.clear();
|
|
100
|
+
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
101
|
+
}
|
|
102
|
+
return u;
|
|
103
|
+
};
|
|
104
|
+
throw Error(`Unknown style: ${String(i)}`);
|
|
105
|
+
} });
|
|
106
|
+
}
|
|
107
|
+
function Fe(r = {}) {
|
|
108
|
+
return f(r);
|
|
109
|
+
}
|
|
110
|
+
var o = Fe();
|
|
111
|
+
|
|
112
|
+
// ../kit/src/theme.ts
|
|
113
|
+
import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
|
|
114
|
+
import { homedir as homedir2 } from "os";
|
|
115
|
+
import { join as join3, resolve as resolve2 } from "path";
|
|
116
|
+
import process5 from "process";
|
|
117
|
+
|
|
118
|
+
// ../kit/src/config.ts
|
|
119
|
+
import { existsSync } from "fs";
|
|
120
|
+
import { dirname, join, resolve } from "path";
|
|
121
|
+
import process3 from "process";
|
|
122
|
+
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
123
|
+
const wanted = typeof names === "string" ? [names] : names;
|
|
124
|
+
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
125
|
+
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
126
|
+
if (found !== undefined)
|
|
127
|
+
return found;
|
|
128
|
+
if (stop(dir) || dirname(dir) === dir)
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ../kit/src/user-config.ts
|
|
134
|
+
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
135
|
+
import { homedir } from "os";
|
|
136
|
+
import { join as join2 } from "path";
|
|
137
|
+
import process4 from "process";
|
|
138
|
+
function configBase(where = {}) {
|
|
139
|
+
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
140
|
+
return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
|
|
141
|
+
}
|
|
142
|
+
function userConfigPath(bin, where = {}) {
|
|
143
|
+
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
144
|
+
}
|
|
145
|
+
function userConfigReadPath(bin, legacy = [], where = {}) {
|
|
146
|
+
const current = userConfigPath(bin, where);
|
|
147
|
+
if (existsSync2(current))
|
|
148
|
+
return current;
|
|
149
|
+
const base = configBase(where);
|
|
150
|
+
return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
|
|
151
|
+
}
|
|
152
|
+
function readUserConfig(bin, where = {}, legacy = []) {
|
|
153
|
+
const path = userConfigReadPath(bin, legacy, where);
|
|
154
|
+
if (!existsSync2(path))
|
|
155
|
+
return {};
|
|
156
|
+
try {
|
|
157
|
+
const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
|
|
158
|
+
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
|
|
159
|
+
} catch {
|
|
160
|
+
return {};
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ../kit/src/theme.ts
|
|
165
|
+
function toLinear(channel) {
|
|
166
|
+
const value = channel / 255;
|
|
167
|
+
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
|
|
168
|
+
}
|
|
169
|
+
var fromLinear = (value) => Math.round(255 * Math.min(1, Math.max(0, value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055)));
|
|
170
|
+
function toOklab(hex) {
|
|
171
|
+
const [r, g, b] = [1, 3, 5].map((at) => toLinear(Number.parseInt(hex.slice(at, at + 2), 16)));
|
|
172
|
+
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
|
|
173
|
+
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
|
|
174
|
+
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
|
|
175
|
+
return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];
|
|
176
|
+
}
|
|
177
|
+
function fromOklab([lightness, a, b]) {
|
|
178
|
+
const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;
|
|
179
|
+
const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;
|
|
180
|
+
const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;
|
|
181
|
+
const channels = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s];
|
|
182
|
+
return `#${channels.map((channel) => fromLinear(channel).toString(16).padStart(2, "0")).join("")}`;
|
|
183
|
+
}
|
|
184
|
+
var ENDS = new Map;
|
|
185
|
+
function gradientAt(theme, ratio) {
|
|
186
|
+
if (theme.gradient === undefined)
|
|
187
|
+
return;
|
|
188
|
+
const key = theme.gradient.join();
|
|
189
|
+
let ends = ENDS.get(key);
|
|
190
|
+
if (ends === undefined) {
|
|
191
|
+
ends = [toOklab(theme.gradient[0]), toOklab(theme.gradient[1])];
|
|
192
|
+
ENDS.set(key, ends);
|
|
193
|
+
}
|
|
194
|
+
const at = Math.min(1, Math.max(0, ratio));
|
|
195
|
+
const [from, to] = ends;
|
|
196
|
+
return fromOklab(from.map((start, index) => start + (to[index] - start) * at));
|
|
197
|
+
}
|
|
198
|
+
var DEFAULT = {
|
|
199
|
+
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" },
|
|
200
|
+
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" },
|
|
201
|
+
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
202
|
+
bins: {},
|
|
203
|
+
gradient: ["#c084fc", "#67e8f9"]
|
|
204
|
+
};
|
|
205
|
+
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" };
|
|
206
|
+
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" };
|
|
207
|
+
var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
208
|
+
var PRESETS = {
|
|
209
|
+
default: {},
|
|
210
|
+
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
211
|
+
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
212
|
+
ascii: { glyphs: ASCII }
|
|
213
|
+
};
|
|
214
|
+
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"]);
|
|
215
|
+
var HEX = /^#[0-9a-f]{6}$/i;
|
|
216
|
+
var CONTROL = /\p{Cc}/u;
|
|
217
|
+
var MAX_FILE_BYTES = 64 * 1024;
|
|
218
|
+
var SPACES = /\s+/;
|
|
219
|
+
function isColorSpec(spec) {
|
|
220
|
+
if (typeof spec === "number")
|
|
221
|
+
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
222
|
+
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
223
|
+
}
|
|
224
|
+
var CUBE = [0, 95, 135, 175, 215, 255];
|
|
225
|
+
function cubeLevel(channel) {
|
|
226
|
+
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
227
|
+
}
|
|
228
|
+
function nearest256(hex) {
|
|
229
|
+
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
230
|
+
const levels = rgb.map(cubeLevel);
|
|
231
|
+
const cube = levels.map((level) => CUBE[level]);
|
|
232
|
+
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
233
|
+
const greyValue = 8 + grey * 10;
|
|
234
|
+
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
235
|
+
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
236
|
+
}
|
|
237
|
+
function hasTrueColor(env) {
|
|
238
|
+
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
239
|
+
}
|
|
240
|
+
function tinted(colors, spec, env = process5.env) {
|
|
241
|
+
if (typeof spec === "number")
|
|
242
|
+
return colors.ansi256(spec);
|
|
243
|
+
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
244
|
+
if (HEX.test(token))
|
|
245
|
+
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
246
|
+
return chain[token] ?? chain;
|
|
247
|
+
}, colors);
|
|
248
|
+
}
|
|
249
|
+
function shaded(theme, colors, glyph, cells, width, env = process5.env) {
|
|
250
|
+
return Array.from({ length: cells }, (_, index) => tinted(colors, gradientAt(theme, width <= 1 ? 0 : index / (width - 1)) ?? theme.colors.accent, env)(glyph)).join("");
|
|
251
|
+
}
|
|
252
|
+
function isRecord(value) {
|
|
253
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
254
|
+
}
|
|
255
|
+
function readThemeFile(path, warn) {
|
|
256
|
+
try {
|
|
257
|
+
const stat = statSync(path, { throwIfNoEntry: false });
|
|
258
|
+
if (stat === undefined)
|
|
259
|
+
return;
|
|
260
|
+
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
261
|
+
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
265
|
+
if (isRecord(parsed))
|
|
266
|
+
return parsed;
|
|
267
|
+
warn(`${path} is not a JSON object, theme ignored`);
|
|
268
|
+
} catch (error) {
|
|
269
|
+
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
270
|
+
}
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
function applyPreset(theme, name, warn, where) {
|
|
274
|
+
if (name === undefined)
|
|
275
|
+
return;
|
|
276
|
+
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
277
|
+
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
const preset = PRESETS[name];
|
|
281
|
+
Object.assign(theme.colors, preset.colors);
|
|
282
|
+
Object.assign(theme.glyphs, preset.glyphs);
|
|
283
|
+
if (preset.accents !== undefined)
|
|
284
|
+
theme.accents = [...preset.accents];
|
|
285
|
+
if (Object.hasOwn(preset, "gradient"))
|
|
286
|
+
theme.gradient = preset.gradient;
|
|
287
|
+
return name;
|
|
288
|
+
}
|
|
289
|
+
function applyFile(theme, file, where, warn) {
|
|
290
|
+
if (isRecord(file.colors)) {
|
|
291
|
+
for (const [key, value] of Object.entries(file.colors)) {
|
|
292
|
+
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
293
|
+
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
294
|
+
else if (!isColorSpec(value))
|
|
295
|
+
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
296
|
+
else
|
|
297
|
+
theme.colors[key] = value;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
if (isRecord(file.glyphs)) {
|
|
301
|
+
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
302
|
+
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
303
|
+
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
304
|
+
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
305
|
+
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
306
|
+
else
|
|
307
|
+
theme.glyphs[key] = value;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
311
|
+
theme.accents = [...file.accents];
|
|
312
|
+
else if (file.accents !== undefined)
|
|
313
|
+
warn(`${where}: accents must be a non-empty list of colours`);
|
|
314
|
+
if (file.gradient === null)
|
|
315
|
+
theme.gradient = undefined;
|
|
316
|
+
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
317
|
+
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
318
|
+
else if (file.gradient !== undefined)
|
|
319
|
+
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
320
|
+
if (isRecord(file.bins)) {
|
|
321
|
+
for (const [bin, value] of Object.entries(file.bins)) {
|
|
322
|
+
if (isColorSpec(value))
|
|
323
|
+
theme.bins[bin] = value;
|
|
324
|
+
else
|
|
325
|
+
warn(`${where}: bin ${bin} has no valid colour`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
function endsWalk(home) {
|
|
330
|
+
return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
|
|
331
|
+
}
|
|
332
|
+
var warned = new Set;
|
|
333
|
+
function warnOnce(message) {
|
|
334
|
+
if (warned.has(message))
|
|
335
|
+
return;
|
|
336
|
+
warned.add(message);
|
|
337
|
+
console.error(`warning: theme ${message}`);
|
|
338
|
+
}
|
|
339
|
+
function isPath(chosen) {
|
|
340
|
+
return chosen.includes("/") || chosen.endsWith(".json");
|
|
341
|
+
}
|
|
342
|
+
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
343
|
+
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
344
|
+
const sources = [];
|
|
345
|
+
const chosen = env.KIT_THEME ?? "";
|
|
346
|
+
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
347
|
+
if (isPath(chosen))
|
|
348
|
+
wanted.push(resolve2(from, chosen));
|
|
349
|
+
const files = [];
|
|
350
|
+
for (const path of wanted) {
|
|
351
|
+
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
352
|
+
if (path !== undefined && file !== undefined)
|
|
353
|
+
files.push({ path, file });
|
|
354
|
+
}
|
|
355
|
+
let preset = "default";
|
|
356
|
+
if (chosen !== "" && !isPath(chosen)) {
|
|
357
|
+
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
358
|
+
} else {
|
|
359
|
+
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
360
|
+
if (named !== undefined)
|
|
361
|
+
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
362
|
+
}
|
|
363
|
+
for (const { path, file } of files) {
|
|
364
|
+
applyFile(theme, file, path, warn);
|
|
365
|
+
sources.push(path);
|
|
366
|
+
}
|
|
367
|
+
return { theme, sources, preset };
|
|
368
|
+
}
|
|
369
|
+
var current;
|
|
370
|
+
var currentKey = "";
|
|
371
|
+
function activeTheme() {
|
|
372
|
+
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
373
|
+
if (current === undefined || key !== currentKey) {
|
|
374
|
+
current = loadTheme();
|
|
375
|
+
currentKey = key;
|
|
376
|
+
}
|
|
377
|
+
return current;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// ../kit/src/style.ts
|
|
381
|
+
var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
|
|
382
|
+
function takesControlCodes(stream, env = process6.env) {
|
|
383
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
384
|
+
}
|
|
385
|
+
function paint(stream, env = process6.env) {
|
|
386
|
+
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
387
|
+
}
|
|
388
|
+
function marked(mark, text, stream, detail, env = process6.env) {
|
|
389
|
+
const colors = paint(stream, env);
|
|
390
|
+
let head = MARK_WORDS[mark];
|
|
391
|
+
if (takesControlCodes(stream, env)) {
|
|
392
|
+
const { theme } = activeTheme();
|
|
393
|
+
head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
|
|
394
|
+
}
|
|
395
|
+
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
396
|
+
}
|
|
397
|
+
function role(name, stream, env = process6.env) {
|
|
398
|
+
const colors = paint(stream, env);
|
|
399
|
+
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
400
|
+
}
|
|
401
|
+
var STATUS_WORDS = {
|
|
402
|
+
passed: ["passed", "success", "succeeded", "ok"],
|
|
403
|
+
failed: ["failed", "failure", "error", "errored"],
|
|
404
|
+
running: ["running", "in_progress", "started", "holding"],
|
|
405
|
+
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
406
|
+
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
407
|
+
};
|
|
408
|
+
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
409
|
+
|
|
410
|
+
// ../kit/src/format.ts
|
|
411
|
+
var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
412
|
+
function formatSeconds(total) {
|
|
413
|
+
let rest = Math.max(0, Math.round(total));
|
|
414
|
+
const amounts = UNITS.map(([unit, size]) => {
|
|
415
|
+
const amount = Math.floor(rest / size);
|
|
416
|
+
rest -= amount * size;
|
|
417
|
+
return `${amount}${unit}`;
|
|
418
|
+
});
|
|
419
|
+
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
420
|
+
if (first === -1)
|
|
421
|
+
return "0s";
|
|
422
|
+
const next = amounts[first + 1];
|
|
423
|
+
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
424
|
+
}
|
|
425
|
+
function formatDuration(ms) {
|
|
426
|
+
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
427
|
+
}
|
|
428
|
+
function formatElapsed(ms) {
|
|
429
|
+
return formatSeconds(Math.floor(Math.max(0, ms) / 1000));
|
|
430
|
+
}
|
|
431
|
+
function upTo(text, separator) {
|
|
432
|
+
const end = text.indexOf(separator);
|
|
433
|
+
return end === -1 ? text : text.slice(0, end);
|
|
434
|
+
}
|
|
435
|
+
function formatAge(date, now = Date.now()) {
|
|
436
|
+
const at = typeof date === "number" ? date : Date.parse(date);
|
|
437
|
+
if (Number.isNaN(at))
|
|
438
|
+
return "-";
|
|
439
|
+
const seconds = (now - at) / 1000;
|
|
440
|
+
return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
|
|
441
|
+
}
|
|
442
|
+
function truncate(text, width) {
|
|
443
|
+
return ko(text, width, { suffix: "\u2026", includeSuffix: true });
|
|
444
|
+
}
|
|
445
|
+
var LINE_BREAKS = /\s*\n\s*/g;
|
|
446
|
+
var ESCAPE = String.fromCharCode(27);
|
|
447
|
+
function textWidth(text) {
|
|
448
|
+
return Bun.stringWidth(text);
|
|
449
|
+
}
|
|
450
|
+
function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
|
|
451
|
+
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
452
|
+
if (outputMode(stream, env) === "agent")
|
|
453
|
+
return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
|
|
454
|
+
`);
|
|
455
|
+
const widths = [];
|
|
456
|
+
for (const row of cells) {
|
|
457
|
+
for (const [index, cell] of row.entries())
|
|
458
|
+
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
459
|
+
}
|
|
460
|
+
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
461
|
+
const colors = paint(stream);
|
|
462
|
+
const lines = shown.map((row) => row.map((cell, index) => {
|
|
463
|
+
const width = widths[index] ?? 0;
|
|
464
|
+
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
465
|
+
if (align[index] === "right")
|
|
466
|
+
return `${gap}${cell}`;
|
|
467
|
+
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
468
|
+
}).join(" ").trimEnd());
|
|
469
|
+
const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
|
|
470
|
+
return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
|
|
471
|
+
`);
|
|
472
|
+
}
|
|
473
|
+
function narrow(rows, widths, limit) {
|
|
474
|
+
const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
|
|
475
|
+
const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
|
|
476
|
+
const floor = 8;
|
|
477
|
+
while (used() > limit) {
|
|
478
|
+
let widest = -1;
|
|
479
|
+
for (const [index, width] of widths.entries()) {
|
|
480
|
+
if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
|
|
481
|
+
widest = index;
|
|
482
|
+
}
|
|
483
|
+
if (widest === -1)
|
|
484
|
+
break;
|
|
485
|
+
widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
|
|
486
|
+
}
|
|
487
|
+
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
488
|
+
}
|
|
489
|
+
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
490
|
+
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
491
|
+
}
|
|
492
|
+
function printJson(value) {
|
|
493
|
+
console.log(jsonText(value));
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// ../kit/src/help.ts
|
|
497
|
+
import process8 from "process";
|
|
498
|
+
var OPTIONAL = /\[[^\]]+\]/g;
|
|
499
|
+
var USAGE_PREFIX = /^usage:\s*/i;
|
|
500
|
+
var FULL_STOP = /\.$/;
|
|
501
|
+
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
502
|
+
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
503
|
+
}
|
|
504
|
+
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
505
|
+
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
506
|
+
`);
|
|
507
|
+
}
|
|
508
|
+
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
509
|
+
if (exits.length === 0)
|
|
510
|
+
return [];
|
|
511
|
+
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
512
|
+
}
|
|
513
|
+
function wantsHelpJson(env = process8.env) {
|
|
514
|
+
return env.KIT_HELP === "json";
|
|
515
|
+
}
|
|
516
|
+
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
517
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
518
|
+
`);
|
|
519
|
+
const first = lines[0];
|
|
520
|
+
const colon = first.indexOf(": ");
|
|
521
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
522
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
523
|
+
return {
|
|
524
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
525
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
526
|
+
...replaces === undefined ? {} : { replaces },
|
|
527
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
528
|
+
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
529
|
+
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
533
|
+
if (examples.length === 0 || outputMode() === "agent")
|
|
534
|
+
return [];
|
|
535
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
536
|
+
}
|
|
537
|
+
function optionRows(options, colors = paint(process8.stdout)) {
|
|
538
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
539
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
540
|
+
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
541
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
542
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
543
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
|
|
544
|
+
});
|
|
545
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
546
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// ../kit/src/text.ts
|
|
550
|
+
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
551
|
+
function distance(a, b) {
|
|
552
|
+
let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
|
|
553
|
+
for (const [i, left] of [...a].entries()) {
|
|
554
|
+
const current = [i + 1];
|
|
555
|
+
for (const [j, right] of [...b].entries())
|
|
556
|
+
current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
|
|
557
|
+
previous = current;
|
|
558
|
+
}
|
|
559
|
+
return previous[b.length] ?? 0;
|
|
560
|
+
}
|
|
561
|
+
function closest(name, names) {
|
|
562
|
+
const started = names.find((known) => known.startsWith(name));
|
|
563
|
+
if (started !== undefined)
|
|
564
|
+
return started;
|
|
565
|
+
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
566
|
+
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
567
|
+
}
|
|
568
|
+
// ../kit/src/input.ts
|
|
569
|
+
var WHOLE = /^\d+$/;
|
|
570
|
+
function wholeNumber(value, name, fallback, min = 1) {
|
|
571
|
+
if (value === undefined)
|
|
572
|
+
return fallback;
|
|
573
|
+
const number = Number(value);
|
|
574
|
+
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
575
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
576
|
+
return number;
|
|
577
|
+
}
|
|
578
|
+
var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
|
|
579
|
+
var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
|
|
580
|
+
function duration(value, name, fallback, unit = "s") {
|
|
581
|
+
if (value === undefined)
|
|
582
|
+
return fallback;
|
|
583
|
+
const match = DURATION.exec(value.trim());
|
|
584
|
+
const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
|
|
585
|
+
if (ms < 1)
|
|
586
|
+
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
587
|
+
return ms;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// ../kit/src/args.ts
|
|
591
|
+
var DASHES = /^-+/;
|
|
592
|
+
function jsonOption(holds) {
|
|
593
|
+
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
594
|
+
}
|
|
595
|
+
class Exit extends Error {
|
|
596
|
+
code;
|
|
597
|
+
hint;
|
|
598
|
+
constructor(message, code, hint) {
|
|
599
|
+
super(message);
|
|
600
|
+
this.code = code;
|
|
601
|
+
this.hint = hint;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
function fail(message, code = 2, hint) {
|
|
605
|
+
throw new Exit(message, code, hint);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
class UsageError extends Exit {
|
|
609
|
+
constructor(message, hint) {
|
|
610
|
+
super(message, 2, hint);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
function badUsage(message) {
|
|
614
|
+
throw new UsageError(message);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
class HelpShown extends Exit {
|
|
618
|
+
constructor() {
|
|
619
|
+
super("help shown", 0);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
class Completing {
|
|
624
|
+
options;
|
|
625
|
+
positionals;
|
|
626
|
+
candidates;
|
|
627
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
628
|
+
this.options = options;
|
|
629
|
+
this.positionals = positionals;
|
|
630
|
+
this.candidates = candidates;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
var completion = { active: false };
|
|
634
|
+
var OUTPUT_OPTIONS = {
|
|
635
|
+
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
636
|
+
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
637
|
+
};
|
|
638
|
+
function applyOutput(color, plain, env = process9.env) {
|
|
639
|
+
const when = plain === true ? "never" : color ?? "auto";
|
|
640
|
+
if (when === "auto")
|
|
641
|
+
return;
|
|
642
|
+
if (when !== "always" && when !== "never")
|
|
643
|
+
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
644
|
+
if (when === "always") {
|
|
645
|
+
env.FORCE_COLOR = "1";
|
|
646
|
+
delete env.NO_COLOR;
|
|
647
|
+
} else {
|
|
648
|
+
env.NO_COLOR = "1";
|
|
649
|
+
delete env.FORCE_COLOR;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
function parse(args, usage, options, settings = {}) {
|
|
653
|
+
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
654
|
+
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
655
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
656
|
+
if (completion.active)
|
|
657
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
658
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
659
|
+
let parsed;
|
|
660
|
+
try {
|
|
661
|
+
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
662
|
+
} catch (error) {
|
|
663
|
+
const message = parseError(error);
|
|
664
|
+
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
665
|
+
}
|
|
666
|
+
const values = parsed.values;
|
|
667
|
+
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
668
|
+
if (values.help === true) {
|
|
669
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
670
|
+
throw new HelpShown;
|
|
671
|
+
}
|
|
672
|
+
checkChoices(parsed.values, all);
|
|
673
|
+
checkConflicts(parsed.values, all);
|
|
674
|
+
if (settings.positionals !== undefined)
|
|
675
|
+
checkPositionals(parsed.positionals, settings.positionals);
|
|
676
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
677
|
+
}
|
|
678
|
+
function splitRest(args, passes) {
|
|
679
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
680
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
681
|
+
}
|
|
682
|
+
function splitTrailing(args, options, count) {
|
|
683
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
684
|
+
let seen = 0;
|
|
685
|
+
if (count === 0)
|
|
686
|
+
return { own: args, rest: undefined };
|
|
687
|
+
for (let at = 0;at < args.length; at++) {
|
|
688
|
+
const word = args[at];
|
|
689
|
+
if (word === "--")
|
|
690
|
+
break;
|
|
691
|
+
if (word.startsWith("-")) {
|
|
692
|
+
if (takesValue(word))
|
|
693
|
+
at++;
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
seen++;
|
|
697
|
+
if (seen === count)
|
|
698
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
699
|
+
}
|
|
700
|
+
return { own: args, rest: undefined };
|
|
701
|
+
}
|
|
702
|
+
function listed(options, allowNegative) {
|
|
703
|
+
if (!allowNegative)
|
|
704
|
+
return options;
|
|
705
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
706
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
707
|
+
return [[name, option]];
|
|
708
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
709
|
+
}));
|
|
710
|
+
}
|
|
711
|
+
function withAliases(args, options) {
|
|
712
|
+
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
713
|
+
if (named.size === 0)
|
|
714
|
+
return args;
|
|
715
|
+
const separator = args.indexOf("--");
|
|
716
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
717
|
+
return [...own.map((arg) => {
|
|
718
|
+
const at = arg.indexOf("=");
|
|
719
|
+
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
720
|
+
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
721
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
722
|
+
}
|
|
723
|
+
function withBare(args, options) {
|
|
724
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
725
|
+
if (bare.size === 0)
|
|
726
|
+
return args;
|
|
727
|
+
const separator = args.indexOf("--");
|
|
728
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
729
|
+
return [...own.flatMap((arg, index) => {
|
|
730
|
+
const optional = bare.get(arg);
|
|
731
|
+
const next = own[index + 1];
|
|
732
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
733
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
734
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
735
|
+
}
|
|
736
|
+
function checkConflicts(values, options) {
|
|
737
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
738
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
739
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
740
|
+
if (other !== undefined)
|
|
741
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
function checkChoices(values, options) {
|
|
745
|
+
for (const [name, option] of Object.entries(options)) {
|
|
746
|
+
if (option.choices === undefined)
|
|
747
|
+
continue;
|
|
748
|
+
const given = values[name];
|
|
749
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
750
|
+
if (typeof value === "string")
|
|
751
|
+
oneOf(value, name, option.choices);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
function oneOf(value, name, choices) {
|
|
756
|
+
if (!choices.includes(value))
|
|
757
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
758
|
+
return value;
|
|
759
|
+
}
|
|
760
|
+
function checkPositionals(given, names) {
|
|
761
|
+
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
762
|
+
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
763
|
+
if (given.length < required)
|
|
764
|
+
badUsage(`missing ${names[given.length]}`);
|
|
765
|
+
if (!variadic && given.length > names.length)
|
|
766
|
+
badUsage(`unexpected argument ${given[names.length]}`);
|
|
767
|
+
}
|
|
768
|
+
function joinDashValues(args, options) {
|
|
769
|
+
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
770
|
+
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
771
|
+
const joined = [];
|
|
772
|
+
for (let i = 0;i < args.length; i++) {
|
|
773
|
+
const arg = args[i] ?? "";
|
|
774
|
+
if (arg === "--")
|
|
775
|
+
return [...joined, ...args.slice(i)];
|
|
776
|
+
const name = longOf.get(arg);
|
|
777
|
+
const next = args[i + 1];
|
|
778
|
+
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
779
|
+
joined.push(`--${name}=${next}`);
|
|
780
|
+
i++;
|
|
781
|
+
} else {
|
|
782
|
+
joined.push(arg);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
return joined;
|
|
786
|
+
}
|
|
787
|
+
function parseError(error) {
|
|
788
|
+
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
789
|
+
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
790
|
+
}
|
|
791
|
+
var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
792
|
+
function nearestOption(message, options, allowNegative) {
|
|
793
|
+
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
794
|
+
if (typed === undefined)
|
|
795
|
+
return;
|
|
796
|
+
const word = typed.replace(DASHES, "");
|
|
797
|
+
if (word.length < 2 && !typed.startsWith("--"))
|
|
798
|
+
return;
|
|
799
|
+
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
800
|
+
...option.short === undefined ? [] : [`-${option.short}`],
|
|
801
|
+
`--${name}`,
|
|
802
|
+
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
803
|
+
]);
|
|
804
|
+
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
805
|
+
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
806
|
+
}
|
|
807
|
+
// ../kit/src/argv.ts
|
|
808
|
+
import { readFileSync as readFileSync3, realpathSync } from "fs";
|
|
809
|
+
import { resolve as resolve3 } from "path";
|
|
810
|
+
import process10 from "process";
|
|
811
|
+
function commandLine() {
|
|
812
|
+
try {
|
|
813
|
+
return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
814
|
+
} catch {
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
function realPath(word) {
|
|
819
|
+
try {
|
|
820
|
+
return realpathSync(resolve3(word));
|
|
821
|
+
} catch {
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
826
|
+
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
827
|
+
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
828
|
+
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
829
|
+
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
830
|
+
}
|
|
831
|
+
// ../kit/src/progress.ts
|
|
832
|
+
import process12 from "process";
|
|
833
|
+
|
|
834
|
+
// ../kit/src/process.ts
|
|
835
|
+
import { constants } from "os";
|
|
836
|
+
import process11 from "process";
|
|
837
|
+
var KILL_GRACE_MS = 2000;
|
|
838
|
+
var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
839
|
+
function exitCodeOf(code, signal) {
|
|
840
|
+
if (code !== null)
|
|
841
|
+
return code;
|
|
842
|
+
if (typeof signal === "number")
|
|
843
|
+
return 128 + signal;
|
|
844
|
+
return signal === null ? 129 : 128 + constants.signals[signal];
|
|
845
|
+
}
|
|
846
|
+
function holdSignals(cleanup) {
|
|
847
|
+
let received;
|
|
848
|
+
let child;
|
|
849
|
+
const held = {
|
|
850
|
+
get signal() {
|
|
851
|
+
return received;
|
|
852
|
+
},
|
|
853
|
+
forward: (to) => {
|
|
854
|
+
child = to;
|
|
855
|
+
},
|
|
856
|
+
release: () => {
|
|
857
|
+
for (const signal of SIGNALS)
|
|
858
|
+
process11.off(signal, onSignal);
|
|
859
|
+
}
|
|
860
|
+
};
|
|
861
|
+
function onSignal(signal) {
|
|
862
|
+
received = signal;
|
|
863
|
+
if (child !== undefined) {
|
|
864
|
+
child.kill(signal);
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
if (cleanup === undefined)
|
|
868
|
+
return;
|
|
869
|
+
held.release();
|
|
870
|
+
cleanup(signal);
|
|
871
|
+
process11.kill(process11.pid, signal);
|
|
872
|
+
}
|
|
873
|
+
for (const signal of SIGNALS)
|
|
874
|
+
process11.on(signal, onSignal);
|
|
875
|
+
return held;
|
|
876
|
+
}
|
|
877
|
+
async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
878
|
+
const chunks = [];
|
|
879
|
+
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
|
|
880
|
+
const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
|
|
881
|
+
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
|
|
882
|
+
const timers = [];
|
|
883
|
+
const killGroup = (killing) => {
|
|
884
|
+
if (state.done)
|
|
885
|
+
return;
|
|
886
|
+
try {
|
|
887
|
+
if (grouped)
|
|
888
|
+
process11.kill(-proc.pid, killing);
|
|
889
|
+
else
|
|
890
|
+
proc.kill(killing);
|
|
891
|
+
} catch {}
|
|
892
|
+
};
|
|
893
|
+
const stop = () => {
|
|
894
|
+
killGroup("SIGTERM");
|
|
895
|
+
timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
|
|
896
|
+
};
|
|
897
|
+
const onAbort = () => stop();
|
|
898
|
+
if (timeoutMs !== undefined) {
|
|
899
|
+
timers.push(setTimeout(() => {
|
|
900
|
+
state.timedOut = true;
|
|
901
|
+
stop();
|
|
902
|
+
}, timeoutMs));
|
|
903
|
+
}
|
|
904
|
+
if (signal?.aborted === true)
|
|
905
|
+
onAbort();
|
|
906
|
+
else
|
|
907
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
908
|
+
onStart?.({ kill: (killing) => killGroup(killing) });
|
|
909
|
+
const drain = async (stream, name) => {
|
|
910
|
+
for await (const data of stream) {
|
|
911
|
+
if (state.failure !== undefined)
|
|
912
|
+
continue;
|
|
913
|
+
try {
|
|
914
|
+
onChunk?.({ stream: name, data });
|
|
915
|
+
} catch (error) {
|
|
916
|
+
state.failure = error;
|
|
917
|
+
stop();
|
|
918
|
+
continue;
|
|
919
|
+
}
|
|
920
|
+
if (state.kept + data.length > maxBytes) {
|
|
921
|
+
state.truncated = true;
|
|
922
|
+
continue;
|
|
923
|
+
}
|
|
924
|
+
state.kept += data.length;
|
|
925
|
+
chunks.push({ stream: name, data });
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
try {
|
|
929
|
+
await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
|
|
930
|
+
await proc.exited;
|
|
931
|
+
} finally {
|
|
932
|
+
state.done = true;
|
|
933
|
+
for (const timer of timers)
|
|
934
|
+
clearTimeout(timer);
|
|
935
|
+
signal?.removeEventListener("abort", onAbort);
|
|
936
|
+
}
|
|
937
|
+
if (state.failure !== undefined)
|
|
938
|
+
throw state.failure;
|
|
939
|
+
const joined = () => Buffer.concat(chunks.map(({ data }) => data));
|
|
940
|
+
let output;
|
|
941
|
+
let text;
|
|
942
|
+
return {
|
|
943
|
+
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
944
|
+
chunks,
|
|
945
|
+
timedOut: state.timedOut,
|
|
946
|
+
truncated: state.truncated,
|
|
947
|
+
get output() {
|
|
948
|
+
return output ??= joined();
|
|
949
|
+
},
|
|
950
|
+
get text() {
|
|
951
|
+
return text ??= (output ??= joined()).toString();
|
|
952
|
+
}
|
|
953
|
+
};
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
// ../kit/src/progress.ts
|
|
957
|
+
var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
958
|
+
var FRAME_MS = 200;
|
|
959
|
+
var BAR_WIDTH = 20;
|
|
960
|
+
var CLEAR_BELOW = "\r\x1B[J";
|
|
961
|
+
var ESC = String.fromCharCode(27);
|
|
962
|
+
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
963
|
+
var RESET_STYLE = `${ESC}[0m`;
|
|
964
|
+
var CTRL_C = 3;
|
|
965
|
+
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
966
|
+
var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
|
|
967
|
+
function liveRegion(render, stream = process12.stderr, env = process12.env) {
|
|
968
|
+
if (!takesControlCodes(stream, env))
|
|
969
|
+
return { redraw: () => {
|
|
970
|
+
return;
|
|
971
|
+
}, print: (text) => void stream.write(`${text}
|
|
972
|
+
`), stop: () => {
|
|
973
|
+
return;
|
|
974
|
+
} };
|
|
975
|
+
const write = stream.write.bind(stream);
|
|
976
|
+
let frame = 0;
|
|
977
|
+
let drawn = false;
|
|
978
|
+
const columns = () => {
|
|
979
|
+
const now = stream.getWindowSize?.()[0] ?? stream.columns;
|
|
980
|
+
return now === undefined || now === 0 ? 80 : now;
|
|
981
|
+
};
|
|
982
|
+
const clear = () => {
|
|
983
|
+
if (drawn)
|
|
984
|
+
write(CLEAR_BELOW);
|
|
985
|
+
drawn = false;
|
|
986
|
+
};
|
|
987
|
+
const draw = () => {
|
|
988
|
+
const width = columns() - 1;
|
|
989
|
+
const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
|
|
990
|
+
const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
|
|
991
|
+
if (lines.length === 0) {
|
|
992
|
+
clear();
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
write(`${CLEAR_BELOW}${lines.join(`
|
|
996
|
+
`)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
|
|
997
|
+
drawn = true;
|
|
998
|
+
};
|
|
999
|
+
const timer = setInterval(draw, FRAME_MS);
|
|
1000
|
+
stream.on?.("resize", draw);
|
|
1001
|
+
const restore = interceptOutput(clear);
|
|
1002
|
+
const release = swallowInput();
|
|
1003
|
+
const onExit = () => {
|
|
1004
|
+
clear();
|
|
1005
|
+
release();
|
|
1006
|
+
};
|
|
1007
|
+
const signals = holdSignals(stop);
|
|
1008
|
+
function stop() {
|
|
1009
|
+
clearInterval(timer);
|
|
1010
|
+
stream.off?.("resize", draw);
|
|
1011
|
+
clear();
|
|
1012
|
+
restore();
|
|
1013
|
+
release();
|
|
1014
|
+
process12.off("exit", onExit);
|
|
1015
|
+
signals.release();
|
|
1016
|
+
}
|
|
1017
|
+
timer.unref();
|
|
1018
|
+
process12.on("exit", onExit);
|
|
1019
|
+
return {
|
|
1020
|
+
redraw: draw,
|
|
1021
|
+
print: (text) => {
|
|
1022
|
+
clear();
|
|
1023
|
+
write(`${text}
|
|
1024
|
+
`);
|
|
1025
|
+
draw();
|
|
1026
|
+
},
|
|
1027
|
+
stop
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
function progressLine(stream = process12.stderr, env = process12.env) {
|
|
1031
|
+
const colors = paint(stream, env);
|
|
1032
|
+
const write = stream.write.bind(stream);
|
|
1033
|
+
const begun = performance.now();
|
|
1034
|
+
let started = begun;
|
|
1035
|
+
let current;
|
|
1036
|
+
const region = liveRegion((spinner) => current === undefined ? [] : [tintedParts(progressParts(current, spinner, performance.now() - started), colors)], stream, env);
|
|
1037
|
+
const end = (line) => {
|
|
1038
|
+
region.stop();
|
|
1039
|
+
write(`${line}
|
|
1040
|
+
`);
|
|
1041
|
+
};
|
|
1042
|
+
return {
|
|
1043
|
+
update: (progress) => {
|
|
1044
|
+
const step = current?.step;
|
|
1045
|
+
current = progress;
|
|
1046
|
+
if (progress.step !== step) {
|
|
1047
|
+
started = performance.now();
|
|
1048
|
+
region.redraw();
|
|
1049
|
+
}
|
|
1050
|
+
},
|
|
1051
|
+
stop: region.stop,
|
|
1052
|
+
done: (text) => end(marked("ok", text, stream, formatDuration(performance.now() - begun), env)),
|
|
1053
|
+
failed: (text) => end(marked("problem", text, stream, undefined, env))
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
function progressParts({ step, done, total, unit }, spinner, ms) {
|
|
1057
|
+
const { theme } = activeTheme();
|
|
1058
|
+
const parts = [{ text: spinner, tint: (colors) => tinted(colors, theme.colors.accent) }, { text: ` ${step}`, tint: () => plain }];
|
|
1059
|
+
if (total !== undefined && total > 0) {
|
|
1060
|
+
const counted = Math.min(done ?? 0, total);
|
|
1061
|
+
const filled = Math.round(counted / total * BAR_WIDTH);
|
|
1062
|
+
parts.push({ text: " ", tint: () => plain }, { text: theme.glyphs.bar.repeat(filled), tint: (colors) => () => shaded(theme, colors, theme.glyphs.bar, filled, BAR_WIDTH) }, { text: theme.glyphs.bar.repeat(BAR_WIDTH - filled), tint: (colors) => colors.dim }, { text: ` ${counted}/${total}${unit === undefined ? "" : ` ${unit}`}`, tint: (colors) => colors.dim });
|
|
1063
|
+
}
|
|
1064
|
+
parts.push({ text: ` ${formatElapsed(ms)}`, tint: (colors) => colors.dim });
|
|
1065
|
+
return parts;
|
|
1066
|
+
}
|
|
1067
|
+
function plain(text) {
|
|
1068
|
+
return text;
|
|
1069
|
+
}
|
|
1070
|
+
function tintedParts(parts, colors) {
|
|
1071
|
+
return parts.map(({ text, tint }) => tint(colors)(text)).join("");
|
|
1072
|
+
}
|
|
1073
|
+
function cutToWidth(line, width) {
|
|
1074
|
+
if (Bun.stringWidth(line) <= width)
|
|
1075
|
+
return line;
|
|
1076
|
+
let room = width;
|
|
1077
|
+
let kept = "";
|
|
1078
|
+
let index = 0;
|
|
1079
|
+
let linked = false;
|
|
1080
|
+
while (index < line.length) {
|
|
1081
|
+
ESCAPE_CODE.lastIndex = index;
|
|
1082
|
+
const escape = ESCAPE_CODE.exec(line);
|
|
1083
|
+
if (escape !== null) {
|
|
1084
|
+
kept += escape[0];
|
|
1085
|
+
linked ||= escape[0].startsWith(`${ESC}]`);
|
|
1086
|
+
index = ESCAPE_CODE.lastIndex;
|
|
1087
|
+
continue;
|
|
1088
|
+
}
|
|
1089
|
+
const char = String.fromCodePoint(line.codePointAt(index));
|
|
1090
|
+
const columns = Bun.stringWidth(char);
|
|
1091
|
+
if (columns > room)
|
|
1092
|
+
break;
|
|
1093
|
+
kept += char;
|
|
1094
|
+
room -= columns;
|
|
1095
|
+
index += char.length;
|
|
1096
|
+
}
|
|
1097
|
+
return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
|
|
1098
|
+
}
|
|
1099
|
+
function swallowInput() {
|
|
1100
|
+
const input = process12.stdin;
|
|
1101
|
+
if (!input.isTTY)
|
|
1102
|
+
return () => {
|
|
1103
|
+
return;
|
|
1104
|
+
};
|
|
1105
|
+
const onData = (data) => {
|
|
1106
|
+
if (data.includes(CTRL_C))
|
|
1107
|
+
process12.kill(process12.pid, "SIGINT");
|
|
1108
|
+
};
|
|
1109
|
+
input.setRawMode(true);
|
|
1110
|
+
input.on("data", onData);
|
|
1111
|
+
input.resume();
|
|
1112
|
+
let released = false;
|
|
1113
|
+
return () => {
|
|
1114
|
+
if (released)
|
|
1115
|
+
return;
|
|
1116
|
+
released = true;
|
|
1117
|
+
input.off("data", onData);
|
|
1118
|
+
input.pause();
|
|
1119
|
+
input.setRawMode(false);
|
|
1120
|
+
};
|
|
1121
|
+
}
|
|
1122
|
+
function interceptOutput(clear) {
|
|
1123
|
+
const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
|
|
1124
|
+
const wrapped = targets.map(([target, name]) => {
|
|
1125
|
+
const original = Reflect.get(target, name);
|
|
1126
|
+
const wrapper = (...args) => {
|
|
1127
|
+
clear();
|
|
1128
|
+
return original.apply(target, args);
|
|
1129
|
+
};
|
|
1130
|
+
Reflect.set(target, name, wrapper);
|
|
1131
|
+
return { target, name, original, wrapper };
|
|
1132
|
+
});
|
|
1133
|
+
return () => {
|
|
1134
|
+
for (const { target, name, original, wrapper } of wrapped) {
|
|
1135
|
+
if (Reflect.get(target, name) === wrapper)
|
|
1136
|
+
Reflect.set(target, name, original);
|
|
1137
|
+
}
|
|
1138
|
+
};
|
|
1139
|
+
}
|
|
1140
|
+
// ../kit/src/cli.ts
|
|
1141
|
+
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
1142
|
+
import { dirname as dirname3, join as join5 } from "path";
|
|
1143
|
+
import process14 from "process";
|
|
1144
|
+
|
|
1145
|
+
// ../kit/src/usage.ts
|
|
1146
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
1147
|
+
import { homedir as homedir3 } from "os";
|
|
1148
|
+
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
1149
|
+
import process13 from "process";
|
|
1150
|
+
|
|
1151
|
+
// ../kit/src/logs.ts
|
|
1152
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1153
|
+
var CLI_FOLDER = "kaynooo-cli";
|
|
1154
|
+
|
|
1155
|
+
// ../kit/src/usage.ts
|
|
1156
|
+
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
1157
|
+
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
1158
|
+
var LONGEST_NAME = 40;
|
|
1159
|
+
var usageError;
|
|
1160
|
+
function noteUsageError(message) {
|
|
1161
|
+
usageError = message;
|
|
1162
|
+
}
|
|
1163
|
+
function stateHome(env = process13.env) {
|
|
1164
|
+
const dir = env.XDG_STATE_HOME;
|
|
1165
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
1166
|
+
}
|
|
1167
|
+
function usagePath(env = process13.env) {
|
|
1168
|
+
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1169
|
+
}
|
|
1170
|
+
function usageRecorded(env = process13.env) {
|
|
1171
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1172
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1173
|
+
}
|
|
1174
|
+
function flagNames(argv) {
|
|
1175
|
+
const end = argv.indexOf("--");
|
|
1176
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1177
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1178
|
+
}
|
|
1179
|
+
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
1180
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1181
|
+
usageError = undefined;
|
|
1182
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
1183
|
+
}
|
|
1184
|
+
function recordUsage(entry, env = process13.env) {
|
|
1185
|
+
if (!usageRecorded(env))
|
|
1186
|
+
return;
|
|
1187
|
+
try {
|
|
1188
|
+
const path = usagePath(env);
|
|
1189
|
+
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1190
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1191
|
+
`, { mode: 384 });
|
|
1192
|
+
} catch {}
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
// ../kit/src/cli.ts
|
|
1196
|
+
var LEVEL_OPTIONS = {
|
|
1197
|
+
...OUTPUT_OPTIONS,
|
|
1198
|
+
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1199
|
+
};
|
|
1200
|
+
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
1201
|
+
function printError(prefix, message, hint, cause) {
|
|
1202
|
+
const colors = paint(process14.stderr);
|
|
1203
|
+
const styled = takesControlCodes(process14.stderr);
|
|
1204
|
+
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1205
|
+
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1206
|
+
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1207
|
+
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1208
|
+
}
|
|
1209
|
+
function runHint(command, effect) {
|
|
1210
|
+
return `run \`${command}\`${effect === undefined ? "" : ` to ${effect}`}`;
|
|
1211
|
+
}
|
|
1212
|
+
function printJsonError(message, hint, cause) {
|
|
1213
|
+
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1214
|
+
}
|
|
1215
|
+
function wantsJson(argv) {
|
|
1216
|
+
const end = argv.indexOf("--");
|
|
1217
|
+
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1218
|
+
}
|
|
1219
|
+
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1220
|
+
if (error instanceof HelpShown)
|
|
1221
|
+
return 0;
|
|
1222
|
+
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1223
|
+
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1224
|
+
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1225
|
+
if (error instanceof Exit && error.code === 2)
|
|
1226
|
+
noteUsageError(error.message);
|
|
1227
|
+
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1228
|
+
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1229
|
+
return error instanceof Exit ? error.code : 1;
|
|
1230
|
+
}
|
|
1231
|
+
var COMPLETE = "__complete";
|
|
1232
|
+
var FILES = "__files__";
|
|
1233
|
+
async function completingOf(run) {
|
|
1234
|
+
completion.active = true;
|
|
1235
|
+
try {
|
|
1236
|
+
await run([]);
|
|
1237
|
+
} catch (error) {
|
|
1238
|
+
if (error instanceof Completing)
|
|
1239
|
+
return error;
|
|
1240
|
+
} finally {
|
|
1241
|
+
completion.active = false;
|
|
1242
|
+
}
|
|
1243
|
+
return new Completing({});
|
|
1244
|
+
}
|
|
1245
|
+
function candidateLine(candidate) {
|
|
1246
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1247
|
+
}
|
|
1248
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
1249
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1250
|
+
const typed = [];
|
|
1251
|
+
let at = 0;
|
|
1252
|
+
while (at < before.length) {
|
|
1253
|
+
const word = before[at];
|
|
1254
|
+
if (word === "--") {
|
|
1255
|
+
typed.push(...before.slice(at + 1));
|
|
1256
|
+
break;
|
|
1257
|
+
}
|
|
1258
|
+
if (!word.startsWith("-"))
|
|
1259
|
+
typed.push(word);
|
|
1260
|
+
else if (takesValue(word))
|
|
1261
|
+
at++;
|
|
1262
|
+
at++;
|
|
1263
|
+
}
|
|
1264
|
+
const last = positionals.at(-1);
|
|
1265
|
+
if (typed.length < positionals.length)
|
|
1266
|
+
return { name: positionals[typed.length], typed };
|
|
1267
|
+
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1268
|
+
}
|
|
1269
|
+
async function leafCandidates(run, words) {
|
|
1270
|
+
const completing = await completingOf(run);
|
|
1271
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1272
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1273
|
+
const flag = words.at(-2);
|
|
1274
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1275
|
+
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1276
|
+
if (option?.type === "string") {
|
|
1277
|
+
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1278
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1279
|
+
}
|
|
1280
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1281
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1282
|
+
}
|
|
1283
|
+
async function printCandidates(found) {
|
|
1284
|
+
for (const line of await found)
|
|
1285
|
+
console.log(line);
|
|
1286
|
+
return 0;
|
|
1287
|
+
}
|
|
1288
|
+
function packageVersion(entry = Bun.main) {
|
|
1289
|
+
let resolved = entry;
|
|
1290
|
+
try {
|
|
1291
|
+
resolved = realpathSync2(entry);
|
|
1292
|
+
} catch {}
|
|
1293
|
+
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1294
|
+
try {
|
|
1295
|
+
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
1296
|
+
if (typeof version === "string")
|
|
1297
|
+
return version;
|
|
1298
|
+
} catch {}
|
|
1299
|
+
if (dirname3(dir) === dir)
|
|
1300
|
+
return "0.0.0";
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1304
|
+
if (argv[0] === COMPLETE)
|
|
1305
|
+
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1306
|
+
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1307
|
+
console.log(version ?? packageVersion());
|
|
1308
|
+
return 0;
|
|
1309
|
+
}
|
|
1310
|
+
let code;
|
|
1311
|
+
try {
|
|
1312
|
+
code = await run(argv);
|
|
1313
|
+
} catch (error) {
|
|
1314
|
+
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1315
|
+
}
|
|
1316
|
+
if (usage !== false) {
|
|
1317
|
+
try {
|
|
1318
|
+
recordUsage(usageEntry(name, undefined, argv, code));
|
|
1319
|
+
} catch {}
|
|
1320
|
+
}
|
|
1321
|
+
return code;
|
|
1322
|
+
}
|
|
1323
|
+
// ../kit/src/folders.ts
|
|
1324
|
+
var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
1325
|
+
// ../kit/src/secrets.ts
|
|
1326
|
+
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1327
|
+
// ../kit/src/sessions.ts
|
|
1328
|
+
var {Glob } = globalThis.Bun;
|
|
1329
|
+
var SESSION_FILES = new Glob("*.json");
|
|
1330
|
+
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1331
|
+
// ../kit/src/watch.ts
|
|
1332
|
+
import process15 from "process";
|
|
1333
|
+
import { format } from "util";
|
|
1334
|
+
var CLEAR_SCREEN = "\x1B[H\x1B[2J";
|
|
1335
|
+
var DEFAULT_SECONDS = 2;
|
|
1336
|
+
var ATTACHED_SHORT = /^-w./;
|
|
1337
|
+
var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
|
|
1338
|
+
function watchOption(what) {
|
|
1339
|
+
return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
|
|
1340
|
+
}
|
|
1341
|
+
function withoutWatch(args) {
|
|
1342
|
+
const rest = [];
|
|
1343
|
+
for (let at = 0;at < args.length; at++) {
|
|
1344
|
+
const arg = args[at];
|
|
1345
|
+
if (arg === "--watch" || arg === "-w") {
|
|
1346
|
+
if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
|
|
1347
|
+
at++;
|
|
1348
|
+
} else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
|
|
1349
|
+
rest.push(arg);
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
return rest;
|
|
1353
|
+
}
|
|
1354
|
+
async function watching(value, step, stream = process15.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
|
|
1355
|
+
const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
|
|
1356
|
+
if (!takesControlCodes(stream))
|
|
1357
|
+
badUsage("--watch redraws the screen, so it needs a terminal");
|
|
1358
|
+
let code = 0;
|
|
1359
|
+
for (let round = 0;round < rounds; round++) {
|
|
1360
|
+
const held = [];
|
|
1361
|
+
const { log, info } = console;
|
|
1362
|
+
const write = process15.stdout.write.bind(process15.stdout);
|
|
1363
|
+
const hold = (...parts) => void held.push(`${format(...parts)}
|
|
1364
|
+
`);
|
|
1365
|
+
console.log = hold;
|
|
1366
|
+
console.info = hold;
|
|
1367
|
+
process15.stdout.write = (text) => {
|
|
1368
|
+
held.push(typeof text === "string" ? text : Buffer.from(text).toString());
|
|
1369
|
+
return true;
|
|
1370
|
+
};
|
|
1371
|
+
try {
|
|
1372
|
+
code = await step();
|
|
1373
|
+
} finally {
|
|
1374
|
+
console.log = log;
|
|
1375
|
+
console.info = info;
|
|
1376
|
+
process15.stdout.write = write;
|
|
1377
|
+
}
|
|
1378
|
+
stream.write(`${CLEAR_SCREEN}${held.join("")}`);
|
|
1379
|
+
await sleep(interval);
|
|
1380
|
+
}
|
|
1381
|
+
return code;
|
|
1382
|
+
}
|
|
1383
|
+
// ../kit/src/workspace-root.ts
|
|
1384
|
+
import { homedir as homedir4 } from "os";
|
|
1385
|
+
import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
|
|
1386
|
+
import process16 from "process";
|
|
1387
|
+
function expandHome(path, home) {
|
|
1388
|
+
if (path === "~")
|
|
1389
|
+
return home;
|
|
1390
|
+
return path.startsWith("~/") ? join6(home, path.slice(2)) : path;
|
|
1391
|
+
}
|
|
1392
|
+
function configured(env, home) {
|
|
1393
|
+
const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
|
|
1394
|
+
return typeof folder === "string" && folder !== "" ? folder : undefined;
|
|
1395
|
+
}
|
|
1396
|
+
function workspaceRoot({ given, env = process16.env, home = homedir4() } = {}) {
|
|
1397
|
+
const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
|
|
1398
|
+
return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
|
|
1399
|
+
}
|
|
1400
|
+
// src/git.ts
|
|
1401
|
+
async function git2(args, env) {
|
|
1402
|
+
const ran = await runCommand(["git", "--no-optional-locks", "-c", "core.quotePath=false", ...args], env === undefined ? {} : { env });
|
|
1403
|
+
const text = (stream) => Buffer.concat(ran.chunks.filter((chunk) => chunk.stream === stream).map((chunk) => chunk.data)).toString();
|
|
1404
|
+
return { code: ran.code, stdout: text("stdout"), stderr: text("stderr") };
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
// src/gu.ts
|
|
1408
|
+
var USAGE = `gu <path>...: undoes changes to the paths given, keeping what it takes away
|
|
1409
|
+
|
|
1410
|
+
By default it discards the unstaged changes of the tracked paths, after saving them as a patch in the git folder (gu/<time>.patch) that \`git apply\` puts back. --staged unstages the paths and loses nothing. --commit undoes the last commit, its changes left staged, and refuses a commit that is already on the upstream or a merge.
|
|
1411
|
+
Nothing is discarded without a path: gu alone is a usage error, never "everything". A path with no change is refused with nothing done.`;
|
|
1412
|
+
var EXITS = [[0, "it undid what was asked"], [1, "a path has no change, the commit is pushed or git refused"], [2, "a usage error or outside a git repository"]];
|
|
1413
|
+
var OPTIONS = {
|
|
1414
|
+
staged: { type: "boolean", short: "s", description: "unstage the paths, the working tree untouched" },
|
|
1415
|
+
commit: { type: "boolean", short: "c", description: "undo the last commit, keeping its changes staged" },
|
|
1416
|
+
json: jsonOption("{action, paths?, saved?, commit?} of what was undone, saved being the patch of a discard")
|
|
1417
|
+
};
|
|
1418
|
+
var LITERAL = { ...process18.env, GIT_LITERAL_PATHSPECS: "1" };
|
|
1419
|
+
var NOT_A_REPOSITORY = /not a git repository/i;
|
|
1420
|
+
async function checked(args) {
|
|
1421
|
+
const { code, stdout, stderr } = await git2(args, LITERAL);
|
|
1422
|
+
if (code !== 0)
|
|
1423
|
+
fail(`git ${args[0]} failed, nothing undone:
|
|
1424
|
+
${stderr.trim()}`, NOT_A_REPOSITORY.test(stderr) ? 2 : 1);
|
|
1425
|
+
return stdout;
|
|
1426
|
+
}
|
|
1427
|
+
async function changed(paths, cached) {
|
|
1428
|
+
const out = await checked(["diff", ...cached ? ["--cached"] : [], "--name-only", "-z", "--", ...paths]);
|
|
1429
|
+
return out.split("\x00").filter(Boolean);
|
|
1430
|
+
}
|
|
1431
|
+
async function undoCommit() {
|
|
1432
|
+
const read = await git2(["log", "-1", "--format=%h%x00%P%x00%s"], LITERAL);
|
|
1433
|
+
if (read.code !== 0)
|
|
1434
|
+
fail(NOT_A_REPOSITORY.test(read.stderr) ? "not inside a git repository" : "there is no commit to undo", NOT_A_REPOSITORY.test(read.stderr) ? 2 : 1);
|
|
1435
|
+
const [sha = "", parents = "", title = ""] = read.stdout.trim().split("\x00");
|
|
1436
|
+
const count = parents.split(" ").filter(Boolean).length;
|
|
1437
|
+
if ((await git2(["merge-base", "--is-ancestor", "HEAD", "@{upstream}"])).code === 0)
|
|
1438
|
+
fail(`${sha} is already on the upstream, undo it with a revert instead`, 1);
|
|
1439
|
+
if (count !== 1)
|
|
1440
|
+
fail(count === 0 ? `${sha} is the first commit, there is nothing before it to go back to` : `${sha} is a merge, gu does not undo those`, 1);
|
|
1441
|
+
await checked(["reset", "--soft", "HEAD~1"]);
|
|
1442
|
+
return { sha, title };
|
|
1443
|
+
}
|
|
1444
|
+
async function main(argv) {
|
|
1445
|
+
const { values, positionals } = parse(argv, USAGE, OPTIONS, { positionals: ["[path]..."], exits: EXITS, replaces: "git restore, git restore --staged and git reset --soft HEAD~1 typed blind", examples: [["gu src/a.ts", "discard its unstaged changes, saved as a patch"], ["gu --staged src/a.ts", "unstage it"], ["gu --commit", "undo the last commit, changes staged"]] });
|
|
1446
|
+
if (values.commit === true) {
|
|
1447
|
+
if (values.staged === true || positionals.length > 0)
|
|
1448
|
+
badUsage("--commit undoes the whole last commit: it takes no path and no --staged");
|
|
1449
|
+
const undone = await undoCommit();
|
|
1450
|
+
if (values.json === true)
|
|
1451
|
+
printJson({ action: "commit", commit: undone });
|
|
1452
|
+
else
|
|
1453
|
+
console.log(`undid ${undone.sha} ${undone.title}, its changes are staged (git reflog keeps the commit)`);
|
|
1454
|
+
return 0;
|
|
1455
|
+
}
|
|
1456
|
+
if (positionals.length === 0)
|
|
1457
|
+
badUsage("gu needs the paths to undo: gu src/a.ts (--commit undoes the last commit)");
|
|
1458
|
+
const staged = values.staged === true;
|
|
1459
|
+
const each = await Promise.all(positionals.map(async (path) => changed([path], staged)));
|
|
1460
|
+
const unchanged = positionals.filter((_, at) => each[at]?.length === 0);
|
|
1461
|
+
if (unchanged.length > 0)
|
|
1462
|
+
fail(`no ${staged ? "staged" : "unstaged"} change in ${unchanged.join(", ")}, nothing undone`, 1);
|
|
1463
|
+
const paths = [...new Set(each.flat())];
|
|
1464
|
+
if (staged) {
|
|
1465
|
+
await checked(["restore", "--staged", "--", ...positionals]);
|
|
1466
|
+
if (values.json === true)
|
|
1467
|
+
printJson({ action: "unstage", paths });
|
|
1468
|
+
else
|
|
1469
|
+
console.log(`unstaged ${paths.join(", ")}`);
|
|
1470
|
+
return 0;
|
|
1471
|
+
}
|
|
1472
|
+
const patch = await checked(["diff", "--binary", "--", ...positionals]);
|
|
1473
|
+
const folder = join7(resolve5((await checked(["rev-parse", "--git-dir"])).trim()), "gu");
|
|
1474
|
+
const saved = join7(folder, `${new Date().toISOString().replaceAll(":", "-")}.patch`);
|
|
1475
|
+
mkdirSync2(folder, { recursive: true });
|
|
1476
|
+
writeFileSync(saved, patch);
|
|
1477
|
+
await checked(["restore", "--", ...positionals]);
|
|
1478
|
+
if (values.json === true)
|
|
1479
|
+
printJson({ action: "discard", paths, saved });
|
|
1480
|
+
else
|
|
1481
|
+
console.log(`discarded ${paths.join(", ")}, saved to ${saved} (git apply puts it back)`);
|
|
1482
|
+
return 0;
|
|
1483
|
+
}
|
|
1484
|
+
process18.exitCode = await runMain({ name: "gu", run: main });
|