@kaynooo/cli-changelog 0.0.0-stage → 2.4.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/LICENSE +21 -0
- package/README.md +212 -2
- package/dist/cli.js +3038 -0
- package/package.json +33 -4
- package/src/changelog.ts +150 -0
- package/src/cli.ts +298 -0
- package/src/config.ts +147 -0
- package/src/discord.ts +158 -0
- package/src/flags.ts +92 -0
- package/src/generate.ts +23 -0
- package/src/git.ts +166 -0
- package/src/gitea.ts +326 -0
- package/src/highlights.ts +142 -0
- package/src/index.ts +9 -0
- package/src/markdown.ts +199 -0
- package/src/parse.ts +8 -0
- package/src/types.ts +185 -0
- package/src/ui.ts +20 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,3038 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
// @bun 2>/dev/null; exec bun --config=/dev/null "$0" "$@"
|
|
3
|
+
var __esm = (fn, res, err) => () => {
|
|
4
|
+
if (fn)
|
|
5
|
+
try {
|
|
6
|
+
res = fn(fn = 0);
|
|
7
|
+
} catch (e) {
|
|
8
|
+
err = [e];
|
|
9
|
+
}
|
|
10
|
+
if (err)
|
|
11
|
+
throw err[0];
|
|
12
|
+
return res;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-yfkscv18.js
|
|
16
|
+
var b, M, n;
|
|
17
|
+
var init_chunk_yfkscv18 = __esm(() => {
|
|
18
|
+
b = new TextEncoder;
|
|
19
|
+
M = new TextDecoder("utf-8", { fatal: true });
|
|
20
|
+
n = { y: 31536000000, M: 2592000000, w: 604800000, d: 86400000, h: 3600000, m: 60000, s: 1000 };
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
|
|
24
|
+
function d(t) {
|
|
25
|
+
return t.charAt(0).toUpperCase() + t.slice(1);
|
|
26
|
+
}
|
|
27
|
+
function G(t, e, { plural: r, zero: n = "singular" } = {}) {
|
|
28
|
+
if (e === 1 || e === 0 && n === "singular")
|
|
29
|
+
return t;
|
|
30
|
+
if (r !== undefined)
|
|
31
|
+
return r;
|
|
32
|
+
if (t.endsWith("y") && !ct.test(t))
|
|
33
|
+
return `${t.slice(0, -1)}ies`;
|
|
34
|
+
if (t.endsWith("s") || t.endsWith("x") || t.endsWith("z") || t.endsWith("ch") || t.endsWith("sh"))
|
|
35
|
+
return `${t}es`;
|
|
36
|
+
if (Ot.test(t))
|
|
37
|
+
return `${t.slice(0, -1)}ves`;
|
|
38
|
+
return Gt.test(t) ? `${t.slice(0, -2)}ves` : `${t}s`;
|
|
39
|
+
}
|
|
40
|
+
var ct, N, Ot, Gt, be, W;
|
|
41
|
+
var init_chunk_rkhsft4a = __esm(() => {
|
|
42
|
+
ct = /[aeiou]y$/;
|
|
43
|
+
N = new Map;
|
|
44
|
+
Ot = /(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/;
|
|
45
|
+
Gt = /(?:knife|life|wife)$/;
|
|
46
|
+
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));
|
|
47
|
+
W = new Map;
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
|
|
51
|
+
var init_text = __esm(() => {
|
|
52
|
+
init_chunk_rkhsft4a();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// ../kit/src/mode.ts
|
|
56
|
+
import process2 from "process";
|
|
57
|
+
function isSet(value) {
|
|
58
|
+
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
59
|
+
}
|
|
60
|
+
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
61
|
+
const chosen = env.KIT_MODE;
|
|
62
|
+
if (chosen !== undefined && MODES.has(chosen))
|
|
63
|
+
return chosen;
|
|
64
|
+
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
65
|
+
return "agent";
|
|
66
|
+
if (stream.isTTY === true)
|
|
67
|
+
return "terminal";
|
|
68
|
+
return isSet(env.CI) ? "ci" : "pipe";
|
|
69
|
+
}
|
|
70
|
+
function isInteractive(streams = process2) {
|
|
71
|
+
return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
|
|
72
|
+
}
|
|
73
|
+
var MODES, AGENT_VARIABLES;
|
|
74
|
+
var init_mode = __esm(() => {
|
|
75
|
+
MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
76
|
+
AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
80
|
+
function b2(r) {
|
|
81
|
+
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
82
|
+
if (!G2.test(e))
|
|
83
|
+
return [0, 0, 0];
|
|
84
|
+
if (e.length === 3 || e.length === 4)
|
|
85
|
+
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
86
|
+
if (e.length !== 6 && e.length !== 8)
|
|
87
|
+
throw Error(`Invalid hex color length: ${e.length}`);
|
|
88
|
+
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
89
|
+
}
|
|
90
|
+
function C(r, e = globalThis.process?.env ?? {}) {
|
|
91
|
+
if (e.FORCE_COLOR !== undefined)
|
|
92
|
+
return h.has(e.FORCE_COLOR);
|
|
93
|
+
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
94
|
+
return false;
|
|
95
|
+
return r?.isTTY === true;
|
|
96
|
+
}
|
|
97
|
+
function f(r, e = []) {
|
|
98
|
+
let l = "", n = "";
|
|
99
|
+
for (let t = 0, i = e.length;t < i; t++)
|
|
100
|
+
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
101
|
+
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
102
|
+
return new Proxy(c, { get(t, i) {
|
|
103
|
+
let a = B[i];
|
|
104
|
+
if (Array.isArray(a)) {
|
|
105
|
+
let s = g.get(i);
|
|
106
|
+
if (s === undefined)
|
|
107
|
+
s = f(r, [...e, a]), g.set(i, s);
|
|
108
|
+
return s;
|
|
109
|
+
}
|
|
110
|
+
if (typeof a === "function")
|
|
111
|
+
return (...s) => {
|
|
112
|
+
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
113
|
+
if (u === undefined) {
|
|
114
|
+
if (g.size >= 64)
|
|
115
|
+
g.clear();
|
|
116
|
+
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
117
|
+
}
|
|
118
|
+
return u;
|
|
119
|
+
};
|
|
120
|
+
throw Error(`Unknown style: ${String(i)}`);
|
|
121
|
+
} });
|
|
122
|
+
}
|
|
123
|
+
function Fe(r = {}) {
|
|
124
|
+
return f(r);
|
|
125
|
+
}
|
|
126
|
+
var G2, B, h, o;
|
|
127
|
+
var init_chunk_x450vn3m = __esm(() => {
|
|
128
|
+
G2 = /^[a-f0-9]+$/i;
|
|
129
|
+
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") => {
|
|
130
|
+
let [l, n, c] = b2(r);
|
|
131
|
+
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
132
|
+
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
133
|
+
h = new Set(["", "1", "2", "3", "true"]);
|
|
134
|
+
o = Fe();
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
|
|
138
|
+
var init_colors = __esm(() => {
|
|
139
|
+
init_chunk_x450vn3m();
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
// ../kit/src/config.ts
|
|
143
|
+
import { existsSync } from "fs";
|
|
144
|
+
import { dirname, join, resolve } from "path";
|
|
145
|
+
import process3 from "process";
|
|
146
|
+
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
147
|
+
const wanted = typeof names === "string" ? [names] : names;
|
|
148
|
+
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
149
|
+
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
150
|
+
if (found !== undefined)
|
|
151
|
+
return found;
|
|
152
|
+
if (stop(dir) || dirname(dir) === dir)
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
var init_config = __esm(() => {
|
|
157
|
+
init_args();
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
// ../kit/src/user-config.ts
|
|
161
|
+
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
162
|
+
import { homedir } from "os";
|
|
163
|
+
import { isAbsolute, join as join2 } from "path";
|
|
164
|
+
import process4 from "process";
|
|
165
|
+
function xdgFolder(value, fallback) {
|
|
166
|
+
return value !== undefined && isAbsolute(value) ? value : fallback;
|
|
167
|
+
}
|
|
168
|
+
function configBase(where = {}) {
|
|
169
|
+
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
170
|
+
return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
|
|
171
|
+
}
|
|
172
|
+
function userConfigPath(bin, where = {}) {
|
|
173
|
+
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
174
|
+
}
|
|
175
|
+
function userConfigReadPath(bin, legacy = [], where = {}) {
|
|
176
|
+
const current = userConfigPath(bin, where);
|
|
177
|
+
if (existsSync2(current))
|
|
178
|
+
return current;
|
|
179
|
+
const base = configBase(where);
|
|
180
|
+
return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
|
|
181
|
+
}
|
|
182
|
+
function readUserConfig(bin, where = {}, legacy = []) {
|
|
183
|
+
const path = userConfigReadPath(bin, legacy, where);
|
|
184
|
+
if (!existsSync2(path))
|
|
185
|
+
return {};
|
|
186
|
+
try {
|
|
187
|
+
const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
|
|
188
|
+
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
|
|
189
|
+
} catch {
|
|
190
|
+
return {};
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function configuredForge(where = {}) {
|
|
194
|
+
const value = readUserConfig("config", where).forge;
|
|
195
|
+
if (typeof value !== "string" || value.trim() === "")
|
|
196
|
+
return;
|
|
197
|
+
const url = (URL_SCHEME.test(value.trim()) ? value.trim() : `https://${value.trim()}`).replace(TRAILING_SLASHES, "");
|
|
198
|
+
return URL.canParse(url) ? { host: new URL(url).host, url } : undefined;
|
|
199
|
+
}
|
|
200
|
+
var URL_SCHEME, TRAILING_SLASHES;
|
|
201
|
+
var init_user_config = __esm(() => {
|
|
202
|
+
URL_SCHEME = /^[a-z][a-z\d+.-]*:\/\//i;
|
|
203
|
+
TRAILING_SLASHES = /\/+$/;
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
// ../kit/src/theme.ts
|
|
207
|
+
import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
|
|
208
|
+
import { homedir as homedir2 } from "os";
|
|
209
|
+
import { join as join3, resolve as resolve2 } from "path";
|
|
210
|
+
import process5 from "process";
|
|
211
|
+
function isColorSpec(spec) {
|
|
212
|
+
if (typeof spec === "number")
|
|
213
|
+
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
214
|
+
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
215
|
+
}
|
|
216
|
+
function cubeLevel(channel) {
|
|
217
|
+
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
218
|
+
}
|
|
219
|
+
function nearest256(hex) {
|
|
220
|
+
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
221
|
+
const levels = rgb.map(cubeLevel);
|
|
222
|
+
const cube = levels.map((level) => CUBE[level]);
|
|
223
|
+
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
224
|
+
const greyValue = 8 + grey * 10;
|
|
225
|
+
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
226
|
+
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
227
|
+
}
|
|
228
|
+
function hasTrueColor(env) {
|
|
229
|
+
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
230
|
+
}
|
|
231
|
+
function tinted(colors, spec, env = process5.env) {
|
|
232
|
+
if (typeof spec === "number")
|
|
233
|
+
return colors.ansi256(spec);
|
|
234
|
+
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
235
|
+
if (HEX.test(token))
|
|
236
|
+
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
237
|
+
return chain[token] ?? chain;
|
|
238
|
+
}, colors);
|
|
239
|
+
}
|
|
240
|
+
function isRecord(value) {
|
|
241
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
242
|
+
}
|
|
243
|
+
function readThemeFile(path, warn) {
|
|
244
|
+
try {
|
|
245
|
+
const stat = statSync(path, { throwIfNoEntry: false });
|
|
246
|
+
if (stat === undefined)
|
|
247
|
+
return;
|
|
248
|
+
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
249
|
+
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
253
|
+
if (isRecord(parsed))
|
|
254
|
+
return parsed;
|
|
255
|
+
warn(`${path} is not a JSON object, theme ignored`);
|
|
256
|
+
} catch (error) {
|
|
257
|
+
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
258
|
+
}
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
function applyPreset(theme, name, warn, where) {
|
|
262
|
+
if (name === undefined)
|
|
263
|
+
return;
|
|
264
|
+
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
265
|
+
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const preset = PRESETS[name];
|
|
269
|
+
Object.assign(theme.colors, preset.colors);
|
|
270
|
+
Object.assign(theme.glyphs, preset.glyphs);
|
|
271
|
+
if (preset.accents !== undefined)
|
|
272
|
+
theme.accents = [...preset.accents];
|
|
273
|
+
if (Object.hasOwn(preset, "gradient"))
|
|
274
|
+
theme.gradient = preset.gradient;
|
|
275
|
+
return name;
|
|
276
|
+
}
|
|
277
|
+
function applyFile(theme, file, where, warn) {
|
|
278
|
+
if (isRecord(file.colors)) {
|
|
279
|
+
for (const [key, value] of Object.entries(file.colors)) {
|
|
280
|
+
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
281
|
+
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
282
|
+
else if (!isColorSpec(value))
|
|
283
|
+
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
284
|
+
else
|
|
285
|
+
theme.colors[key] = value;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (isRecord(file.glyphs)) {
|
|
289
|
+
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
290
|
+
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
291
|
+
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
292
|
+
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
293
|
+
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
294
|
+
else
|
|
295
|
+
theme.glyphs[key] = value;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
299
|
+
theme.accents = [...file.accents];
|
|
300
|
+
else if (file.accents !== undefined)
|
|
301
|
+
warn(`${where}: accents must be a non-empty list of colours`);
|
|
302
|
+
if (file.gradient === null)
|
|
303
|
+
theme.gradient = undefined;
|
|
304
|
+
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
305
|
+
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
306
|
+
else if (file.gradient !== undefined)
|
|
307
|
+
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
308
|
+
if (isRecord(file.bins)) {
|
|
309
|
+
for (const [bin, value] of Object.entries(file.bins)) {
|
|
310
|
+
if (isColorSpec(value))
|
|
311
|
+
theme.bins[bin] = value;
|
|
312
|
+
else
|
|
313
|
+
warn(`${where}: bin ${bin} has no valid colour`);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
function endsWalk(home) {
|
|
318
|
+
return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
|
|
319
|
+
}
|
|
320
|
+
function warnOnce(message) {
|
|
321
|
+
if (warned.has(message))
|
|
322
|
+
return;
|
|
323
|
+
warned.add(message);
|
|
324
|
+
console.error(`warning: theme ${message}`);
|
|
325
|
+
}
|
|
326
|
+
function isPath(chosen) {
|
|
327
|
+
return chosen.includes("/") || chosen.endsWith(".json");
|
|
328
|
+
}
|
|
329
|
+
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
330
|
+
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
331
|
+
const sources = [];
|
|
332
|
+
const chosen = env.KIT_THEME ?? "";
|
|
333
|
+
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
334
|
+
if (isPath(chosen))
|
|
335
|
+
wanted.push(resolve2(from, chosen));
|
|
336
|
+
const files = [];
|
|
337
|
+
for (const path of wanted) {
|
|
338
|
+
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
339
|
+
if (path !== undefined && file !== undefined)
|
|
340
|
+
files.push({ path, file });
|
|
341
|
+
}
|
|
342
|
+
let preset = "default";
|
|
343
|
+
if (chosen !== "" && !isPath(chosen)) {
|
|
344
|
+
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
345
|
+
} else {
|
|
346
|
+
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
347
|
+
if (named !== undefined)
|
|
348
|
+
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
349
|
+
}
|
|
350
|
+
for (const { path, file } of files) {
|
|
351
|
+
applyFile(theme, file, path, warn);
|
|
352
|
+
sources.push(path);
|
|
353
|
+
}
|
|
354
|
+
return { theme, sources, preset };
|
|
355
|
+
}
|
|
356
|
+
function activeTheme() {
|
|
357
|
+
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
358
|
+
if (current === undefined || key !== currentKey) {
|
|
359
|
+
current = loadTheme();
|
|
360
|
+
currentKey = key;
|
|
361
|
+
}
|
|
362
|
+
return current;
|
|
363
|
+
}
|
|
364
|
+
var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
|
|
365
|
+
var init_theme = __esm(() => {
|
|
366
|
+
init_config();
|
|
367
|
+
init_user_config();
|
|
368
|
+
ENDS = new Map;
|
|
369
|
+
DEFAULT = {
|
|
370
|
+
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" },
|
|
371
|
+
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" },
|
|
372
|
+
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
373
|
+
bins: {},
|
|
374
|
+
gradient: ["#c084fc", "#67e8f9"]
|
|
375
|
+
};
|
|
376
|
+
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" };
|
|
377
|
+
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" };
|
|
378
|
+
ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
379
|
+
PRESETS = {
|
|
380
|
+
default: {},
|
|
381
|
+
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
382
|
+
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
383
|
+
ascii: { glyphs: ASCII }
|
|
384
|
+
};
|
|
385
|
+
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"]);
|
|
386
|
+
HEX = /^#[0-9a-f]{6}$/i;
|
|
387
|
+
CONTROL = /\p{Cc}/u;
|
|
388
|
+
MAX_FILE_BYTES = 64 * 1024;
|
|
389
|
+
SPACES = /\s+/;
|
|
390
|
+
CUBE = [0, 95, 135, 175, 215, 255];
|
|
391
|
+
warned = new Set;
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
// ../kit/src/style.ts
|
|
395
|
+
import process6 from "process";
|
|
396
|
+
function takesControlCodes(stream, env = process6.env) {
|
|
397
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
398
|
+
}
|
|
399
|
+
function paint(stream, env = process6.env) {
|
|
400
|
+
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
401
|
+
}
|
|
402
|
+
function role(name, stream, env = process6.env) {
|
|
403
|
+
const colors = paint(stream, env);
|
|
404
|
+
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
405
|
+
}
|
|
406
|
+
var STATUS_WORDS, STATUS_OF;
|
|
407
|
+
var init_style = __esm(() => {
|
|
408
|
+
init_colors();
|
|
409
|
+
init_mode();
|
|
410
|
+
init_theme();
|
|
411
|
+
STATUS_WORDS = {
|
|
412
|
+
passed: ["passed", "success", "succeeded", "ok"],
|
|
413
|
+
failed: ["failed", "failure", "error", "errored"],
|
|
414
|
+
running: ["running", "in_progress", "started", "holding"],
|
|
415
|
+
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
416
|
+
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
417
|
+
};
|
|
418
|
+
STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
419
|
+
});
|
|
420
|
+
|
|
421
|
+
// ../kit/src/format.ts
|
|
422
|
+
import process7 from "process";
|
|
423
|
+
function formatSeconds(total) {
|
|
424
|
+
let rest = Math.max(0, Math.round(total));
|
|
425
|
+
const amounts = UNITS.map(([unit, size]) => {
|
|
426
|
+
const amount = Math.floor(rest / size);
|
|
427
|
+
rest -= amount * size;
|
|
428
|
+
return `${amount}${unit}`;
|
|
429
|
+
});
|
|
430
|
+
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
431
|
+
if (first === -1)
|
|
432
|
+
return "0s";
|
|
433
|
+
const next = amounts[first + 1];
|
|
434
|
+
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
435
|
+
}
|
|
436
|
+
function formatDuration(ms) {
|
|
437
|
+
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
438
|
+
}
|
|
439
|
+
function upTo(text, separator) {
|
|
440
|
+
const end = text.indexOf(separator);
|
|
441
|
+
return end === -1 ? text : text.slice(0, end);
|
|
442
|
+
}
|
|
443
|
+
function textWidth(text) {
|
|
444
|
+
return Bun.stringWidth(text);
|
|
445
|
+
}
|
|
446
|
+
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
447
|
+
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
448
|
+
}
|
|
449
|
+
function printJson(value) {
|
|
450
|
+
console.log(jsonText(value));
|
|
451
|
+
}
|
|
452
|
+
var UNITS, ESCAPE;
|
|
453
|
+
var init_format = __esm(() => {
|
|
454
|
+
init_mode();
|
|
455
|
+
init_style();
|
|
456
|
+
UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
457
|
+
ESCAPE = String.fromCharCode(27);
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
// ../kit/src/help.ts
|
|
461
|
+
import process8 from "process";
|
|
462
|
+
function usageLine(usage, colors = paint(process8.stdout), { summary: withSummary = true } = {}) {
|
|
463
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
464
|
+
`);
|
|
465
|
+
const blank = lines.indexOf("");
|
|
466
|
+
const synopses = blank === -1 ? lines : lines.slice(0, blank);
|
|
467
|
+
const details = blank === -1 ? [] : lines.slice(blank + 1);
|
|
468
|
+
const colon = synopses[0].indexOf(": ");
|
|
469
|
+
const inline = synopses[0].slice(colon + 2);
|
|
470
|
+
const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
|
|
471
|
+
if (colon !== -1)
|
|
472
|
+
synopses[0] = synopses[0].slice(0, colon);
|
|
473
|
+
const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
|
|
474
|
+
`)}`;
|
|
475
|
+
const lead = summary === undefined || !withSummary ? [] : ["", colors.bold(prose(summary, colors))];
|
|
476
|
+
const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
|
|
477
|
+
return [head, ...lead, ...rest].join(`
|
|
478
|
+
`);
|
|
479
|
+
}
|
|
480
|
+
function prose(line, colors) {
|
|
481
|
+
if (colors.cyan("x") === "x")
|
|
482
|
+
return line;
|
|
483
|
+
return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
|
|
484
|
+
}
|
|
485
|
+
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [], bin } = {}) {
|
|
486
|
+
const { summary } = description(usage);
|
|
487
|
+
const head = bin === undefined ? [usageLine(usage, colors)] : [`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary === "" ? "" : ` ${summary}`}`, "", usageLine(usage, colors, { summary: false })];
|
|
488
|
+
return [...head, "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
489
|
+
`);
|
|
490
|
+
}
|
|
491
|
+
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
492
|
+
if (exits.length === 0)
|
|
493
|
+
return [];
|
|
494
|
+
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
495
|
+
}
|
|
496
|
+
function wantsHelpJson(env = process8.env) {
|
|
497
|
+
return env.KIT_HELP === "json";
|
|
498
|
+
}
|
|
499
|
+
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
500
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
501
|
+
`);
|
|
502
|
+
const first = lines[0];
|
|
503
|
+
const colon = first.indexOf(": ");
|
|
504
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
505
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
506
|
+
return {
|
|
507
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
508
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
509
|
+
...replaces === undefined ? {} : { replaces },
|
|
510
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
511
|
+
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
512
|
+
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
516
|
+
if (examples.length === 0 || outputMode() === "agent")
|
|
517
|
+
return [];
|
|
518
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
519
|
+
}
|
|
520
|
+
function optionRows(options, colors = paint(process8.stdout)) {
|
|
521
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
522
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
523
|
+
const choices = option.choices?.join("|");
|
|
524
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
525
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
526
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
527
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
528
|
+
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
529
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
530
|
+
});
|
|
531
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
532
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
533
|
+
}
|
|
534
|
+
var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
|
|
535
|
+
var init_help = __esm(() => {
|
|
536
|
+
init_mode();
|
|
537
|
+
init_style();
|
|
538
|
+
OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
539
|
+
USAGE_PREFIX = /^usage:\s*/i;
|
|
540
|
+
FULL_STOP = /\.$/;
|
|
541
|
+
PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
|
|
542
|
+
});
|
|
543
|
+
|
|
544
|
+
// ../kit/src/text.ts
|
|
545
|
+
function distance(a, b) {
|
|
546
|
+
const left = [...a];
|
|
547
|
+
const right = [...b];
|
|
548
|
+
let before = [];
|
|
549
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
550
|
+
for (const [i, x] of left.entries()) {
|
|
551
|
+
const current = [i + 1];
|
|
552
|
+
for (const [j, y] of right.entries()) {
|
|
553
|
+
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
554
|
+
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
555
|
+
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
556
|
+
current.push(cost);
|
|
557
|
+
}
|
|
558
|
+
before = previous;
|
|
559
|
+
previous = current;
|
|
560
|
+
}
|
|
561
|
+
return previous[right.length] ?? 0;
|
|
562
|
+
}
|
|
563
|
+
function closest(name, names) {
|
|
564
|
+
const started = names.find((known) => known.startsWith(name));
|
|
565
|
+
if (started !== undefined)
|
|
566
|
+
return started;
|
|
567
|
+
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
568
|
+
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
569
|
+
}
|
|
570
|
+
var init_text2 = () => {};
|
|
571
|
+
|
|
572
|
+
// ../kit/src/input.ts
|
|
573
|
+
var init_input = __esm(() => {
|
|
574
|
+
init_args();
|
|
575
|
+
});
|
|
576
|
+
|
|
577
|
+
// ../kit/src/args.ts
|
|
578
|
+
import process9 from "process";
|
|
579
|
+
import { parseArgs } from "util";
|
|
580
|
+
function jsonOption(holds) {
|
|
581
|
+
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
582
|
+
}
|
|
583
|
+
function fail(message, code = 2, hint) {
|
|
584
|
+
throw new Exit(message, code, hint);
|
|
585
|
+
}
|
|
586
|
+
function badUsage(message) {
|
|
587
|
+
throw new UsageError(message);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
class Completing {
|
|
591
|
+
options;
|
|
592
|
+
positionals;
|
|
593
|
+
candidates;
|
|
594
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
595
|
+
this.options = options;
|
|
596
|
+
this.positionals = positionals;
|
|
597
|
+
this.candidates = candidates;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
function applyOutput(color, plain, env = process9.env) {
|
|
601
|
+
const when = plain === true ? "never" : color ?? "auto";
|
|
602
|
+
if (when === "auto")
|
|
603
|
+
return;
|
|
604
|
+
if (when !== "always" && when !== "never")
|
|
605
|
+
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
606
|
+
if (when === "always") {
|
|
607
|
+
env.FORCE_COLOR = "1";
|
|
608
|
+
delete env.NO_COLOR;
|
|
609
|
+
} else {
|
|
610
|
+
env.NO_COLOR = "1";
|
|
611
|
+
delete env.FORCE_COLOR;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
function parse(args, usage, options, settings = {}) {
|
|
615
|
+
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
616
|
+
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
617
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
618
|
+
if (completion.active)
|
|
619
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
620
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
621
|
+
let parsed;
|
|
622
|
+
try {
|
|
623
|
+
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
624
|
+
} catch (error) {
|
|
625
|
+
const message = parseError(error);
|
|
626
|
+
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
627
|
+
}
|
|
628
|
+
const values = parsed.values;
|
|
629
|
+
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
630
|
+
if (values.help === true) {
|
|
631
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, { ...settings, bin: heading.bin }));
|
|
632
|
+
throw new HelpShown;
|
|
633
|
+
}
|
|
634
|
+
checkChoices(parsed.values, all);
|
|
635
|
+
checkConflicts(parsed.values, all);
|
|
636
|
+
if (settings.positionals !== undefined)
|
|
637
|
+
checkPositionals(parsed.positionals, settings.positionals);
|
|
638
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
639
|
+
}
|
|
640
|
+
function splitRest(args, passes) {
|
|
641
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
642
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
643
|
+
}
|
|
644
|
+
function splitTrailing(args, options, count) {
|
|
645
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
646
|
+
let seen = 0;
|
|
647
|
+
if (count === 0)
|
|
648
|
+
return { own: args, rest: undefined };
|
|
649
|
+
for (let at = 0;at < args.length; at++) {
|
|
650
|
+
const word = args[at];
|
|
651
|
+
if (word === "--")
|
|
652
|
+
break;
|
|
653
|
+
if (word.startsWith("-")) {
|
|
654
|
+
if (takesValue(word))
|
|
655
|
+
at++;
|
|
656
|
+
continue;
|
|
657
|
+
}
|
|
658
|
+
seen++;
|
|
659
|
+
if (seen === count)
|
|
660
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
661
|
+
}
|
|
662
|
+
return { own: args, rest: undefined };
|
|
663
|
+
}
|
|
664
|
+
function listed(options, allowNegative) {
|
|
665
|
+
if (!allowNegative)
|
|
666
|
+
return options;
|
|
667
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
668
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
669
|
+
return [[name, option]];
|
|
670
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
671
|
+
}));
|
|
672
|
+
}
|
|
673
|
+
function withAliases(args, options) {
|
|
674
|
+
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
675
|
+
if (named.size === 0)
|
|
676
|
+
return args;
|
|
677
|
+
const separator = args.indexOf("--");
|
|
678
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
679
|
+
return [...own.map((arg) => {
|
|
680
|
+
const at = arg.indexOf("=");
|
|
681
|
+
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
682
|
+
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
683
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
684
|
+
}
|
|
685
|
+
function withBare(args, options) {
|
|
686
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
687
|
+
if (bare.size === 0)
|
|
688
|
+
return args;
|
|
689
|
+
const separator = args.indexOf("--");
|
|
690
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
691
|
+
return [...own.flatMap((arg, index) => {
|
|
692
|
+
const optional = bare.get(arg);
|
|
693
|
+
const next = own[index + 1];
|
|
694
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
695
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
696
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
697
|
+
}
|
|
698
|
+
function checkConflicts(values, options) {
|
|
699
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
700
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
701
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
702
|
+
if (other !== undefined)
|
|
703
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
function checkChoices(values, options) {
|
|
707
|
+
for (const [name, option] of Object.entries(options)) {
|
|
708
|
+
if (option.choices === undefined)
|
|
709
|
+
continue;
|
|
710
|
+
const given = values[name];
|
|
711
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
712
|
+
if (typeof value === "string")
|
|
713
|
+
oneOf(value, name, option.choices);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
function oneOf(value, name, choices) {
|
|
718
|
+
if (!choices.includes(value))
|
|
719
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
720
|
+
return value;
|
|
721
|
+
}
|
|
722
|
+
function checkPositionals(given, names) {
|
|
723
|
+
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
724
|
+
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
725
|
+
if (given.length < required)
|
|
726
|
+
badUsage(`missing ${names[given.length]}`);
|
|
727
|
+
if (!variadic && given.length > names.length)
|
|
728
|
+
badUsage(`unexpected argument ${given[names.length]}`);
|
|
729
|
+
}
|
|
730
|
+
function joinDashValues(args, options) {
|
|
731
|
+
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
732
|
+
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
733
|
+
const joined = [];
|
|
734
|
+
for (let i = 0;i < args.length; i++) {
|
|
735
|
+
const arg = args[i] ?? "";
|
|
736
|
+
if (arg === "--")
|
|
737
|
+
return [...joined, ...args.slice(i)];
|
|
738
|
+
const name = longOf.get(arg);
|
|
739
|
+
const next = args[i + 1];
|
|
740
|
+
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
741
|
+
joined.push(`--${name}=${next}`);
|
|
742
|
+
i++;
|
|
743
|
+
} else {
|
|
744
|
+
joined.push(arg);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
return joined;
|
|
748
|
+
}
|
|
749
|
+
function parseError(error) {
|
|
750
|
+
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
751
|
+
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
752
|
+
}
|
|
753
|
+
function nearestOption(message, options, allowNegative) {
|
|
754
|
+
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
755
|
+
if (typed === undefined)
|
|
756
|
+
return;
|
|
757
|
+
const word = typed.replace(DASHES, "");
|
|
758
|
+
if (word.length < 2 && !typed.startsWith("--"))
|
|
759
|
+
return;
|
|
760
|
+
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
761
|
+
...option.short === undefined ? [] : [`-${option.short}`],
|
|
762
|
+
`--${name}`,
|
|
763
|
+
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
764
|
+
]);
|
|
765
|
+
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
766
|
+
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
767
|
+
}
|
|
768
|
+
var DASHES, EXIT, Exit, UsageError, HelpShown, completion, heading, OUTPUT_OPTIONS, UNKNOWN_OPTION;
|
|
769
|
+
var init_args = __esm(() => {
|
|
770
|
+
init_format();
|
|
771
|
+
init_help();
|
|
772
|
+
init_text2();
|
|
773
|
+
init_help();
|
|
774
|
+
init_input();
|
|
775
|
+
DASHES = /^-+/;
|
|
776
|
+
EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
|
|
777
|
+
Exit = class Exit extends Error {
|
|
778
|
+
code;
|
|
779
|
+
hint;
|
|
780
|
+
[EXIT] = true;
|
|
781
|
+
constructor(message, code, hint) {
|
|
782
|
+
super(message);
|
|
783
|
+
this.code = code;
|
|
784
|
+
this.hint = hint;
|
|
785
|
+
}
|
|
786
|
+
static [Symbol.hasInstance](value) {
|
|
787
|
+
if (this !== Exit)
|
|
788
|
+
return Function.prototype[Symbol.hasInstance].call(this, value);
|
|
789
|
+
return typeof value === "object" && value !== null && value[EXIT] === true;
|
|
790
|
+
}
|
|
791
|
+
};
|
|
792
|
+
UsageError = class UsageError extends Exit {
|
|
793
|
+
constructor(message, hint) {
|
|
794
|
+
super(message, 2, hint);
|
|
795
|
+
}
|
|
796
|
+
};
|
|
797
|
+
HelpShown = class HelpShown extends Exit {
|
|
798
|
+
constructor() {
|
|
799
|
+
super("help shown", 0);
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
completion = { active: false };
|
|
803
|
+
heading = { bin: undefined };
|
|
804
|
+
OUTPUT_OPTIONS = {
|
|
805
|
+
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
806
|
+
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
807
|
+
};
|
|
808
|
+
UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
809
|
+
});
|
|
810
|
+
|
|
811
|
+
// ../kit/src/folders.ts
|
|
812
|
+
var SKIPPED_FOLDERS;
|
|
813
|
+
var init_folders = __esm(() => {
|
|
814
|
+
init_user_config();
|
|
815
|
+
SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
816
|
+
});
|
|
817
|
+
|
|
818
|
+
// ../kit/src/answers.ts
|
|
819
|
+
var init_answers = __esm(() => {
|
|
820
|
+
init_folders();
|
|
821
|
+
});
|
|
822
|
+
|
|
823
|
+
// ../kit/src/job.ts
|
|
824
|
+
import process16 from "process";
|
|
825
|
+
function stopJob() {
|
|
826
|
+
process16.kill(0, "SIGTSTP");
|
|
827
|
+
}
|
|
828
|
+
var init_job = () => {};
|
|
829
|
+
|
|
830
|
+
// ../kit/src/picker/line.ts
|
|
831
|
+
function isEditKey(key) {
|
|
832
|
+
return EDIT_KEYS.has(key);
|
|
833
|
+
}
|
|
834
|
+
var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS;
|
|
835
|
+
var init_line = __esm(() => {
|
|
836
|
+
EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
|
|
837
|
+
BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
|
|
838
|
+
FORWARD_KILLS = new Set(["killnext", "killend"]);
|
|
839
|
+
});
|
|
840
|
+
|
|
841
|
+
// ../kit/src/picker/score.ts
|
|
842
|
+
var BOUNDARY_AFTER, NONE;
|
|
843
|
+
var init_score = __esm(() => {
|
|
844
|
+
BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
845
|
+
NONE = Number.NEGATIVE_INFINITY;
|
|
846
|
+
});
|
|
847
|
+
|
|
848
|
+
// ../kit/src/picker/state.ts
|
|
849
|
+
function repeat(value, count) {
|
|
850
|
+
return Array.from({ length: count }).fill(value);
|
|
851
|
+
}
|
|
852
|
+
function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
853
|
+
const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
|
|
854
|
+
return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
|
|
855
|
+
const wheel = MOUSE.exec(sequence)?.[1];
|
|
856
|
+
if (wheel !== undefined)
|
|
857
|
+
return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
|
|
858
|
+
const named = codes.get(sequence);
|
|
859
|
+
const key = named === undefined ? KEYS[sequence] : { ctrl: named };
|
|
860
|
+
if (sequence === PASTE_START || sequence === PASTE_END) {
|
|
861
|
+
paste.active = sequence === PASTE_START;
|
|
862
|
+
return [];
|
|
863
|
+
}
|
|
864
|
+
if (paste.active && (sequence === "\r" || sequence === `
|
|
865
|
+
`))
|
|
866
|
+
return [];
|
|
867
|
+
if (key !== undefined)
|
|
868
|
+
return [key];
|
|
869
|
+
return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
var IS_CONTROL, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
|
|
873
|
+
var init_state = __esm(() => {
|
|
874
|
+
init_text2();
|
|
875
|
+
init_line();
|
|
876
|
+
init_score();
|
|
877
|
+
IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
|
|
878
|
+
KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
|
|
879
|
+
MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
|
|
880
|
+
KEYS = {
|
|
881
|
+
"\x1B[A": "up",
|
|
882
|
+
"\x1BOA": "up",
|
|
883
|
+
"\x10": "up",
|
|
884
|
+
"\x1B[B": "down",
|
|
885
|
+
"\x1BOB": "down",
|
|
886
|
+
"\x0E": "down",
|
|
887
|
+
"\x1B[5~": "pageup",
|
|
888
|
+
"\x1B[6~": "pagedown",
|
|
889
|
+
"\x1B[H": "home",
|
|
890
|
+
"\x1B[1~": "home",
|
|
891
|
+
"\x1BOH": "home",
|
|
892
|
+
"\x1B[F": "end",
|
|
893
|
+
"\x1B[4~": "end",
|
|
894
|
+
"\x1BOF": "end",
|
|
895
|
+
"\r": "enter",
|
|
896
|
+
"\n": "enter",
|
|
897
|
+
"\x03": "cancel",
|
|
898
|
+
"\x1B": "cancel",
|
|
899
|
+
"\x1B[D": "left",
|
|
900
|
+
"\x1BOD": "left",
|
|
901
|
+
"\x1B[C": "right",
|
|
902
|
+
"\x1BOC": "right",
|
|
903
|
+
"\x1B[1;5D": "wordleft",
|
|
904
|
+
"\x1B[1;3D": "wordleft",
|
|
905
|
+
"\x1Bb": "wordleft",
|
|
906
|
+
"\x1B[1;5C": "wordright",
|
|
907
|
+
"\x1B[1;3C": "wordright",
|
|
908
|
+
"\x1Bf": "wordright",
|
|
909
|
+
"\x01": "linestart",
|
|
910
|
+
"\x05": "lineend",
|
|
911
|
+
"\x7F": "erase",
|
|
912
|
+
"\x1B[3~": "delete",
|
|
913
|
+
"\b": "killword",
|
|
914
|
+
"\x1B\x7F": "killword",
|
|
915
|
+
"\x1B[3;5~": "killnext",
|
|
916
|
+
"\x1Bd": "killnext",
|
|
917
|
+
"\x15": "clear",
|
|
918
|
+
"\v": "killend",
|
|
919
|
+
"\x17": "word",
|
|
920
|
+
"\x19": "yank",
|
|
921
|
+
"\x1A": "suspend",
|
|
922
|
+
"\t": "tab",
|
|
923
|
+
"\x1F": "help",
|
|
924
|
+
"\x1BOP": "help",
|
|
925
|
+
"\x1B[11~": "help"
|
|
926
|
+
};
|
|
927
|
+
});
|
|
928
|
+
|
|
929
|
+
// ../kit/src/redraw.ts
|
|
930
|
+
function overwrite(lines, columns) {
|
|
931
|
+
return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
|
|
932
|
+
`);
|
|
933
|
+
}
|
|
934
|
+
function rowsTaken(lines, columns) {
|
|
935
|
+
return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
|
|
936
|
+
}
|
|
937
|
+
var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
|
|
938
|
+
var init_redraw = __esm(() => {
|
|
939
|
+
init_format();
|
|
940
|
+
});
|
|
941
|
+
|
|
942
|
+
// ../kit/src/prompt.ts
|
|
943
|
+
import process17 from "process";
|
|
944
|
+
function readKeys(input, paste = { active: false }) {
|
|
945
|
+
return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
|
|
946
|
+
}
|
|
947
|
+
async function confirm(question, { default: fallback, ...settings } = {}) {
|
|
948
|
+
let answered = fallback;
|
|
949
|
+
const choices = { true: "Y/n", false: "y/N", undefined: "y/n" }[String(fallback)];
|
|
950
|
+
const accepted = await ask(question, settings, (colors, state) => [state === "asking" ? asking(colors, question, "", choices) : answer(colors, question, state, answered ? "yes" : "no")], (key) => {
|
|
951
|
+
if (key === "cancel")
|
|
952
|
+
return "cancel";
|
|
953
|
+
if (key === "enter")
|
|
954
|
+
return answered === undefined ? undefined : "enter";
|
|
955
|
+
const letter = typeof key === "object" ? key.text.toLowerCase() : "";
|
|
956
|
+
if (letter !== "y" && letter !== "n")
|
|
957
|
+
return;
|
|
958
|
+
answered = letter === "y";
|
|
959
|
+
return "enter";
|
|
960
|
+
});
|
|
961
|
+
return accepted ? answered : undefined;
|
|
962
|
+
}
|
|
963
|
+
function asking(colors, question, typed, keys) {
|
|
964
|
+
return `${colors.cyan("?")} ${question} ${typed === "" ? colors.dim(`(${keys})`) : typed}`;
|
|
965
|
+
}
|
|
966
|
+
function answer(colors, question, state, picked) {
|
|
967
|
+
return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
|
|
968
|
+
}
|
|
969
|
+
async function ask(question, { hint, terminal = process17 }, render, press) {
|
|
970
|
+
const { stdin, stderr } = terminal;
|
|
971
|
+
if (!isInteractive(terminal))
|
|
972
|
+
fail(`cannot ask "${question}" off a terminal`, 2, hint);
|
|
973
|
+
const colors = paint(stderr);
|
|
974
|
+
let current = "asking";
|
|
975
|
+
let outcome;
|
|
976
|
+
const columns = () => stderr.columns || 80;
|
|
977
|
+
const draw = (state, last = false) => {
|
|
978
|
+
const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
|
|
979
|
+
const rows = rowsTaken(frame, columns());
|
|
980
|
+
stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
|
|
981
|
+
current = state;
|
|
982
|
+
};
|
|
983
|
+
const redraw = () => draw(current);
|
|
984
|
+
const paste = { active: false };
|
|
985
|
+
const stop = terminal.stop ?? (terminal === process17 ? stopJob : undefined);
|
|
986
|
+
const suspend = () => {
|
|
987
|
+
if (stop === undefined)
|
|
988
|
+
return;
|
|
989
|
+
stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
|
|
990
|
+
stdin.setRawMode(false);
|
|
991
|
+
stop();
|
|
992
|
+
stdin.setRawMode(true);
|
|
993
|
+
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
994
|
+
};
|
|
995
|
+
try {
|
|
996
|
+
stderr.on?.("resize", redraw);
|
|
997
|
+
stdin.setRawMode(true);
|
|
998
|
+
stdin.resume();
|
|
999
|
+
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
1000
|
+
draw("asking");
|
|
1001
|
+
return await new Promise((resolve) => {
|
|
1002
|
+
function onData(data) {
|
|
1003
|
+
for (const key of readKeys(data.toString(), paste)) {
|
|
1004
|
+
if (key === "suspend") {
|
|
1005
|
+
suspend();
|
|
1006
|
+
continue;
|
|
1007
|
+
}
|
|
1008
|
+
const pressed = press(key);
|
|
1009
|
+
if (pressed !== undefined) {
|
|
1010
|
+
settle(pressed);
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
draw("asking");
|
|
1015
|
+
}
|
|
1016
|
+
function onEnd() {
|
|
1017
|
+
settle("cancel");
|
|
1018
|
+
}
|
|
1019
|
+
function settle(settled) {
|
|
1020
|
+
outcome = settled;
|
|
1021
|
+
stdin.off("data", onData);
|
|
1022
|
+
stdin.off("end", onEnd);
|
|
1023
|
+
resolve(settled === "enter");
|
|
1024
|
+
}
|
|
1025
|
+
stdin.on("data", onData);
|
|
1026
|
+
stdin.on("end", onEnd);
|
|
1027
|
+
});
|
|
1028
|
+
} finally {
|
|
1029
|
+
stderr.off?.("resize", redraw);
|
|
1030
|
+
draw(outcome ?? "cancel", true);
|
|
1031
|
+
stderr.write(`
|
|
1032
|
+
\x1B[?25h\x1B[?2004l`);
|
|
1033
|
+
stdin.setRawMode(false);
|
|
1034
|
+
stdin.pause();
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
var PROMPT_KEYS;
|
|
1038
|
+
var init_prompt = __esm(() => {
|
|
1039
|
+
init_answers();
|
|
1040
|
+
init_args();
|
|
1041
|
+
init_format();
|
|
1042
|
+
init_job();
|
|
1043
|
+
init_mode();
|
|
1044
|
+
init_line();
|
|
1045
|
+
init_state();
|
|
1046
|
+
init_redraw();
|
|
1047
|
+
init_style();
|
|
1048
|
+
PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
|
|
1049
|
+
});
|
|
1050
|
+
|
|
1051
|
+
// src/cli.ts
|
|
1052
|
+
import { tmpdir } from "os";
|
|
1053
|
+
import { join as join9 } from "path";
|
|
1054
|
+
|
|
1055
|
+
// ../kit/src/index.ts
|
|
1056
|
+
init_args();
|
|
1057
|
+
|
|
1058
|
+
// ../kit/src/argv.ts
|
|
1059
|
+
import { readFileSync as readFileSync3, realpathSync } from "fs";
|
|
1060
|
+
import { resolve as resolve3 } from "path";
|
|
1061
|
+
import process10 from "process";
|
|
1062
|
+
function commandLine() {
|
|
1063
|
+
try {
|
|
1064
|
+
return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
1065
|
+
} catch {
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
function realPath(word) {
|
|
1070
|
+
try {
|
|
1071
|
+
return realpathSync(resolve3(word));
|
|
1072
|
+
} catch {
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
1077
|
+
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
1078
|
+
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
1079
|
+
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
1080
|
+
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
1081
|
+
}
|
|
1082
|
+
// ../kit/src/chart.ts
|
|
1083
|
+
init_format();
|
|
1084
|
+
init_mode();
|
|
1085
|
+
init_style();
|
|
1086
|
+
init_theme();
|
|
1087
|
+
// ../kit/src/ci.ts
|
|
1088
|
+
init_args();
|
|
1089
|
+
init_format();
|
|
1090
|
+
|
|
1091
|
+
// ../kit/src/progress.ts
|
|
1092
|
+
init_format();
|
|
1093
|
+
|
|
1094
|
+
// ../kit/src/process.ts
|
|
1095
|
+
var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
|
|
1096
|
+
|
|
1097
|
+
// ../kit/src/progress.ts
|
|
1098
|
+
init_style();
|
|
1099
|
+
init_theme();
|
|
1100
|
+
var ESC = String.fromCharCode(27);
|
|
1101
|
+
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
1102
|
+
var RESET_STYLE = `${ESC}[0m`;
|
|
1103
|
+
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
1104
|
+
|
|
1105
|
+
// ../kit/src/ci.ts
|
|
1106
|
+
init_style();
|
|
1107
|
+
|
|
1108
|
+
// ../kit/src/tool.ts
|
|
1109
|
+
init_format();
|
|
1110
|
+
// ../kit/src/cli.ts
|
|
1111
|
+
init_args();
|
|
1112
|
+
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
1113
|
+
import { dirname as dirname3, join as join5 } from "path";
|
|
1114
|
+
import process14 from "process";
|
|
1115
|
+
|
|
1116
|
+
// ../kit/src/askpass.ts
|
|
1117
|
+
import process11 from "process";
|
|
1118
|
+
var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
|
|
1119
|
+
async function askpassClient(argv) {
|
|
1120
|
+
const socketPath = process11.env[SOCKET_VARIABLE];
|
|
1121
|
+
if (socketPath === undefined)
|
|
1122
|
+
return;
|
|
1123
|
+
const request = { prompt: argv[0] ?? "", ...process11.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
|
|
1124
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
1125
|
+
let received = "";
|
|
1126
|
+
try {
|
|
1127
|
+
await Bun.connect({
|
|
1128
|
+
unix: socketPath,
|
|
1129
|
+
socket: {
|
|
1130
|
+
open: (socket) => void socket.write(`${JSON.stringify(request)}
|
|
1131
|
+
`),
|
|
1132
|
+
data: (_, chunk) => {
|
|
1133
|
+
received += chunk.toString();
|
|
1134
|
+
},
|
|
1135
|
+
close: () => resolve(received),
|
|
1136
|
+
error: () => resolve("")
|
|
1137
|
+
}
|
|
1138
|
+
});
|
|
1139
|
+
} catch {
|
|
1140
|
+
return 1;
|
|
1141
|
+
}
|
|
1142
|
+
const reply = await promise;
|
|
1143
|
+
if (reply === "")
|
|
1144
|
+
return 1;
|
|
1145
|
+
const { answer } = JSON.parse(reply);
|
|
1146
|
+
if (request.notice === true)
|
|
1147
|
+
return 0;
|
|
1148
|
+
if (answer === undefined)
|
|
1149
|
+
return 1;
|
|
1150
|
+
process11.stdout.write(`${answer}
|
|
1151
|
+
`);
|
|
1152
|
+
return 0;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
// ../kit/src/completions.ts
|
|
1156
|
+
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
1157
|
+
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'
|
|
1158
|
+
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
1159
|
+
set -l current (commandline -ct)
|
|
1160
|
+
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
1161
|
+
if test "$line" = __files__
|
|
1162
|
+
__fish_complete_path $current
|
|
1163
|
+
else
|
|
1164
|
+
echo $line
|
|
1165
|
+
end
|
|
1166
|
+
end
|
|
1167
|
+
end`;
|
|
1168
|
+
var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1169
|
+
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
1170
|
+
local -a lines
|
|
1171
|
+
COMPREPLY=()
|
|
1172
|
+
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
1173
|
+
for line in "\${lines[@]}"; do
|
|
1174
|
+
if [[ $line == __files__ ]]; then
|
|
1175
|
+
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
1176
|
+
else
|
|
1177
|
+
words+="\${line%%$'\\t'*}"$'\\n'
|
|
1178
|
+
fi
|
|
1179
|
+
done
|
|
1180
|
+
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
1181
|
+
}`;
|
|
1182
|
+
var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1183
|
+
local line
|
|
1184
|
+
local -a described plain
|
|
1185
|
+
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
1186
|
+
if [[ $line == __files__ ]]; then
|
|
1187
|
+
_files
|
|
1188
|
+
elif [[ $line == *$'\\t'* ]]; then
|
|
1189
|
+
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
1190
|
+
else
|
|
1191
|
+
plain+=("$line")
|
|
1192
|
+
fi
|
|
1193
|
+
done
|
|
1194
|
+
(( \${#described} )) && _describe -V value described
|
|
1195
|
+
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
1196
|
+
return 0
|
|
1197
|
+
}
|
|
1198
|
+
__kaynooo_cli_register() {
|
|
1199
|
+
add-zsh-hook -d precmd __kaynooo_cli_register
|
|
1200
|
+
(( $+functions[compdef] )) || { autoload -Uz compinit && compinit }
|
|
1201
|
+
compdef __kaynooo_cli_complete $__kaynooo_cli_bins
|
|
1202
|
+
}
|
|
1203
|
+
autoload -Uz add-zsh-hook
|
|
1204
|
+
add-zsh-hook precmd __kaynooo_cli_register
|
|
1205
|
+
typeset -gaU __kaynooo_cli_bins`;
|
|
1206
|
+
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
1207
|
+
if (shell === "fish")
|
|
1208
|
+
return `${header}
|
|
1209
|
+
${FISH_FUNCTION}
|
|
1210
|
+
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
1211
|
+
`).join("")}`;
|
|
1212
|
+
if (shell === "bash")
|
|
1213
|
+
return `${header}
|
|
1214
|
+
${BASH_FUNCTION}
|
|
1215
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
1216
|
+
`;
|
|
1217
|
+
return `${header}
|
|
1218
|
+
${ZSH_FUNCTION}
|
|
1219
|
+
__kaynooo_cli_bins+=(${bins.join(" ")})
|
|
1220
|
+
`;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
// ../kit/src/notify.ts
|
|
1224
|
+
init_format();
|
|
1225
|
+
init_mode();
|
|
1226
|
+
import process12 from "process";
|
|
1227
|
+
var NOTIFY_AFTER_MS = 1e4;
|
|
1228
|
+
var CANCELLED = 130;
|
|
1229
|
+
function base64(text) {
|
|
1230
|
+
return Buffer.from(text).toString("base64");
|
|
1231
|
+
}
|
|
1232
|
+
function notification(title, body, env = process12.env) {
|
|
1233
|
+
const id = `kit${process12.pid}`;
|
|
1234
|
+
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\\`];
|
|
1235
|
+
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
1236
|
+
}
|
|
1237
|
+
function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
|
|
1238
|
+
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1239
|
+
return;
|
|
1240
|
+
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
// ../kit/src/cli.ts
|
|
1244
|
+
init_style();
|
|
1245
|
+
init_text2();
|
|
1246
|
+
|
|
1247
|
+
// ../kit/src/usage.ts
|
|
1248
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
1249
|
+
import { homedir as homedir3 } from "os";
|
|
1250
|
+
import { dirname as dirname2, join as join4 } from "path";
|
|
1251
|
+
import process13 from "process";
|
|
1252
|
+
|
|
1253
|
+
// ../kit/src/logs.ts
|
|
1254
|
+
init_user_config();
|
|
1255
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1256
|
+
var CLI_FOLDER = "kaynooo-cli";
|
|
1257
|
+
|
|
1258
|
+
// ../kit/src/usage.ts
|
|
1259
|
+
init_user_config();
|
|
1260
|
+
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
1261
|
+
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
1262
|
+
var LONGEST_NAME = 40;
|
|
1263
|
+
var usageError;
|
|
1264
|
+
function noteUsageError(message) {
|
|
1265
|
+
usageError = message;
|
|
1266
|
+
}
|
|
1267
|
+
function stateHome(env = process13.env) {
|
|
1268
|
+
return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
|
|
1269
|
+
}
|
|
1270
|
+
function usagePath(env = process13.env) {
|
|
1271
|
+
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1272
|
+
}
|
|
1273
|
+
function usageRecorded(env = process13.env) {
|
|
1274
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1275
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1276
|
+
}
|
|
1277
|
+
function flagNames(argv) {
|
|
1278
|
+
const end = argv.indexOf("--");
|
|
1279
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1280
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1281
|
+
}
|
|
1282
|
+
function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
|
|
1283
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1284
|
+
usageError = undefined;
|
|
1285
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
|
|
1286
|
+
}
|
|
1287
|
+
function recordUsage(entry, env = process13.env) {
|
|
1288
|
+
if (!usageRecorded(env))
|
|
1289
|
+
return;
|
|
1290
|
+
try {
|
|
1291
|
+
const path = usagePath(env);
|
|
1292
|
+
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1293
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1294
|
+
`, { mode: 384 });
|
|
1295
|
+
} catch {}
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
// ../kit/src/cli.ts
|
|
1299
|
+
var LEVEL_OPTIONS = {
|
|
1300
|
+
...OUTPUT_OPTIONS,
|
|
1301
|
+
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1302
|
+
};
|
|
1303
|
+
var TOP_OPTIONS = {
|
|
1304
|
+
...LEVEL_OPTIONS,
|
|
1305
|
+
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1306
|
+
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1307
|
+
};
|
|
1308
|
+
async function commandRows(all, colors) {
|
|
1309
|
+
const commands = shown(all);
|
|
1310
|
+
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
1311
|
+
const groups = new Map([["Commands:", []]]);
|
|
1312
|
+
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
1313
|
+
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
1314
|
+
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
1315
|
+
const rows = groups.get(heading) ?? [];
|
|
1316
|
+
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
1317
|
+
groups.set(heading, rows);
|
|
1318
|
+
}
|
|
1319
|
+
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
1320
|
+
}
|
|
1321
|
+
function shown(commands) {
|
|
1322
|
+
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
1323
|
+
}
|
|
1324
|
+
function takeOutputFlags(argv) {
|
|
1325
|
+
let index = 0;
|
|
1326
|
+
for (;index < argv.length; index++) {
|
|
1327
|
+
const word = argv[index];
|
|
1328
|
+
if (word === "--plain")
|
|
1329
|
+
applyOutput(undefined, true);
|
|
1330
|
+
else if (word.startsWith("--color="))
|
|
1331
|
+
applyOutput(word.slice("--color=".length), undefined);
|
|
1332
|
+
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
1333
|
+
applyOutput(argv[++index], undefined);
|
|
1334
|
+
else
|
|
1335
|
+
break;
|
|
1336
|
+
}
|
|
1337
|
+
return argv.slice(index);
|
|
1338
|
+
}
|
|
1339
|
+
async function resolveSummary(summary) {
|
|
1340
|
+
return typeof summary === "string" ? summary : summary();
|
|
1341
|
+
}
|
|
1342
|
+
function lookup({ commands, aliases }, word) {
|
|
1343
|
+
const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
|
|
1344
|
+
return Object.hasOwn(commands, name) ? commands[name] : undefined;
|
|
1345
|
+
}
|
|
1346
|
+
function scopeOf(commands, extra, aliases) {
|
|
1347
|
+
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
1348
|
+
}
|
|
1349
|
+
async function expand(scope, words) {
|
|
1350
|
+
if (scope.lazy.length === 0)
|
|
1351
|
+
return scope;
|
|
1352
|
+
const commands = { ...scope.commands };
|
|
1353
|
+
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
1354
|
+
for (const [name, command] of Object.entries(added))
|
|
1355
|
+
commands[name] ??= command;
|
|
1356
|
+
}
|
|
1357
|
+
return { ...scope, commands, lazy: [] };
|
|
1358
|
+
}
|
|
1359
|
+
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
1360
|
+
const colors = paint(stream);
|
|
1361
|
+
const prefix = path.join(" ");
|
|
1362
|
+
const summary = await resolveSummary(lazySummary);
|
|
1363
|
+
if (wantsHelpJson())
|
|
1364
|
+
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
1365
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1366
|
+
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
1367
|
+
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
1368
|
+
return [
|
|
1369
|
+
header(colors, summary),
|
|
1370
|
+
"",
|
|
1371
|
+
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
1372
|
+
"",
|
|
1373
|
+
...await commandRows(commands, colors),
|
|
1374
|
+
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
1375
|
+
"",
|
|
1376
|
+
colors.bold("Options:"),
|
|
1377
|
+
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
1378
|
+
...exampleRows(examples ?? [], colors),
|
|
1379
|
+
"",
|
|
1380
|
+
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
1381
|
+
].join(`
|
|
1382
|
+
`);
|
|
1383
|
+
}
|
|
1384
|
+
function printError(prefix, message, hint, cause) {
|
|
1385
|
+
const colors = paint(process14.stderr);
|
|
1386
|
+
const styled = takesControlCodes(process14.stderr);
|
|
1387
|
+
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1388
|
+
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1389
|
+
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1390
|
+
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1391
|
+
}
|
|
1392
|
+
function printJsonError(message, hint, cause) {
|
|
1393
|
+
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1394
|
+
}
|
|
1395
|
+
function wantsJson(argv) {
|
|
1396
|
+
const end = argv.indexOf("--");
|
|
1397
|
+
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1398
|
+
}
|
|
1399
|
+
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1400
|
+
if (error instanceof HelpShown)
|
|
1401
|
+
return 0;
|
|
1402
|
+
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1403
|
+
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1404
|
+
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1405
|
+
if (error instanceof Exit && error.code === 2)
|
|
1406
|
+
noteUsageError(error.message);
|
|
1407
|
+
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1408
|
+
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1409
|
+
return error instanceof Exit ? error.code : 1;
|
|
1410
|
+
}
|
|
1411
|
+
async function dispatch(level, typed, { version, redact }) {
|
|
1412
|
+
const prefix = level.path.join(" ");
|
|
1413
|
+
let argv;
|
|
1414
|
+
try {
|
|
1415
|
+
argv = takeOutputFlags(typed);
|
|
1416
|
+
} catch (error) {
|
|
1417
|
+
return reportThrown(prefix, error);
|
|
1418
|
+
}
|
|
1419
|
+
const [name, ...args] = argv;
|
|
1420
|
+
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
1421
|
+
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
1422
|
+
try {
|
|
1423
|
+
return await fallback.run([]);
|
|
1424
|
+
} catch (error) {
|
|
1425
|
+
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
if (name === undefined && level.path.length > 1) {
|
|
1429
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
|
|
1430
|
+
return 2;
|
|
1431
|
+
}
|
|
1432
|
+
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1433
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
|
|
1434
|
+
return 0;
|
|
1435
|
+
}
|
|
1436
|
+
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1437
|
+
console.log(version);
|
|
1438
|
+
return 0;
|
|
1439
|
+
}
|
|
1440
|
+
let command = lookup(level, name);
|
|
1441
|
+
let rest = args;
|
|
1442
|
+
let ran = name;
|
|
1443
|
+
if (command === undefined && level.lazy.length > 0) {
|
|
1444
|
+
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
1445
|
+
command = lookup(level, name);
|
|
1446
|
+
}
|
|
1447
|
+
if (command === undefined && level.defaultCommand !== undefined) {
|
|
1448
|
+
command = level.commands[level.defaultCommand];
|
|
1449
|
+
rest = argv;
|
|
1450
|
+
ran = level.defaultCommand;
|
|
1451
|
+
}
|
|
1452
|
+
if (command === undefined) {
|
|
1453
|
+
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
1454
|
+
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
1455
|
+
return 2;
|
|
1456
|
+
}
|
|
1457
|
+
if ("commands" in command) {
|
|
1458
|
+
const { summary } = command;
|
|
1459
|
+
return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
|
|
1460
|
+
}
|
|
1461
|
+
try {
|
|
1462
|
+
return await command.run(rest);
|
|
1463
|
+
} catch (error) {
|
|
1464
|
+
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
var COMPLETE = "__complete";
|
|
1468
|
+
var FILES = "__files__";
|
|
1469
|
+
async function completingOf(run) {
|
|
1470
|
+
completion.active = true;
|
|
1471
|
+
try {
|
|
1472
|
+
await run([]);
|
|
1473
|
+
} catch (error) {
|
|
1474
|
+
if (error instanceof Completing)
|
|
1475
|
+
return error;
|
|
1476
|
+
} finally {
|
|
1477
|
+
completion.active = false;
|
|
1478
|
+
}
|
|
1479
|
+
return new Completing({});
|
|
1480
|
+
}
|
|
1481
|
+
async function optionsOf(run) {
|
|
1482
|
+
return (await completingOf(run)).options;
|
|
1483
|
+
}
|
|
1484
|
+
function candidateLine(candidate) {
|
|
1485
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1486
|
+
}
|
|
1487
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
1488
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1489
|
+
const typed = [];
|
|
1490
|
+
let at = 0;
|
|
1491
|
+
while (at < before.length) {
|
|
1492
|
+
const word = before[at];
|
|
1493
|
+
if (word === "--") {
|
|
1494
|
+
typed.push(...before.slice(at + 1));
|
|
1495
|
+
break;
|
|
1496
|
+
}
|
|
1497
|
+
if (!word.startsWith("-"))
|
|
1498
|
+
typed.push(word);
|
|
1499
|
+
else if (takesValue(word))
|
|
1500
|
+
at++;
|
|
1501
|
+
at++;
|
|
1502
|
+
}
|
|
1503
|
+
const last = positionals.at(-1);
|
|
1504
|
+
if (typed.length < positionals.length)
|
|
1505
|
+
return { name: positionals[typed.length], typed };
|
|
1506
|
+
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1507
|
+
}
|
|
1508
|
+
async function leafCandidates(run, words) {
|
|
1509
|
+
const completing = await completingOf(run);
|
|
1510
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1511
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1512
|
+
const flag = words.at(-2);
|
|
1513
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1514
|
+
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1515
|
+
if (option?.type === "string") {
|
|
1516
|
+
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1517
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1518
|
+
}
|
|
1519
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1520
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1521
|
+
}
|
|
1522
|
+
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1523
|
+
const [word = "", ...rest] = words;
|
|
1524
|
+
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1525
|
+
let { commands } = scope;
|
|
1526
|
+
let command = lookup(scope, word);
|
|
1527
|
+
if (listing || command === undefined) {
|
|
1528
|
+
const expanded = await expand(scope, [...before, ...words]);
|
|
1529
|
+
commands = expanded.commands;
|
|
1530
|
+
command = lookup(expanded, word);
|
|
1531
|
+
}
|
|
1532
|
+
if (listing) {
|
|
1533
|
+
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1534
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1535
|
+
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1536
|
+
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1537
|
+
return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
|
|
1538
|
+
}
|
|
1539
|
+
if (command === undefined) {
|
|
1540
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1541
|
+
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
1542
|
+
}
|
|
1543
|
+
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1544
|
+
}
|
|
1545
|
+
var COMPLETIONS = "--completions";
|
|
1546
|
+
function flagValue([flag = "", ...rest]) {
|
|
1547
|
+
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1548
|
+
}
|
|
1549
|
+
function printCompletionScript(name, args) {
|
|
1550
|
+
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1551
|
+
if (shell === undefined || args.length !== 1) {
|
|
1552
|
+
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1553
|
+
return 2;
|
|
1554
|
+
}
|
|
1555
|
+
console.log(completionScript(shell, [name]).trimEnd());
|
|
1556
|
+
return 0;
|
|
1557
|
+
}
|
|
1558
|
+
async function printCandidates(found) {
|
|
1559
|
+
for (const line of await found)
|
|
1560
|
+
console.log(line);
|
|
1561
|
+
return 0;
|
|
1562
|
+
}
|
|
1563
|
+
function packageVersion(entry = Bun.main) {
|
|
1564
|
+
let resolved = entry;
|
|
1565
|
+
try {
|
|
1566
|
+
resolved = realpathSync2(entry);
|
|
1567
|
+
} catch {}
|
|
1568
|
+
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1569
|
+
try {
|
|
1570
|
+
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
1571
|
+
if (typeof version === "string")
|
|
1572
|
+
return version;
|
|
1573
|
+
} catch {}
|
|
1574
|
+
if (dirname3(dir) === dir)
|
|
1575
|
+
return "0.0.0";
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
async function runCli(cli, argv = scriptArgs()) {
|
|
1579
|
+
const version = cli.version ?? packageVersion();
|
|
1580
|
+
const answered = await askpassClient(argv);
|
|
1581
|
+
if (answered !== undefined)
|
|
1582
|
+
return answered;
|
|
1583
|
+
if (argv[0] === COMPLETE)
|
|
1584
|
+
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1585
|
+
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1586
|
+
return printCompletionScript(cli.name, flagValue(argv));
|
|
1587
|
+
const started = performance.now();
|
|
1588
|
+
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 });
|
|
1589
|
+
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1590
|
+
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1591
|
+
if (cli.usage !== false) {
|
|
1592
|
+
try {
|
|
1593
|
+
recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
|
|
1594
|
+
} catch {}
|
|
1595
|
+
}
|
|
1596
|
+
return code;
|
|
1597
|
+
}
|
|
1598
|
+
function commandPath(scope, argv) {
|
|
1599
|
+
const path = [];
|
|
1600
|
+
let level = scope;
|
|
1601
|
+
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1602
|
+
const command = lookup(level, word);
|
|
1603
|
+
if (command === undefined)
|
|
1604
|
+
break;
|
|
1605
|
+
path.push(word);
|
|
1606
|
+
if (!("commands" in command))
|
|
1607
|
+
break;
|
|
1608
|
+
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
1609
|
+
}
|
|
1610
|
+
return path.length === 0 ? undefined : path.join(" ");
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
// ../kit/src/index.ts
|
|
1614
|
+
init_config();
|
|
1615
|
+
|
|
1616
|
+
// ../kit/src/excerpt.ts
|
|
1617
|
+
init_text2();
|
|
1618
|
+
|
|
1619
|
+
// ../kit/src/index.ts
|
|
1620
|
+
init_folders();
|
|
1621
|
+
init_format();
|
|
1622
|
+
|
|
1623
|
+
// ../kit/src/git.ts
|
|
1624
|
+
init_args();
|
|
1625
|
+
// ../kit/src/limit.ts
|
|
1626
|
+
init_args();
|
|
1627
|
+
|
|
1628
|
+
// ../kit/src/index.ts
|
|
1629
|
+
init_mode();
|
|
1630
|
+
|
|
1631
|
+
// ../kit/src/report.ts
|
|
1632
|
+
init_style();
|
|
1633
|
+
init_text2();
|
|
1634
|
+
// ../kit/src/secrets.ts
|
|
1635
|
+
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1636
|
+
var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
|
|
1637
|
+
// ../kit/src/sessions.ts
|
|
1638
|
+
var {Glob } = globalThis.Bun;
|
|
1639
|
+
var SESSION_FILES = new Glob("*.json");
|
|
1640
|
+
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1641
|
+
|
|
1642
|
+
// ../kit/src/index.ts
|
|
1643
|
+
init_style();
|
|
1644
|
+
init_text2();
|
|
1645
|
+
init_theme();
|
|
1646
|
+
init_user_config();
|
|
1647
|
+
|
|
1648
|
+
// ../kit/src/watch.ts
|
|
1649
|
+
init_args();
|
|
1650
|
+
init_input();
|
|
1651
|
+
init_style();
|
|
1652
|
+
// ../kit/src/workspace-root.ts
|
|
1653
|
+
init_user_config();
|
|
1654
|
+
// src/cli.ts
|
|
1655
|
+
init_prompt();
|
|
1656
|
+
|
|
1657
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-3624x5ew.js
|
|
1658
|
+
init_chunk_yfkscv18();
|
|
1659
|
+
var W2 = 1000;
|
|
1660
|
+
var ht = 60 * W2;
|
|
1661
|
+
var Ue = 60 * ht;
|
|
1662
|
+
var S = 24 * Ue;
|
|
1663
|
+
var ei = 7 * S;
|
|
1664
|
+
var p = new Map;
|
|
1665
|
+
var Y = [[n.y, "year"], [n.M, "month"], [n.w, "week"], [n.d, "day"], [n.h, "hour"], [n.m, "minute"], [n.s, "second"]];
|
|
1666
|
+
|
|
1667
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-1nmct6ry.js
|
|
1668
|
+
var T = 15 * W2;
|
|
1669
|
+
function l(e, n) {
|
|
1670
|
+
if (n === undefined)
|
|
1671
|
+
return e ?? undefined;
|
|
1672
|
+
let t = AbortSignal.timeout(n);
|
|
1673
|
+
return e ? AbortSignal.any([e, t]) : t;
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-1dqf2hrj.js
|
|
1677
|
+
function w(e) {
|
|
1678
|
+
if (typeof e !== "object" || e === null)
|
|
1679
|
+
return false;
|
|
1680
|
+
let n = Object.getPrototypeOf(e);
|
|
1681
|
+
return n === Object.prototype || n === null;
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-sgh0r8t7.js
|
|
1685
|
+
function J(e, { signal: n } = {}) {
|
|
1686
|
+
return new Promise((t, o) => {
|
|
1687
|
+
if (n?.aborted)
|
|
1688
|
+
return o(n.reason);
|
|
1689
|
+
let r = setTimeout(() => {
|
|
1690
|
+
n?.removeEventListener("abort", s), t();
|
|
1691
|
+
}, e);
|
|
1692
|
+
function s() {
|
|
1693
|
+
clearTimeout(r), o(n.reason);
|
|
1694
|
+
}
|
|
1695
|
+
n?.addEventListener("abort", s, { once: true });
|
|
1696
|
+
});
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1699
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-8xadcg99.js
|
|
1700
|
+
init_chunk_rkhsft4a();
|
|
1701
|
+
async function ae(r, { attempts: t = 3, delay: s = 1000, backoff: m = 2, maxDelay: o = 1 / 0, jitter: i = false, shouldRetry: a, onRetry: u, signal: l } = {}) {
|
|
1702
|
+
let c = i === true ? 1 : Number(i), e;
|
|
1703
|
+
for (let n = 0;n < t + 1; n++) {
|
|
1704
|
+
l?.throwIfAborted();
|
|
1705
|
+
try {
|
|
1706
|
+
return await r(n);
|
|
1707
|
+
} catch (f) {
|
|
1708
|
+
if (e = f, a && !a(f, n))
|
|
1709
|
+
throw f;
|
|
1710
|
+
if (n < t) {
|
|
1711
|
+
let p = Math.min(s * m ** n, o) * (1 - c * Math.random());
|
|
1712
|
+
u?.(f, n, p), await J(p, { signal: l });
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
throw Error(`Failed after ${t} ${G("retry", t)}`, { cause: e });
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-4faezqnz.js
|
|
1720
|
+
function s(...e) {
|
|
1721
|
+
let r = new Headers;
|
|
1722
|
+
for (let n of e) {
|
|
1723
|
+
if (!n)
|
|
1724
|
+
continue;
|
|
1725
|
+
let i;
|
|
1726
|
+
if (n instanceof Headers)
|
|
1727
|
+
i = [...n];
|
|
1728
|
+
else
|
|
1729
|
+
i = Array.isArray(n) ? n : Object.entries(n);
|
|
1730
|
+
for (let [a, t] of i)
|
|
1731
|
+
if (t !== undefined)
|
|
1732
|
+
r.set(a, t);
|
|
1733
|
+
}
|
|
1734
|
+
return r;
|
|
1735
|
+
}
|
|
1736
|
+
function T2(e) {
|
|
1737
|
+
return w(e) || Array.isArray(e);
|
|
1738
|
+
}
|
|
1739
|
+
function J2(e) {
|
|
1740
|
+
return typeof e === "string" || e instanceof ArrayBuffer || ArrayBuffer.isView(e) || e instanceof FormData || e instanceof URLSearchParams || e instanceof ReadableStream || typeof Blob < "u" && e instanceof Blob;
|
|
1741
|
+
}
|
|
1742
|
+
var b3 = "http://relative.invalid";
|
|
1743
|
+
function I(e) {
|
|
1744
|
+
try {
|
|
1745
|
+
return { parsed: new URL(e), relative: false };
|
|
1746
|
+
} catch {
|
|
1747
|
+
return { parsed: new URL(e, b3), relative: true };
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
function B2(e, r) {
|
|
1751
|
+
if (!r)
|
|
1752
|
+
return e;
|
|
1753
|
+
let { parsed: n, relative: i } = I(e);
|
|
1754
|
+
for (let [t, o] of Object.entries(r))
|
|
1755
|
+
for (let u of Array.isArray(o) ? o : [o])
|
|
1756
|
+
if (u !== undefined)
|
|
1757
|
+
n.searchParams.append(t, String(u));
|
|
1758
|
+
if (!i)
|
|
1759
|
+
return n.href;
|
|
1760
|
+
let a = `${n.pathname}${n.search}${n.hash}`;
|
|
1761
|
+
return n.origin === b3 ? a : `//${n.host}${a}`;
|
|
1762
|
+
}
|
|
1763
|
+
function E(e) {
|
|
1764
|
+
if (!e)
|
|
1765
|
+
return;
|
|
1766
|
+
try {
|
|
1767
|
+
return JSON.parse(e);
|
|
1768
|
+
} catch {
|
|
1769
|
+
return;
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
function v(e) {
|
|
1773
|
+
if (!w(e))
|
|
1774
|
+
return;
|
|
1775
|
+
for (let r of ["error", "message", "detail"])
|
|
1776
|
+
if (typeof e[r] === "string" && e[r])
|
|
1777
|
+
return e[r];
|
|
1778
|
+
return;
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1781
|
+
class ie extends Error {
|
|
1782
|
+
status;
|
|
1783
|
+
statusText;
|
|
1784
|
+
url;
|
|
1785
|
+
body;
|
|
1786
|
+
data;
|
|
1787
|
+
said;
|
|
1788
|
+
constructor(e, r, n, i, a) {
|
|
1789
|
+
let t = v(a), o = t ?? i;
|
|
1790
|
+
super(`HTTP ${e} ${r} - ${n}${o ? ` - ${o}` : ""}`);
|
|
1791
|
+
this.status = e;
|
|
1792
|
+
this.statusText = r;
|
|
1793
|
+
this.url = n;
|
|
1794
|
+
this.body = i;
|
|
1795
|
+
this.data = a;
|
|
1796
|
+
this.name = "FetchError", this.said = t;
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
async function x(e, r) {
|
|
1800
|
+
let n;
|
|
1801
|
+
try {
|
|
1802
|
+
n = await e.text();
|
|
1803
|
+
} catch {
|
|
1804
|
+
n = "";
|
|
1805
|
+
}
|
|
1806
|
+
return new ie(e.status, e.statusText, e.url || r, n || undefined, E(n));
|
|
1807
|
+
}
|
|
1808
|
+
|
|
1809
|
+
class _e extends Error {
|
|
1810
|
+
url;
|
|
1811
|
+
body;
|
|
1812
|
+
constructor(e, r, n) {
|
|
1813
|
+
super(`Invalid JSON response from ${e} - ${r.slice(0, 200)}`, { cause: n });
|
|
1814
|
+
this.url = e;
|
|
1815
|
+
this.body = r;
|
|
1816
|
+
this.name = "FetchParseError";
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
function q(e) {
|
|
1820
|
+
if (e instanceof ie)
|
|
1821
|
+
return e.status === 408 || e.status === 429 || e.status >= 500;
|
|
1822
|
+
return e instanceof TypeError || e instanceof DOMException && e.name === "TimeoutError";
|
|
1823
|
+
}
|
|
1824
|
+
async function c(e, r = {}) {
|
|
1825
|
+
let { retry: n, onError: i, ...a } = r, { signal: t } = a;
|
|
1826
|
+
try {
|
|
1827
|
+
let o = H2(e, a);
|
|
1828
|
+
if (!n)
|
|
1829
|
+
return await m(o);
|
|
1830
|
+
let { attempts: u = 3, shouldRetry: d = q, ...f } = typeof n === "number" ? { attempts: n } : n;
|
|
1831
|
+
return await ae(() => m(o), { ...f, attempts: u, signal: t ?? undefined, shouldRetry: (p, y) => y < u && !t?.aborted && d(p, y) });
|
|
1832
|
+
} catch (o) {
|
|
1833
|
+
throw i?.(o), o;
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
function A(e, r, n) {
|
|
1837
|
+
if (e === undefined || e === null)
|
|
1838
|
+
return null;
|
|
1839
|
+
return r ? n(e) : e;
|
|
1840
|
+
}
|
|
1841
|
+
function H2(e, r) {
|
|
1842
|
+
let { baseUrl: n, token: i, query: a, body: t, headers: o, timeout: u, signal: d, onResponse: f, fetch: p = fetch, parse: y = JSON.parse, serialize: R = JSON.stringify, ...k } = r, g = B2(n ? new URL(e, n).href : e, a), h = T2(t);
|
|
1843
|
+
if (t !== undefined && t !== null && !h && !J2(t))
|
|
1844
|
+
throw TypeError(`Unsupported body type for ${g}: ${Object.getPrototypeOf(t)?.constructor?.name ?? typeof t}`);
|
|
1845
|
+
let O = s({ Accept: "application/json", "Content-Type": h ? "application/json" : undefined, Authorization: i ? `Bearer ${i}` : undefined }, o);
|
|
1846
|
+
return { fullUrl: g, init: { ...k, headers: O, body: A(t, h, R) }, fetcher: p, parse: y, onResponse: f, timeout: u, signal: d };
|
|
1847
|
+
}
|
|
1848
|
+
async function m({ fullUrl: e, init: r, fetcher: n, parse: i, onResponse: a, timeout: t, signal: o }) {
|
|
1849
|
+
let u = l(o, t), d = await n(e, { ...r, ...u ? { signal: u } : {} });
|
|
1850
|
+
if (a?.(d), !d.ok)
|
|
1851
|
+
throw await x(d, e);
|
|
1852
|
+
let f = await d.text();
|
|
1853
|
+
if (!f)
|
|
1854
|
+
return null;
|
|
1855
|
+
try {
|
|
1856
|
+
return i(f);
|
|
1857
|
+
} catch (p) {
|
|
1858
|
+
throw new _e(d.url || e, f, p);
|
|
1859
|
+
}
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-dzf6hacc.js
|
|
1863
|
+
async function cr(r, t, o = [], s = {}) {
|
|
1864
|
+
let n = new FormData;
|
|
1865
|
+
n.append("payload_json", JSON.stringify(t));
|
|
1866
|
+
for (let e = 0;e < o.length; ++e) {
|
|
1867
|
+
let i = o[e], p = new Blob([new Uint8Array(i.buffer)], { type: i.contentType ?? "image/png" });
|
|
1868
|
+
n.append(`files[${e}]`, p, i.filename);
|
|
1869
|
+
}
|
|
1870
|
+
return await c(r, { ...s, timeout: s.timeout ?? T, method: "POST", body: n });
|
|
1871
|
+
}
|
|
1872
|
+
// package.json
|
|
1873
|
+
var version = "2.4.1";
|
|
1874
|
+
|
|
1875
|
+
// src/flags.ts
|
|
1876
|
+
var shared = {
|
|
1877
|
+
token: { type: "string", description: "The forge's token, defaults to GITHUB_TOKEN, then on GitHub to gh's login" },
|
|
1878
|
+
from: { type: "string", description: "From tag" },
|
|
1879
|
+
to: { type: "string", description: "To tag" },
|
|
1880
|
+
repo: { type: "string", short: "r", description: "Repository, e.g. kaynooo/cli, origin's by default (--gitea is kept as an alias)" },
|
|
1881
|
+
"release-repo": { type: "string", description: "Release repository, defaults to --repo (--release-gitea is kept as an alias)" },
|
|
1882
|
+
name: { type: "string", description: "Name of the release" },
|
|
1883
|
+
contributors: { type: "boolean", description: "Show contributors" },
|
|
1884
|
+
prerelease: { type: "boolean", description: "Mark release as prerelease" },
|
|
1885
|
+
draft: { type: "boolean", short: "d", description: "Mark release as draft" },
|
|
1886
|
+
output: { type: "string", description: "Output to file instead of sending to the forge" },
|
|
1887
|
+
capitalize: { type: "boolean", description: "Capitalize each commit message" },
|
|
1888
|
+
emoji: { type: "boolean", description: "Use emojis in section titles, --no-emoji to drop them" },
|
|
1889
|
+
group: { type: "boolean", description: "Nest commit messages under their scopes" },
|
|
1890
|
+
"first-parent": { type: "boolean", description: "Walk only the first parent of each merge" },
|
|
1891
|
+
"discord-webhook": { type: "string", description: "Discord webhook to post the release to, defaults to DISCORD_WEBHOOK" },
|
|
1892
|
+
"dry-run": { type: "boolean", description: "Dry run (--dry is kept as an alias)" },
|
|
1893
|
+
assets: { type: "string", multiple: true, description: "Files to upload as assets to the release, repeatable or comma separated; quote globs, e.g. --assets 'dist/*.js'" },
|
|
1894
|
+
json: jsonOption("release: {command, status, from, to, commits, notes, url, output, assetsFailed, discord}; undo: {command, status, tag, releaseNote, remoteTag, localTag, commitReset}. Progress goes to stderr"),
|
|
1895
|
+
debug: { type: "boolean", description: "Print the stack of an unexpected error" }
|
|
1896
|
+
};
|
|
1897
|
+
var undoFlags = {
|
|
1898
|
+
...shared,
|
|
1899
|
+
note: { type: "boolean", description: "Also delete the release note on the forge (skips the question)" },
|
|
1900
|
+
yes: { type: "boolean", description: "Skip confirmation prompts" }
|
|
1901
|
+
};
|
|
1902
|
+
var ALIASES = {
|
|
1903
|
+
"--dry": "--dry-run",
|
|
1904
|
+
"--gitea": "--repo",
|
|
1905
|
+
"--release-gitea": "--release-repo"
|
|
1906
|
+
};
|
|
1907
|
+
function aliasFlags(argv) {
|
|
1908
|
+
const end = argv.indexOf("--");
|
|
1909
|
+
const head = end === -1 ? argv : argv.slice(0, end);
|
|
1910
|
+
return [...head.map((word) => {
|
|
1911
|
+
const [name = "", ...value] = word.split("=");
|
|
1912
|
+
const current = ALIASES[name];
|
|
1913
|
+
return current === undefined ? word : [current, ...value].join("=");
|
|
1914
|
+
}), ...end === -1 ? [] : argv.slice(end)];
|
|
1915
|
+
}
|
|
1916
|
+
function defined(values) {
|
|
1917
|
+
return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined));
|
|
1918
|
+
}
|
|
1919
|
+
function toOptions(args) {
|
|
1920
|
+
return defined({
|
|
1921
|
+
token: args.token,
|
|
1922
|
+
from: args.from,
|
|
1923
|
+
to: args.to,
|
|
1924
|
+
repo: args.repo,
|
|
1925
|
+
releaseRepo: args["release-repo"],
|
|
1926
|
+
name: args.name,
|
|
1927
|
+
contributors: args.contributors,
|
|
1928
|
+
prerelease: args.prerelease,
|
|
1929
|
+
draft: args.draft,
|
|
1930
|
+
output: args.output,
|
|
1931
|
+
capitalize: args.capitalize,
|
|
1932
|
+
emoji: args.emoji,
|
|
1933
|
+
group: args.group,
|
|
1934
|
+
firstParent: args["first-parent"],
|
|
1935
|
+
discordWebhook: args["discord-webhook"],
|
|
1936
|
+
dry: args["dry-run"],
|
|
1937
|
+
assets: args.assets
|
|
1938
|
+
});
|
|
1939
|
+
}
|
|
1940
|
+
function withToken(options) {
|
|
1941
|
+
const token = [options.token, process.env.GITHUB_TOKEN].find((value) => value !== undefined && value !== "");
|
|
1942
|
+
return token === undefined ? options : { ...options, token };
|
|
1943
|
+
}
|
|
1944
|
+
function shouldAskNote({ release, note, yes, dry }) {
|
|
1945
|
+
return Boolean(release) && note !== true && yes !== true && dry !== true;
|
|
1946
|
+
}
|
|
1947
|
+
|
|
1948
|
+
// src/gitea.ts
|
|
1949
|
+
import path from "path";
|
|
1950
|
+
|
|
1951
|
+
// src/ui.ts
|
|
1952
|
+
var out = () => paint(process.stdout);
|
|
1953
|
+
var err = () => paint(process.stderr);
|
|
1954
|
+
async function stdoutToStderr(active, body) {
|
|
1955
|
+
const log = console.log;
|
|
1956
|
+
if (active)
|
|
1957
|
+
console.log = (...args) => console.error(...args.length === 0 ? [""] : args);
|
|
1958
|
+
try {
|
|
1959
|
+
return await body();
|
|
1960
|
+
} finally {
|
|
1961
|
+
console.log = log;
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1964
|
+
|
|
1965
|
+
// src/gitea.ts
|
|
1966
|
+
var REQUEST_MS = 60000;
|
|
1967
|
+
function onGithub(options) {
|
|
1968
|
+
return options.provider === "github";
|
|
1969
|
+
}
|
|
1970
|
+
function tagPath(options, repo, tag, write = false) {
|
|
1971
|
+
return onGithub(options) ? `repos/${repo}/git/${write ? "refs" : "ref"}/tags/${encodeURIComponent(tag)}` : `repos/${repo}/tags/${encodeURIComponent(tag)}`;
|
|
1972
|
+
}
|
|
1973
|
+
async function request(url, init) {
|
|
1974
|
+
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_MS) });
|
|
1975
|
+
if (!res.ok)
|
|
1976
|
+
throw new Error(`${res.status} ${res.statusText}: ${await res.text()}`);
|
|
1977
|
+
return res;
|
|
1978
|
+
}
|
|
1979
|
+
async function api(url, init) {
|
|
1980
|
+
return await (await request(url, init)).json();
|
|
1981
|
+
}
|
|
1982
|
+
async function sendRelease(options, content) {
|
|
1983
|
+
const headers = getHeaders(options);
|
|
1984
|
+
let url = `https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases`;
|
|
1985
|
+
let method = "POST";
|
|
1986
|
+
try {
|
|
1987
|
+
const exists = await api(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(options.to ?? "")}`, {
|
|
1988
|
+
headers
|
|
1989
|
+
});
|
|
1990
|
+
if (exists.url) {
|
|
1991
|
+
url = exists.url;
|
|
1992
|
+
method = "PATCH";
|
|
1993
|
+
}
|
|
1994
|
+
} catch {}
|
|
1995
|
+
const body = {
|
|
1996
|
+
body: content,
|
|
1997
|
+
draft: options.draft || false,
|
|
1998
|
+
name: options.name ?? options.to,
|
|
1999
|
+
prerelease: options.prerelease,
|
|
2000
|
+
tag_name: options.to
|
|
2001
|
+
};
|
|
2002
|
+
console.log(out().cyan(method === "POST" ? "Creating release notes..." : "Updating release notes..."));
|
|
2003
|
+
const res = await api(url, {
|
|
2004
|
+
method,
|
|
2005
|
+
body: JSON.stringify(body),
|
|
2006
|
+
headers: { ...headers, "content-type": "application/json" }
|
|
2007
|
+
});
|
|
2008
|
+
console.log(out().green(`Released on ${res.html_url}`));
|
|
2009
|
+
return res.html_url;
|
|
2010
|
+
}
|
|
2011
|
+
async function getRelease(options, tag) {
|
|
2012
|
+
try {
|
|
2013
|
+
return await api(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(tag)}`, {
|
|
2014
|
+
headers: getHeaders(options)
|
|
2015
|
+
});
|
|
2016
|
+
} catch {
|
|
2017
|
+
return null;
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
async function deleteRelease(options, releaseId) {
|
|
2021
|
+
await request(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/${releaseId}`, {
|
|
2022
|
+
method: "DELETE",
|
|
2023
|
+
headers: getHeaders(options)
|
|
2024
|
+
});
|
|
2025
|
+
}
|
|
2026
|
+
async function hasRemoteTag(options, tag) {
|
|
2027
|
+
try {
|
|
2028
|
+
await api(`https://${options.baseUrlApi}/${tagPath(options, options.releaseRepo, tag)}`, {
|
|
2029
|
+
headers: getHeaders(options)
|
|
2030
|
+
});
|
|
2031
|
+
return true;
|
|
2032
|
+
} catch {
|
|
2033
|
+
return false;
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
async function deleteRemoteTag(options, tag) {
|
|
2037
|
+
await request(`https://${options.baseUrlApi}/${tagPath(options, options.releaseRepo, tag, true)}`, {
|
|
2038
|
+
method: "DELETE",
|
|
2039
|
+
headers: getHeaders(options)
|
|
2040
|
+
});
|
|
2041
|
+
}
|
|
2042
|
+
function getHeaders(options) {
|
|
2043
|
+
if (onGithub(options))
|
|
2044
|
+
return { accept: "application/vnd.github+json", authorization: `Bearer ${options.token}`, "x-github-api-version": "2022-11-28" };
|
|
2045
|
+
return {
|
|
2046
|
+
accept: "application/vnd.gitea.v3+json",
|
|
2047
|
+
authorization: `token ${options.token}`
|
|
2048
|
+
};
|
|
2049
|
+
}
|
|
2050
|
+
var excludeAuthors = [
|
|
2051
|
+
/\[bot\]/i,
|
|
2052
|
+
/dependabot/i,
|
|
2053
|
+
/\(bot\)/i
|
|
2054
|
+
];
|
|
2055
|
+
async function resolveAuthorInfo(options, info) {
|
|
2056
|
+
if ((info.login ?? "") !== "")
|
|
2057
|
+
return info;
|
|
2058
|
+
if ((options.token ?? "") === "")
|
|
2059
|
+
return info;
|
|
2060
|
+
if (info.commits.length) {
|
|
2061
|
+
try {
|
|
2062
|
+
const data = await api(`https://${options.baseUrlApi}/repos/${options.repo}/${onGithub(options) ? "commits" : "git/commits"}/${info.commits[0]}`, {
|
|
2063
|
+
headers: getHeaders(options)
|
|
2064
|
+
});
|
|
2065
|
+
if (data.author !== null) {
|
|
2066
|
+
info.login = data.author.login;
|
|
2067
|
+
info.avatar = data.author.avatar_url;
|
|
2068
|
+
}
|
|
2069
|
+
} catch {}
|
|
2070
|
+
}
|
|
2071
|
+
if ((info.login ?? "") !== "" || onGithub(options))
|
|
2072
|
+
return info;
|
|
2073
|
+
try {
|
|
2074
|
+
const data = await api(`https://${options.baseUrlApi}/users/search?q=${encodeURIComponent(info.email)}`, {
|
|
2075
|
+
headers: getHeaders(options)
|
|
2076
|
+
});
|
|
2077
|
+
const user = data.data.find((user) => user.email.toLowerCase() === info.email.toLowerCase());
|
|
2078
|
+
if (user !== undefined) {
|
|
2079
|
+
info.login = user.login;
|
|
2080
|
+
if (user.avatar_url !== undefined)
|
|
2081
|
+
info.avatar = user.avatar_url;
|
|
2082
|
+
}
|
|
2083
|
+
} catch {}
|
|
2084
|
+
return info;
|
|
2085
|
+
}
|
|
2086
|
+
async function resolveAuthors(commits, options) {
|
|
2087
|
+
const map = new Map;
|
|
2088
|
+
for (const commit of commits) {
|
|
2089
|
+
for (const [idx, author] of commit.authors.entries()) {
|
|
2090
|
+
if (!author.email || !author.name || excludeAuthors.some((re) => re.test(author.name)))
|
|
2091
|
+
continue;
|
|
2092
|
+
if (!map.has(author.email))
|
|
2093
|
+
map.set(author.email, { commits: [], name: author.name, email: author.email });
|
|
2094
|
+
if (idx === 0)
|
|
2095
|
+
map.get(author.email).commits.push(commit.shortHash);
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
const authors = Array.from(map.values());
|
|
2099
|
+
const resolved = await Promise.all(authors.map(async (info) => resolveAuthorInfo(options, info)));
|
|
2100
|
+
const loginSet = new Set;
|
|
2101
|
+
const nameSet = new Set;
|
|
2102
|
+
return resolved.sort((a, b) => (a.login ?? a.name).localeCompare(b.login ?? b.name)).filter((i) => {
|
|
2103
|
+
if (i.login !== undefined && loginSet.has(i.login))
|
|
2104
|
+
return false;
|
|
2105
|
+
if (i.login !== undefined) {
|
|
2106
|
+
loginSet.add(i.login);
|
|
2107
|
+
} else {
|
|
2108
|
+
if (nameSet.has(i.name))
|
|
2109
|
+
return false;
|
|
2110
|
+
nameSet.add(i.name);
|
|
2111
|
+
}
|
|
2112
|
+
return true;
|
|
2113
|
+
});
|
|
2114
|
+
}
|
|
2115
|
+
async function hasTagOnGitea(tag, options) {
|
|
2116
|
+
try {
|
|
2117
|
+
const url = `https://${options.baseUrlApi}/${tagPath(options, options.repo, tag)}`;
|
|
2118
|
+
console.log(`checking if tag exists on ${url}`);
|
|
2119
|
+
await api(url, {
|
|
2120
|
+
headers: getHeaders(options)
|
|
2121
|
+
});
|
|
2122
|
+
return true;
|
|
2123
|
+
} catch {
|
|
2124
|
+
return false;
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
async function uploadAssets(options, assets) {
|
|
2128
|
+
const headers = getHeaders(options);
|
|
2129
|
+
let assetList = [];
|
|
2130
|
+
if (typeof assets === "string") {
|
|
2131
|
+
assetList = assets.split(",").map((s) => s.trim()).filter(Boolean);
|
|
2132
|
+
} else if (Array.isArray(assets)) {
|
|
2133
|
+
assetList = assets.flatMap((item) => typeof item === "string" ? item.split(",").map((s) => s.trim()) : []).filter(Boolean);
|
|
2134
|
+
}
|
|
2135
|
+
const expandedAssets = [];
|
|
2136
|
+
for (const pattern of assetList) {
|
|
2137
|
+
try {
|
|
2138
|
+
const glob = new Bun.Glob(pattern);
|
|
2139
|
+
const matches = Array.from(glob.scanSync());
|
|
2140
|
+
if (matches.length) {
|
|
2141
|
+
expandedAssets.push(...matches);
|
|
2142
|
+
} else {
|
|
2143
|
+
expandedAssets.push(pattern);
|
|
2144
|
+
}
|
|
2145
|
+
} catch (error) {
|
|
2146
|
+
console.error(err().red(`Failed to process glob pattern "${pattern}": ${String(error)}`));
|
|
2147
|
+
expandedAssets.push(pattern);
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
const release = await api(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(options.to ?? "")}`, {
|
|
2151
|
+
headers
|
|
2152
|
+
});
|
|
2153
|
+
let failed = 0;
|
|
2154
|
+
for (const asset of expandedAssets) {
|
|
2155
|
+
const filePath = path.resolve(asset);
|
|
2156
|
+
const file = Bun.file(filePath);
|
|
2157
|
+
if (!await file.exists()) {
|
|
2158
|
+
console.error(err().red(`Failed to read file ${filePath}: file does not exist`));
|
|
2159
|
+
failed++;
|
|
2160
|
+
continue;
|
|
2161
|
+
}
|
|
2162
|
+
const fileName = path.basename(filePath);
|
|
2163
|
+
const assetsPath = `repos/${options.releaseRepo}/releases/${release.id}/assets?name=${encodeURIComponent(fileName)}`;
|
|
2164
|
+
console.log(out().cyan(`Uploading ${fileName}...`));
|
|
2165
|
+
try {
|
|
2166
|
+
if (onGithub(options)) {
|
|
2167
|
+
await request(`https://uploads.github.com/${assetsPath}`, { method: "POST", headers: { ...headers, "content-type": "application/octet-stream" }, body: file });
|
|
2168
|
+
} else {
|
|
2169
|
+
const form = new FormData;
|
|
2170
|
+
form.append("attachment", file, fileName);
|
|
2171
|
+
await request(`https://${options.baseUrlApi}/${assetsPath}`, { method: "POST", headers, body: form });
|
|
2172
|
+
}
|
|
2173
|
+
console.log(out().green(`Uploaded ${fileName} successfully.`));
|
|
2174
|
+
} catch (error) {
|
|
2175
|
+
console.error(err().red(`Failed to upload ${fileName}: ${String(error)}`));
|
|
2176
|
+
failed++;
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
return failed;
|
|
2180
|
+
}
|
|
2181
|
+
|
|
2182
|
+
// src/config.ts
|
|
2183
|
+
import { join as join6 } from "path";
|
|
2184
|
+
var {$: $2 } = globalThis.Bun;
|
|
2185
|
+
|
|
2186
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-4yevg2zv.js
|
|
2187
|
+
var o2 = /^(\d+)\.(\d+)\.(\d+)$/;
|
|
2188
|
+
function wn(r) {
|
|
2189
|
+
return o2.test(r);
|
|
2190
|
+
}
|
|
2191
|
+
function Z(r) {
|
|
2192
|
+
let n = o2.exec(r);
|
|
2193
|
+
if (!n)
|
|
2194
|
+
throw Error(`Invalid semver: "${r}"`);
|
|
2195
|
+
return { major: Number(n[1]), minor: Number(n[2]), patch: Number(n[3]) };
|
|
2196
|
+
}
|
|
2197
|
+
|
|
2198
|
+
// src/git.ts
|
|
2199
|
+
var {$ } = globalThis.Bun;
|
|
2200
|
+
var gitSuffixRE = /\.git$/;
|
|
2201
|
+
var sshRegex = /(?:ssh:\/\/[^/]+\/|^(?:[^@/\s]+@)?[^:/\s]+:)(\w[\w.-]*)\/(\w[\w.-]*)$/i;
|
|
2202
|
+
var regexSpecialRE = /[.*+?^${}()|[\]\\]/g;
|
|
2203
|
+
var httpsRegex = /https?:\/\/[^/]+\/(\w[\w.-]*)\/(\w[\w.-]*)$/i;
|
|
2204
|
+
var releaseVersionRE = /^[^.]*(?:\.[\d.]*|\d)$/;
|
|
2205
|
+
var TAG_DECORATION = /tag: ([^,\n]+)/g;
|
|
2206
|
+
var ORIGIN_HOST = /^(?:[a-z][a-z\d+.-]*:\/\/)?(?:[^@/]+@)?([^:/]+)/i;
|
|
2207
|
+
async function getOriginHost() {
|
|
2208
|
+
const url = (await $`git config --get remote.origin.url`.quiet().nothrow().text()).trim();
|
|
2209
|
+
return ORIGIN_HOST.exec(url)?.[1];
|
|
2210
|
+
}
|
|
2211
|
+
async function getGiteaRepo() {
|
|
2212
|
+
const url = await execCommand("git", ["config", "--get", "remote.origin.url"]);
|
|
2213
|
+
const cleanUrl = url.replace(gitSuffixRE, "");
|
|
2214
|
+
let match = sshRegex.exec(cleanUrl);
|
|
2215
|
+
match ||= httpsRegex.exec(cleanUrl);
|
|
2216
|
+
if (!match)
|
|
2217
|
+
throw new Error(`Can not parse Gitea repo from url ${url}`);
|
|
2218
|
+
return `${match[1]}/${match[2]}`;
|
|
2219
|
+
}
|
|
2220
|
+
async function getCurrentGitBranch() {
|
|
2221
|
+
const [tag] = (await execCommand("git", ["tag", "--points-at", "HEAD", "--sort=-v:refname"])).split(`
|
|
2222
|
+
`);
|
|
2223
|
+
return tag !== undefined && tag !== "" ? tag : execCommand("git", ["rev-parse", "--abbrev-ref", "HEAD"]);
|
|
2224
|
+
}
|
|
2225
|
+
async function isRepoShallow() {
|
|
2226
|
+
return (await execCommand("git", ["rev-parse", "--is-shallow-repository"])).trim() === "true";
|
|
2227
|
+
}
|
|
2228
|
+
function getSafeTagTemplate(template) {
|
|
2229
|
+
return template.includes("%s") ? template : `${template}%s`;
|
|
2230
|
+
}
|
|
2231
|
+
function getVersionString(template, tag) {
|
|
2232
|
+
const pattern = template.split("%s").map((part) => part.replace(regexSpecialRE, "\\$&")).join("(.+)");
|
|
2233
|
+
const regex = new RegExp(`^${pattern}$`);
|
|
2234
|
+
const match = regex.exec(tag);
|
|
2235
|
+
return match?.[1] ?? tag;
|
|
2236
|
+
}
|
|
2237
|
+
async function tipOf(to) {
|
|
2238
|
+
return (await $`git rev-parse --verify -q ${`${to}^{commit}`}`.quiet().nothrow()).exitCode === 0 ? to : "HEAD";
|
|
2239
|
+
}
|
|
2240
|
+
async function getGitTags(firstParent = false, to = "HEAD") {
|
|
2241
|
+
const output = await execCommand("git", ["log", ...firstParent ? ["--first-parent"] : [], "--decorate-refs=refs/tags/", "--format=%D", await tipOf(to), "--"]);
|
|
2242
|
+
return [...output.matchAll(TAG_DECORATION)].map((match) => match[1]?.trim() ?? "").filter((tag) => tag !== "");
|
|
2243
|
+
}
|
|
2244
|
+
async function getLastMatchingTag(inputTag, tagFilter, tagTemplate, rollup = {}, firstParent = false) {
|
|
2245
|
+
const inputVersionString = getVersionString(tagTemplate, inputTag);
|
|
2246
|
+
const isStableVersion = wn(inputVersionString);
|
|
2247
|
+
const tags = await getGitTags(firstParent, inputTag);
|
|
2248
|
+
const filteredTags = tags.filter(tagFilter);
|
|
2249
|
+
let tag;
|
|
2250
|
+
if (isStableVersion) {
|
|
2251
|
+
const input = Z(inputVersionString);
|
|
2252
|
+
const isMajor = input.minor === 0 && input.patch === 0;
|
|
2253
|
+
const isMinor = !isMajor && input.patch === 0;
|
|
2254
|
+
let boundary;
|
|
2255
|
+
if (isMajor && rollup.major)
|
|
2256
|
+
boundary = (v) => v.minor === 0 && v.patch === 0;
|
|
2257
|
+
else if (isMinor && rollup.minor)
|
|
2258
|
+
boundary = (v) => v.patch === 0;
|
|
2259
|
+
tag = filteredTags.find((tag) => {
|
|
2260
|
+
const versionString = getVersionString(tagTemplate, tag);
|
|
2261
|
+
if (versionString === inputVersionString || !wn(versionString))
|
|
2262
|
+
return false;
|
|
2263
|
+
return boundary ? boundary(Z(versionString)) : true;
|
|
2264
|
+
});
|
|
2265
|
+
}
|
|
2266
|
+
tag ||= filteredTags.find((tag) => tag !== inputTag);
|
|
2267
|
+
return tag;
|
|
2268
|
+
}
|
|
2269
|
+
async function isRefGitTag(to) {
|
|
2270
|
+
const ref = `refs/tags/${to}`;
|
|
2271
|
+
try {
|
|
2272
|
+
await $`git show-ref --verify ${ref}`.quiet();
|
|
2273
|
+
return true;
|
|
2274
|
+
} catch {
|
|
2275
|
+
return false;
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
async function getFirstGitCommit(firstParent = false, to = "HEAD") {
|
|
2279
|
+
return (await execCommand("git", ["rev-list", "--max-parents=0", ...firstParent ? ["--first-parent"] : [], await tipOf(to), "--"])).split(`
|
|
2280
|
+
`).at(-1) ?? "";
|
|
2281
|
+
}
|
|
2282
|
+
async function deleteLocalTag(tag) {
|
|
2283
|
+
await $`git tag -d ${tag}`.quiet();
|
|
2284
|
+
}
|
|
2285
|
+
async function hasRemoteGitTag(tag, remote = "origin") {
|
|
2286
|
+
return (await execCommand("git", ["ls-remote", "--tags", remote, `refs/tags/${tag}`])).length > 0;
|
|
2287
|
+
}
|
|
2288
|
+
async function deleteRemoteGitTag(tag, remote = "origin") {
|
|
2289
|
+
await $`git push ${remote} --delete ${tag}`.quiet();
|
|
2290
|
+
}
|
|
2291
|
+
async function getTagCommit(tag) {
|
|
2292
|
+
return execCommand("git", ["rev-list", "-n", "1", tag]);
|
|
2293
|
+
}
|
|
2294
|
+
async function getHeadCommit() {
|
|
2295
|
+
return execCommand("git", ["rev-parse", "HEAD"]);
|
|
2296
|
+
}
|
|
2297
|
+
async function getCommitSubject(ref) {
|
|
2298
|
+
return execCommand("git", ["log", "-1", "--format=%s", ref]);
|
|
2299
|
+
}
|
|
2300
|
+
async function softResetLastCommit() {
|
|
2301
|
+
await $`git reset --soft HEAD~1`.quiet();
|
|
2302
|
+
}
|
|
2303
|
+
function isPrerelease(version) {
|
|
2304
|
+
return !releaseVersionRE.test(version);
|
|
2305
|
+
}
|
|
2306
|
+
async function execCommand(cmd, args) {
|
|
2307
|
+
return (await $`${cmd} ${args}`.quiet().text()).trim();
|
|
2308
|
+
}
|
|
2309
|
+
|
|
2310
|
+
// src/config.ts
|
|
2311
|
+
var GITHUB = "github.com";
|
|
2312
|
+
function forgeName(config) {
|
|
2313
|
+
return config.provider === "github" ? "GitHub" : "Forgejo";
|
|
2314
|
+
}
|
|
2315
|
+
var configFiles = ["ts", "mts", "js", "mjs", "json"].map((ext) => `changelog.config.${ext}`);
|
|
2316
|
+
var defaultConfig = {
|
|
2317
|
+
scopeMap: {},
|
|
2318
|
+
types: {
|
|
2319
|
+
feat: { title: "\u2728 New" },
|
|
2320
|
+
fix: { title: "\uD83D\uDD27 Fixed" },
|
|
2321
|
+
perf: { title: "\u26A1 Faster" },
|
|
2322
|
+
refactor: { title: "refactor", folded: true },
|
|
2323
|
+
docs: { title: "docs", folded: true },
|
|
2324
|
+
build: { title: "build", folded: true },
|
|
2325
|
+
types: { title: "types", folded: true },
|
|
2326
|
+
test: { title: "test", folded: true },
|
|
2327
|
+
style: { title: "style", folded: true },
|
|
2328
|
+
ci: { title: "ci", folded: true }
|
|
2329
|
+
},
|
|
2330
|
+
titles: {
|
|
2331
|
+
breakingChanges: "\u26A0\uFE0F Breaking",
|
|
2332
|
+
highlights: "\uD83C\uDF1F Highlights",
|
|
2333
|
+
maintenance: "\uD83E\uDDF9 Maintenance"
|
|
2334
|
+
},
|
|
2335
|
+
contributors: true,
|
|
2336
|
+
capitalize: true,
|
|
2337
|
+
group: true,
|
|
2338
|
+
emoji: true,
|
|
2339
|
+
firstParent: false,
|
|
2340
|
+
tag: "v%s"
|
|
2341
|
+
};
|
|
2342
|
+
function isPlainObject(value) {
|
|
2343
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2344
|
+
}
|
|
2345
|
+
function mergeLayers(...layers) {
|
|
2346
|
+
const merged = {};
|
|
2347
|
+
for (const layer of layers) {
|
|
2348
|
+
for (const [key, value] of Object.entries(layer)) {
|
|
2349
|
+
if (value === undefined)
|
|
2350
|
+
continue;
|
|
2351
|
+
merged[key] = isPlainObject(value) && isPlainObject(merged[key]) ? mergeLayers(merged[key], value) : value;
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
return merged;
|
|
2355
|
+
}
|
|
2356
|
+
async function loadConfigFile(cwd) {
|
|
2357
|
+
for (const name of configFiles) {
|
|
2358
|
+
const path = join6(cwd, name);
|
|
2359
|
+
if (await Bun.file(path).exists())
|
|
2360
|
+
return (await import(path)).default ?? {};
|
|
2361
|
+
}
|
|
2362
|
+
return {};
|
|
2363
|
+
}
|
|
2364
|
+
async function ghToken() {
|
|
2365
|
+
if (Bun.which("gh") === null)
|
|
2366
|
+
return;
|
|
2367
|
+
const answer = await $2`gh auth token`.quiet().nothrow();
|
|
2368
|
+
return answer.exitCode === 0 && answer.text().trim() !== "" ? answer.text().trim() : undefined;
|
|
2369
|
+
}
|
|
2370
|
+
async function loadPackageConfig(cwd) {
|
|
2371
|
+
const file = Bun.file(join6(cwd, "package.json"));
|
|
2372
|
+
return !await file.exists() ? {} : (await file.json()).changelog ?? {};
|
|
2373
|
+
}
|
|
2374
|
+
async function loadConfig(options, cwd = process.cwd()) {
|
|
2375
|
+
const [packageConfig, fileConfig] = await Promise.all([loadPackageConfig(cwd), loadConfigFile(cwd)]);
|
|
2376
|
+
return mergeLayers(defaultConfig, packageConfig, fileConfig, options);
|
|
2377
|
+
}
|
|
2378
|
+
async function resolveConfig(options) {
|
|
2379
|
+
const config = await loadConfig(options);
|
|
2380
|
+
const origin = config.baseUrl === undefined ? await getOriginHost() : undefined;
|
|
2381
|
+
const baseUrl = config.baseUrl ?? (origin === GITHUB ? origin : configuredForge()?.host ?? origin);
|
|
2382
|
+
if (baseUrl === undefined || baseUrl === "")
|
|
2383
|
+
throw new Error("no forge to link the notes to: set baseUrl in the changelog config, forge in ~/.config/kaynooo-cli/config.json, or an origin remote");
|
|
2384
|
+
config.baseUrl = baseUrl;
|
|
2385
|
+
config.provider ??= baseUrl === GITHUB ? "github" : "gitea";
|
|
2386
|
+
config.baseUrlApi ??= config.provider === "github" ? "api.github.com" : `${baseUrl}/api/v1`;
|
|
2387
|
+
const token = config.provider === "github" && (config.token ?? "") === "" ? await ghToken() : undefined;
|
|
2388
|
+
if (token !== undefined)
|
|
2389
|
+
config.token = token;
|
|
2390
|
+
config.to ||= await getCurrentGitBranch();
|
|
2391
|
+
config.tagFilter ??= () => true;
|
|
2392
|
+
config.tag = getSafeTagTemplate(config.tag ?? defaultConfig.tag);
|
|
2393
|
+
config.rollup ??= {};
|
|
2394
|
+
config.fromRoot = false;
|
|
2395
|
+
if (config.from === undefined || config.from === "") {
|
|
2396
|
+
const tag = await getLastMatchingTag(config.to, config.tagFilter, config.tag, config.rollup, config.firstParent);
|
|
2397
|
+
config.fromRoot = tag === undefined;
|
|
2398
|
+
config.from = tag ?? await getFirstGitCommit(config.firstParent, config.to);
|
|
2399
|
+
}
|
|
2400
|
+
const legacy = config;
|
|
2401
|
+
config.repo ||= legacy.gitea ?? await getGiteaRepo();
|
|
2402
|
+
config.releaseRepo ||= legacy.releaseGithub ?? config.repo;
|
|
2403
|
+
config.prerelease ??= isPrerelease(config.to);
|
|
2404
|
+
config.discordWebhook ??= process.env.DISCORD_WEBHOOK ?? "";
|
|
2405
|
+
if (typeof config.repo !== "string")
|
|
2406
|
+
throw new TypeError(`Invalid repository, expected a string but got ${JSON.stringify(config.repo)}`);
|
|
2407
|
+
return config;
|
|
2408
|
+
}
|
|
2409
|
+
|
|
2410
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-m6zaxxzm.js
|
|
2411
|
+
function p2(n) {
|
|
2412
|
+
return n !== null && n !== undefined;
|
|
2413
|
+
}
|
|
2414
|
+
function m2(n, e, t) {
|
|
2415
|
+
Object.defineProperty(n, e, { value: t, enumerable: true, writable: true, configurable: true });
|
|
2416
|
+
}
|
|
2417
|
+
function Fr(n, e) {
|
|
2418
|
+
let t = {};
|
|
2419
|
+
for (let o of n) {
|
|
2420
|
+
let u = e(o);
|
|
2421
|
+
if (Object.hasOwn(t, u))
|
|
2422
|
+
t[u].push(o);
|
|
2423
|
+
else
|
|
2424
|
+
m2(t, u, [o]);
|
|
2425
|
+
}
|
|
2426
|
+
return t;
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
// src/markdown.ts
|
|
2430
|
+
init_text();
|
|
2431
|
+
var emojiRE = /\p{Extended_Pictographic}\uFE0F?/gu;
|
|
2432
|
+
var fullHashRE = /^[\da-f]{40}$/;
|
|
2433
|
+
var IDENTIFIER_START = /^(?:`|[a-z]+[A-Z]|\S*\d|\S*[._/]\w)/;
|
|
2434
|
+
function groupCommits(commits, options) {
|
|
2435
|
+
const breaking = commits.filter((c) => c.isBreaking);
|
|
2436
|
+
const byType = Fr(commits.filter((c) => !c.isBreaking), (c) => c.type);
|
|
2437
|
+
const sections = breaking.length ? [{ title: options.titles.breakingChanges, commits: breaking }] : [];
|
|
2438
|
+
const folded = [];
|
|
2439
|
+
for (const [type, config] of Object.entries(options.types)) {
|
|
2440
|
+
const typed = byType[type] ?? [];
|
|
2441
|
+
if (typeof config === "boolean" || typed.length === 0)
|
|
2442
|
+
continue;
|
|
2443
|
+
const target = config.folded === true ? folded : sections;
|
|
2444
|
+
target.push({ title: config.title, commits: typed });
|
|
2445
|
+
}
|
|
2446
|
+
return { sections, folded };
|
|
2447
|
+
}
|
|
2448
|
+
function formatTitle(title, options) {
|
|
2449
|
+
return (options.emoji ? title : title.replace(emojiRE, "")).trim();
|
|
2450
|
+
}
|
|
2451
|
+
function shortRef(ref) {
|
|
2452
|
+
return fullHashRE.test(ref) ? ref.slice(0, 7) : ref;
|
|
2453
|
+
}
|
|
2454
|
+
function repoUrl(options) {
|
|
2455
|
+
return `https://${options.baseUrl}/${options.repo}`;
|
|
2456
|
+
}
|
|
2457
|
+
function compareUrl(options) {
|
|
2458
|
+
return `${repoUrl(options)}/compare/${options.from}...${options.to}`;
|
|
2459
|
+
}
|
|
2460
|
+
function releaseUrl(options) {
|
|
2461
|
+
return `https://${options.baseUrl}/${options.releaseRepo}/releases/tag/${encodeURIComponent(options.to)}`;
|
|
2462
|
+
}
|
|
2463
|
+
function userUrl(login, options) {
|
|
2464
|
+
return `https://${options.baseUrl}/${login}`;
|
|
2465
|
+
}
|
|
2466
|
+
function formatIssue(ref, options, withTitle) {
|
|
2467
|
+
const text = withTitle && ref.title !== undefined ? `${ref.value} ${ref.title}` : ref.value;
|
|
2468
|
+
return `[${text}](${repoUrl(options)}/issues/${ref.value.slice(1)})`;
|
|
2469
|
+
}
|
|
2470
|
+
function capitalized(description) {
|
|
2471
|
+
return IDENTIFIER_START.test(description) ? description : d(description);
|
|
2472
|
+
}
|
|
2473
|
+
function formatLine(commit, options, prefix = "", issueTitles = false) {
|
|
2474
|
+
const description = options.capitalize ? capitalized(commit.description) : commit.description;
|
|
2475
|
+
const hash = `[\`${commit.shortHash.slice(0, 7)}\`](${repoUrl(options)}/commit/${commit.shortHash})`;
|
|
2476
|
+
const issues = commit.references.filter((ref) => ref.type !== "hash").map((ref) => formatIssue(ref, options, issueTitles));
|
|
2477
|
+
return [`${prefix}${description}`, hash, ...issues].join(" \xB7 ");
|
|
2478
|
+
}
|
|
2479
|
+
function foldedPrefix(commit) {
|
|
2480
|
+
return `**${commit.scope ? `${commit.type}(${commit.scope})` : commit.type}**: `;
|
|
2481
|
+
}
|
|
2482
|
+
function foldedCounts(folded, options) {
|
|
2483
|
+
return folded.map((section) => `${section.commits.length} ${formatTitle(section.title, options)}`).join(", ");
|
|
2484
|
+
}
|
|
2485
|
+
function formatAuthors(contributors, options) {
|
|
2486
|
+
return join7(contributors.map((c) => c.login !== undefined ? `[@${c.login}](${userUrl(c.login, options)})` : `**${c.name}**`));
|
|
2487
|
+
}
|
|
2488
|
+
function summaryLabel(title) {
|
|
2489
|
+
return title.replace(emojiRE, "").trim().toLowerCase();
|
|
2490
|
+
}
|
|
2491
|
+
function formatSummary({ sections, folded }, contributors, options) {
|
|
2492
|
+
const counts = sections.map((section) => `${section.commits.length} ${summaryLabel(section.title)}`);
|
|
2493
|
+
if (folded.length) {
|
|
2494
|
+
const total = folded.reduce((sum, section) => sum + section.commits.length, 0);
|
|
2495
|
+
counts.push(`${total} ${summaryLabel(options.titles.maintenance)}`);
|
|
2496
|
+
}
|
|
2497
|
+
const authors = formatAuthors(contributors, options);
|
|
2498
|
+
const parts = [
|
|
2499
|
+
counts.length ? `**${counts.join(" \xB7 ")}**` : "",
|
|
2500
|
+
authors && `by ${authors}`,
|
|
2501
|
+
`\`${shortRef(options.from)}\` \u2192 \`${shortRef(options.to)}\``
|
|
2502
|
+
];
|
|
2503
|
+
return `> ${parts.filter(Boolean).join(" \xB7 ")}`;
|
|
2504
|
+
}
|
|
2505
|
+
function formatSection(section, options) {
|
|
2506
|
+
const lines = ["", `### ${formatTitle(section.title, options)}`, ""];
|
|
2507
|
+
const scopes = Fr(section.commits, (c) => c.scope);
|
|
2508
|
+
const nestable = Object.entries(scopes).some(([scope, commits]) => scope !== "" && commits.length > 1);
|
|
2509
|
+
for (const [scope, commits] of Object.entries(scopes).sort(([a], [b]) => a.localeCompare(b))) {
|
|
2510
|
+
const scopeText = `**${scope}**`;
|
|
2511
|
+
const nested = nestable && scope !== "" && (options.group === true || options.group === "multiple" && commits.length > 1);
|
|
2512
|
+
const prefix = scope !== "" && !nested ? `${scopeText}: ` : "";
|
|
2513
|
+
const padding = nested ? " " : "";
|
|
2514
|
+
if (nested)
|
|
2515
|
+
lines.push(`- ${scopeText}:`);
|
|
2516
|
+
for (const commit of commits.toReversed()) {
|
|
2517
|
+
lines.push(`${padding}- ${formatLine(commit, options, prefix)}`);
|
|
2518
|
+
if (commit.breakingNote !== undefined)
|
|
2519
|
+
lines.push(`${padding} - ${commit.breakingNote}`);
|
|
2520
|
+
}
|
|
2521
|
+
}
|
|
2522
|
+
return lines;
|
|
2523
|
+
}
|
|
2524
|
+
function formatAvatars(contributors, options) {
|
|
2525
|
+
return contributors.filter((c) => c.login !== undefined && c.avatar !== undefined).map((c) => `<a href="${userUrl(c.login, options)}"><img src="${c.avatar}" width="28" height="28" alt="@${c.login}"></a>`).join(" ");
|
|
2526
|
+
}
|
|
2527
|
+
function generateMarkdown(commits, options, contributors = [], highlights) {
|
|
2528
|
+
const grouped = groupCommits(commits, options);
|
|
2529
|
+
const { sections, folded } = grouped;
|
|
2530
|
+
const lines = [formatSummary(grouped, contributors, options)];
|
|
2531
|
+
if (highlights)
|
|
2532
|
+
lines.push("", `### ${formatTitle(options.titles.highlights, options)}`, "", ...highlights.lines, "", `[Read more](${highlights.link})`);
|
|
2533
|
+
for (const section of sections)
|
|
2534
|
+
lines.push(...formatSection(section, options));
|
|
2535
|
+
if (folded.length) {
|
|
2536
|
+
lines.push("", "<details>", `<summary><b>${formatTitle(options.titles.maintenance, options)}</b> \xB7 ${foldedCounts(folded, options)}</summary>`, "", ...folded.flatMap((section) => section.commits.toReversed().map((commit) => `- ${formatLine(commit, options, foldedPrefix(commit))}`)), "", "</details>");
|
|
2537
|
+
}
|
|
2538
|
+
if (!sections.length && !folded.length)
|
|
2539
|
+
lines.push("", "*No significant changes*");
|
|
2540
|
+
lines.push("", "---", "");
|
|
2541
|
+
const avatars = formatAvatars(contributors, options);
|
|
2542
|
+
if (avatars)
|
|
2543
|
+
lines.push(avatars, "");
|
|
2544
|
+
lines.push(`<sub>[Full diff \`${shortRef(options.from)}...${shortRef(options.to)}\`](${compareUrl(options)}) \xB7 generated by cli-changelog</sub>`);
|
|
2545
|
+
return lines.join(`
|
|
2546
|
+
`);
|
|
2547
|
+
}
|
|
2548
|
+
function join7(array, glue = ", ", finalGlue = " and ") {
|
|
2549
|
+
return array.length <= 2 ? array.join(finalGlue) : `${array.slice(0, -1).join(glue)}${finalGlue}${array.at(-1)}`;
|
|
2550
|
+
}
|
|
2551
|
+
|
|
2552
|
+
// src/discord.ts
|
|
2553
|
+
var descriptionLimit = 4096;
|
|
2554
|
+
var color = 16486972;
|
|
2555
|
+
var breakingColor = 15548997;
|
|
2556
|
+
var fenceRE = /^\s*(`{3,}|~{3,})/;
|
|
2557
|
+
var headingRE = /^#{1,6}(?:\s(.*))?$/;
|
|
2558
|
+
var strongRE = /\*\*|__/g;
|
|
2559
|
+
var isCommitLine = (line) => line.startsWith("- ");
|
|
2560
|
+
function fitCommits(head, lines, tail) {
|
|
2561
|
+
const total = lines.filter(isCommitLine).length;
|
|
2562
|
+
for (let kept = lines.length;kept >= 0; kept--) {
|
|
2563
|
+
const shown = lines.slice(0, kept);
|
|
2564
|
+
while (shown.length && kept < lines.length && !isCommitLine(shown.at(-1)))
|
|
2565
|
+
shown.pop();
|
|
2566
|
+
const more = total - shown.filter(isCommitLine).length;
|
|
2567
|
+
const text = [...head, ...shown, ...more ? ["", `*\u2026and ${more} more*`] : [], "", tail].join(`
|
|
2568
|
+
`).trim();
|
|
2569
|
+
if (text.length <= descriptionLimit)
|
|
2570
|
+
return text;
|
|
2571
|
+
}
|
|
2572
|
+
return;
|
|
2573
|
+
}
|
|
2574
|
+
function fitDescription(head, lines, tail) {
|
|
2575
|
+
const fitted = fitCommits(head, lines, tail);
|
|
2576
|
+
if (fitted !== undefined || !head.length)
|
|
2577
|
+
return fitted ?? tail.slice(0, descriptionLimit);
|
|
2578
|
+
for (let kept = head.length - 2;kept >= 1; kept--) {
|
|
2579
|
+
const shown = head.slice(0, kept);
|
|
2580
|
+
const open = openFence(shown);
|
|
2581
|
+
if (open !== undefined)
|
|
2582
|
+
shown.push(open);
|
|
2583
|
+
const text = fitCommits([...shown, "\u2026", head.at(-1)], lines, tail);
|
|
2584
|
+
if (text !== undefined)
|
|
2585
|
+
return text;
|
|
2586
|
+
}
|
|
2587
|
+
return tail.slice(0, descriptionLimit);
|
|
2588
|
+
}
|
|
2589
|
+
function openFence(lines) {
|
|
2590
|
+
let open;
|
|
2591
|
+
for (const line of lines) {
|
|
2592
|
+
const marker = fenceRE.exec(line)?.[1];
|
|
2593
|
+
if (marker !== undefined)
|
|
2594
|
+
open = open !== undefined && marker.startsWith(open) ? undefined : open ?? marker;
|
|
2595
|
+
}
|
|
2596
|
+
return open;
|
|
2597
|
+
}
|
|
2598
|
+
var tableRowRE = /^\s*\|.*\|\s*$/;
|
|
2599
|
+
var tableRuleRE = /^\s*\|(?:\s*:?-+:?\s*\|)+\s*$/;
|
|
2600
|
+
var cellSplitRE = /(?<!\\)\|(?=(?:[^`]*`[^`]*`)*[^`]*$)/;
|
|
2601
|
+
function bulletedTables(lines) {
|
|
2602
|
+
let fenced = false;
|
|
2603
|
+
const out = [];
|
|
2604
|
+
for (const [index, line] of lines.entries()) {
|
|
2605
|
+
if (fenceRE.test(line))
|
|
2606
|
+
fenced = !fenced;
|
|
2607
|
+
if (fenced || !tableRowRE.test(line)) {
|
|
2608
|
+
out.push(line);
|
|
2609
|
+
continue;
|
|
2610
|
+
}
|
|
2611
|
+
if (tableRuleRE.test(line) || tableRuleRE.test(lines[index + 1] ?? ""))
|
|
2612
|
+
continue;
|
|
2613
|
+
const [first = "", ...rest] = line.trim().slice(1, -1).split(cellSplitRE).map((cell) => cell.trim());
|
|
2614
|
+
out.push(`- **${first}**${rest.length ? `: ${rest.join(" \xB7 ")}` : ""}`);
|
|
2615
|
+
}
|
|
2616
|
+
return out;
|
|
2617
|
+
}
|
|
2618
|
+
function highlightLines(highlights, options) {
|
|
2619
|
+
let fenced = false;
|
|
2620
|
+
const lines = bulletedTables(highlights.lines).flatMap((line) => {
|
|
2621
|
+
if (fenceRE.test(line))
|
|
2622
|
+
fenced = !fenced;
|
|
2623
|
+
const heading = fenced ? null : headingRE.exec(line);
|
|
2624
|
+
if (!heading)
|
|
2625
|
+
return [line];
|
|
2626
|
+
const text = (heading[1] ?? "").replace(strongRE, "").trim();
|
|
2627
|
+
return text ? [`**${text}**`] : [];
|
|
2628
|
+
});
|
|
2629
|
+
return [`**${formatTitle(options.titles.highlights, options)}**`, ...lines, `[Read more](${highlights.link})`];
|
|
2630
|
+
}
|
|
2631
|
+
function generateDiscordPayload(commits, options, contributors = [], highlights) {
|
|
2632
|
+
const { sections, folded } = groupCommits(commits, options);
|
|
2633
|
+
const lines = [];
|
|
2634
|
+
for (const section of sections) {
|
|
2635
|
+
lines.push("", `**${formatTitle(section.title, options)}**`);
|
|
2636
|
+
for (const commit of section.commits.toReversed())
|
|
2637
|
+
lines.push(`- ${formatLine(commit, options, commit.scope ? `**${commit.scope}**: ` : "", true)}`);
|
|
2638
|
+
}
|
|
2639
|
+
if (!sections.length && !folded.length)
|
|
2640
|
+
lines.push("*No significant changes*");
|
|
2641
|
+
const links = `[full notes](${releaseUrl(options)}) \xB7 [diff](${compareUrl(options)})`;
|
|
2642
|
+
const tail = folded.length ? `${formatTitle(options.titles.maintenance, options)} *${foldedCounts(folded, options)}* \xB7 ${links}` : links;
|
|
2643
|
+
const authors = contributors.map((c) => c.login ?? c.name).join(", ");
|
|
2644
|
+
const range = `${shortRef(options.from)} \u2192 ${shortRef(options.to)}`;
|
|
2645
|
+
const avatar = contributors.find((c) => c.avatar !== undefined)?.avatar;
|
|
2646
|
+
return {
|
|
2647
|
+
embeds: [{
|
|
2648
|
+
title: `${String(options.releaseRepo).split("/").at(-1)} ${options.name || options.to}`.slice(0, 256),
|
|
2649
|
+
url: releaseUrl(options),
|
|
2650
|
+
color: commits.some((c) => c.isBreaking) ? breakingColor : color,
|
|
2651
|
+
description: fitDescription(highlights ? highlightLines(highlights, options) : [], lines, tail),
|
|
2652
|
+
footer: { text: authors ? `${authors} \xB7 ${range}` : range, ...avatar === undefined ? {} : { icon_url: avatar } },
|
|
2653
|
+
timestamp: new Date().toISOString()
|
|
2654
|
+
}]
|
|
2655
|
+
};
|
|
2656
|
+
}
|
|
2657
|
+
|
|
2658
|
+
// src/changelog.ts
|
|
2659
|
+
var {$: $3 } = globalThis.Bun;
|
|
2660
|
+
var ConventionalCommitRegex = /^(?::.+:|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F\uDE80-\uDEFF]|[\u2600-\u2B55])? *(?<type>[a-z]+)(?:\((?<scope>[^()\n]+)\))?(?<breaking>!)?: (?<description>.+)/i;
|
|
2661
|
+
var CoAuthoredByRegex = /co-authored-by:\s*(?<name>\S[^<]*)<(?<email>[^>]+)>/gi;
|
|
2662
|
+
var PullRequestRE = /\([ a-z]*(#\d+)\s*\)/g;
|
|
2663
|
+
var IssueRE = /(#\d+)/g;
|
|
2664
|
+
var BreakingBodyRE = /^BREAKING[ -]CHANGE:[ \t]*(.*(?:\n(?![ \t]*$|[\w-]+(?:: | #)).+)*)/m;
|
|
2665
|
+
var TicketLineRE = /^(#\d+) - (.+)$/gm;
|
|
2666
|
+
async function getGitDiff(from, to = "HEAD", firstParent = false) {
|
|
2667
|
+
const range = `${from !== undefined && from !== "" ? `${from}..` : ""}${to}`;
|
|
2668
|
+
const pretty = "%x1e%s%x00%h%x00%an%x00%ae%x00%b";
|
|
2669
|
+
const flags = firstParent ? ["--first-parent"] : [];
|
|
2670
|
+
const output = await $3`git --no-pager log ${range} ${flags} --pretty=${pretty}`.quiet().text();
|
|
2671
|
+
return output.split("\x1E").slice(1).map((record) => {
|
|
2672
|
+
const [message = "", shortHash = "", authorName = "", authorEmail = "", body = ""] = record.split("\x00");
|
|
2673
|
+
return {
|
|
2674
|
+
message,
|
|
2675
|
+
shortHash,
|
|
2676
|
+
author: { name: authorName, email: authorEmail },
|
|
2677
|
+
body: body.trim()
|
|
2678
|
+
};
|
|
2679
|
+
});
|
|
2680
|
+
}
|
|
2681
|
+
function parseGitCommit(commit, config) {
|
|
2682
|
+
const match = commit.message.match(ConventionalCommitRegex);
|
|
2683
|
+
if (!match?.groups)
|
|
2684
|
+
return null;
|
|
2685
|
+
const type = (match.groups.type ?? "").toLowerCase();
|
|
2686
|
+
const breakingBody = BreakingBodyRE.exec(commit.body);
|
|
2687
|
+
const breakingNote = breakingBody?.[1]?.replaceAll(/\s+/g, " ").trim();
|
|
2688
|
+
const rawScope = match.groups.scope ?? "";
|
|
2689
|
+
const scope = Object.hasOwn(config.scopeMap, rawScope) ? config.scopeMap[rawScope] : rawScope;
|
|
2690
|
+
const isBreaking = match.groups.breaking !== undefined || breakingBody !== null;
|
|
2691
|
+
let description = match.groups.description ?? "";
|
|
2692
|
+
const references = [];
|
|
2693
|
+
for (const m of description.matchAll(PullRequestRE))
|
|
2694
|
+
references.push({ type: "pull-request", value: m[1] });
|
|
2695
|
+
for (const m of description.matchAll(IssueRE)) {
|
|
2696
|
+
if (!references.some((i) => i.value === m[1]))
|
|
2697
|
+
references.push({ type: "issue", value: m[1] });
|
|
2698
|
+
}
|
|
2699
|
+
for (const m of commit.body.matchAll(TicketLineRE)) {
|
|
2700
|
+
const known = references.find((i) => i.value === m[1]);
|
|
2701
|
+
if (known)
|
|
2702
|
+
known.title = m[2].trim();
|
|
2703
|
+
else
|
|
2704
|
+
references.push({ type: "issue", value: m[1], title: m[2].trim() });
|
|
2705
|
+
}
|
|
2706
|
+
references.push({ value: commit.shortHash, type: "hash" });
|
|
2707
|
+
description = description.replace(PullRequestRE, "").trim();
|
|
2708
|
+
const authors = [commit.author];
|
|
2709
|
+
for (const m of commit.body.matchAll(CoAuthoredByRegex)) {
|
|
2710
|
+
authors.push({
|
|
2711
|
+
name: (m.groups?.name ?? "").trim(),
|
|
2712
|
+
email: (m.groups?.email ?? "").trim()
|
|
2713
|
+
});
|
|
2714
|
+
}
|
|
2715
|
+
return {
|
|
2716
|
+
...commit,
|
|
2717
|
+
authors,
|
|
2718
|
+
description,
|
|
2719
|
+
type,
|
|
2720
|
+
scope,
|
|
2721
|
+
references,
|
|
2722
|
+
isBreaking,
|
|
2723
|
+
...breakingNote === undefined || breakingNote === "" ? {} : { breakingNote }
|
|
2724
|
+
};
|
|
2725
|
+
}
|
|
2726
|
+
|
|
2727
|
+
// src/highlights.ts
|
|
2728
|
+
import { isAbsolute as isAbsolute2, join as join8 } from "path";
|
|
2729
|
+
var fenceRE2 = /^\s*(`{3,}|~{3,})/;
|
|
2730
|
+
var headingRE2 = /^(#{1,6})(\s.*)$/;
|
|
2731
|
+
var schemeRE = /^[a-z][a-z\d+.-]*:/i;
|
|
2732
|
+
var inlineLinkRE = /(\]\(\s*<?)((?:[^\s<>()]|\([^\s<>()]*\))+)/g;
|
|
2733
|
+
var definitionRE = /^(\s{0,3}\[[^\]]+\]:\s*<?)([^\s<>]+)(>?(?:\s.*)?)$/;
|
|
2734
|
+
var newlineRE = /\r?\n/;
|
|
2735
|
+
var codeSpanRE = /(`+)[\s\S]*?\1/;
|
|
2736
|
+
function headingAnchor(text) {
|
|
2737
|
+
return text.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, "").replace(/\s/g, "-");
|
|
2738
|
+
}
|
|
2739
|
+
function resolveTarget(written, base, link) {
|
|
2740
|
+
const target = link?.(written) ?? written;
|
|
2741
|
+
if (schemeRE.test(target) || target.startsWith("//"))
|
|
2742
|
+
return target;
|
|
2743
|
+
try {
|
|
2744
|
+
return new URL(target, base).href;
|
|
2745
|
+
} catch {
|
|
2746
|
+
return target;
|
|
2747
|
+
}
|
|
2748
|
+
}
|
|
2749
|
+
function resolveLinks(line, base, link) {
|
|
2750
|
+
const definition = definitionRE.exec(line);
|
|
2751
|
+
if (definition)
|
|
2752
|
+
return `${definition[1]}${resolveTarget(definition[2], base, link)}${definition[3]}`;
|
|
2753
|
+
let rest = line;
|
|
2754
|
+
let out = "";
|
|
2755
|
+
while (rest) {
|
|
2756
|
+
const code = codeSpanRE.exec(rest);
|
|
2757
|
+
const text = code ? rest.slice(0, code.index) : rest;
|
|
2758
|
+
out += text.replace(inlineLinkRE, (_, open, target) => `${open}${resolveTarget(target, base, link)}`);
|
|
2759
|
+
if (!code)
|
|
2760
|
+
break;
|
|
2761
|
+
out += code[0];
|
|
2762
|
+
rest = rest.slice(code.index + code[0].length);
|
|
2763
|
+
}
|
|
2764
|
+
return out;
|
|
2765
|
+
}
|
|
2766
|
+
function withoutAnchor(url) {
|
|
2767
|
+
const hash = url.indexOf("#");
|
|
2768
|
+
return hash === -1 ? url : url.slice(0, hash);
|
|
2769
|
+
}
|
|
2770
|
+
function withoutFrontmatter(lines) {
|
|
2771
|
+
if (lines[0]?.trim() !== "---")
|
|
2772
|
+
return lines;
|
|
2773
|
+
const end = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
|
|
2774
|
+
return end === -1 ? lines : lines.slice(end + 1);
|
|
2775
|
+
}
|
|
2776
|
+
function parseHighlights(source, version, url, link) {
|
|
2777
|
+
const lines = withoutFrontmatter(source.split(newlineRE));
|
|
2778
|
+
const section = [];
|
|
2779
|
+
let fence;
|
|
2780
|
+
let inside = false;
|
|
2781
|
+
for (const line of lines) {
|
|
2782
|
+
const marker = fenceRE2.exec(line)?.[1];
|
|
2783
|
+
if (fence === undefined && marker === undefined) {
|
|
2784
|
+
const heading = headingRE2.exec(line);
|
|
2785
|
+
if (heading?.[1] === "##") {
|
|
2786
|
+
if (inside)
|
|
2787
|
+
break;
|
|
2788
|
+
inside = heading[2].trim() === version;
|
|
2789
|
+
continue;
|
|
2790
|
+
}
|
|
2791
|
+
if (inside && heading) {
|
|
2792
|
+
section.push(`${"#".repeat(Math.min(heading[1].length + 1, 6))}${heading[2]}`);
|
|
2793
|
+
continue;
|
|
2794
|
+
}
|
|
2795
|
+
}
|
|
2796
|
+
if (marker !== undefined)
|
|
2797
|
+
fence = fence !== undefined && marker.startsWith(fence) ? undefined : fence ?? marker;
|
|
2798
|
+
if (inside)
|
|
2799
|
+
section.push(fence !== undefined || marker !== undefined ? line : resolveLinks(line, url, link));
|
|
2800
|
+
}
|
|
2801
|
+
while (section.length && !section[0].trim())
|
|
2802
|
+
section.shift();
|
|
2803
|
+
while (section.length && !section.at(-1).trim())
|
|
2804
|
+
section.pop();
|
|
2805
|
+
return !section.length ? undefined : { lines: section, link: `${withoutAnchor(url)}#${headingAnchor(version)}` };
|
|
2806
|
+
}
|
|
2807
|
+
async function readHighlights(options, cwd = process.cwd()) {
|
|
2808
|
+
const highlights = options.highlights;
|
|
2809
|
+
if (highlights === undefined)
|
|
2810
|
+
return;
|
|
2811
|
+
const { file, url, link } = highlights;
|
|
2812
|
+
const source = Bun.file(isAbsolute2(file) ? file : join8(cwd, file));
|
|
2813
|
+
if (!await source.exists())
|
|
2814
|
+
return;
|
|
2815
|
+
return parseHighlights(await source.text(), getVersionString(options.tag, options.to), url, link);
|
|
2816
|
+
}
|
|
2817
|
+
|
|
2818
|
+
// src/parse.ts
|
|
2819
|
+
function parseCommits(commits, config) {
|
|
2820
|
+
return commits.map((commit) => parseGitCommit(commit, config)).filter(p2);
|
|
2821
|
+
}
|
|
2822
|
+
|
|
2823
|
+
// src/generate.ts
|
|
2824
|
+
async function generate(options) {
|
|
2825
|
+
const resolved = await resolveConfig(options);
|
|
2826
|
+
const rawCommits = await getGitDiff(resolved.fromRoot === true ? undefined : resolved.from, resolved.to, resolved.firstParent);
|
|
2827
|
+
const commits = parseCommits(rawCommits, resolved);
|
|
2828
|
+
const contributors = resolved.contributors ? await resolveAuthors(commits, resolved) : [];
|
|
2829
|
+
const highlights = await readHighlights(resolved);
|
|
2830
|
+
const md = generateMarkdown(commits, resolved, contributors, highlights);
|
|
2831
|
+
const discord = generateDiscordPayload(commits, resolved, contributors, highlights);
|
|
2832
|
+
return { config: resolved, md, discord, commits, contributors };
|
|
2833
|
+
}
|
|
2834
|
+
|
|
2835
|
+
// src/cli.ts
|
|
2836
|
+
async function reporting(argv, run) {
|
|
2837
|
+
const end = argv.indexOf("--");
|
|
2838
|
+
const json = (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
2839
|
+
const reports = [];
|
|
2840
|
+
const code = await stdoutToStderr(json, async () => run(argv, (value) => reports.push(value)));
|
|
2841
|
+
if (json && reports[0] !== undefined)
|
|
2842
|
+
printJson(reports[0]);
|
|
2843
|
+
return code;
|
|
2844
|
+
}
|
|
2845
|
+
function failed(e, debug) {
|
|
2846
|
+
if (e instanceof Exit)
|
|
2847
|
+
throw e;
|
|
2848
|
+
if (debug === true && e instanceof Error && e.stack !== undefined)
|
|
2849
|
+
console.error(err().dim(e.stack.split(`
|
|
2850
|
+
`).slice(1).join(`
|
|
2851
|
+
`)));
|
|
2852
|
+
return fail(e instanceof Error ? e.message : String(e), 1);
|
|
2853
|
+
}
|
|
2854
|
+
async function ask2(question) {
|
|
2855
|
+
return await confirm(question, { default: false, hint: "pass --yes to skip the questions" }) === true;
|
|
2856
|
+
}
|
|
2857
|
+
async function printManualRelease(config, md, heading) {
|
|
2858
|
+
const file = join9(tmpdir(), `changelog-${config.to.replaceAll("/", "-")}.md`);
|
|
2859
|
+
await Bun.write(file, md);
|
|
2860
|
+
console.log();
|
|
2861
|
+
console.error(err().yellow(heading));
|
|
2862
|
+
console.error(err().yellow(` https://${config.baseUrl}/${config.releaseRepo}/releases/new?tag=${encodeURIComponent(config.to)}`));
|
|
2863
|
+
console.error(err().yellow(` pasting the notes saved to ${file}`));
|
|
2864
|
+
console.log();
|
|
2865
|
+
}
|
|
2866
|
+
var RELEASE_EXITS = [[0, "it released, wrote --output or showed --dry-run"], [1, "the release could not be made (no token, the tag not on the forge, a shallow clone, an API error), an asset upload or the Discord post failed"], [2, "a usage error"]];
|
|
2867
|
+
async function release(argv, report) {
|
|
2868
|
+
const parsed = parse(argv, `usage: changelog release [options]
|
|
2869
|
+
|
|
2870
|
+
--json prints {command, status (released, dry-run or saved), from, to, commits, notes, url, output, assetsFailed, discord (posted, failed or null)} on stdout and the progress on stderr; a failure is {error} on stderr.`, shared, { allowNegative: true, positionals: [], exits: RELEASE_EXITS });
|
|
2871
|
+
const options = withToken(toOptions(parsed.values));
|
|
2872
|
+
let generated;
|
|
2873
|
+
let code = 0;
|
|
2874
|
+
try {
|
|
2875
|
+
console.log();
|
|
2876
|
+
console.log(out().dim(`changelog v${version}`));
|
|
2877
|
+
const { config, md, discord, commits } = await generate(options);
|
|
2878
|
+
const result = { command: "release", status: "released", from: config.from, to: config.to, commits: commits.length, notes: md, url: null, output: null, assetsFailed: 0, discord: null };
|
|
2879
|
+
generated = { config, md };
|
|
2880
|
+
console.log(role("accent", process.stdout)(config.from) + out().dim(" -> ") + role("path", process.stdout)(config.to) + out().dim(` (${commits.length} commits)`));
|
|
2881
|
+
console.log(out().dim("--------------"));
|
|
2882
|
+
console.log();
|
|
2883
|
+
console.log(md.replace(/ /g, ""));
|
|
2884
|
+
console.log();
|
|
2885
|
+
console.log(out().dim("--------------"));
|
|
2886
|
+
if (config.dry) {
|
|
2887
|
+
console.log(out().yellow(config.discordWebhook ? "Dry run. Release and Discord post skipped." : "Dry run. Release skipped."));
|
|
2888
|
+
await printManualRelease(config, md, "Create it manually at");
|
|
2889
|
+
report({ ...result, status: "dry-run" });
|
|
2890
|
+
return 0;
|
|
2891
|
+
}
|
|
2892
|
+
if (typeof config.output === "string") {
|
|
2893
|
+
await Bun.write(config.output, md);
|
|
2894
|
+
console.log(out().yellow(`Saved to ${config.output}`));
|
|
2895
|
+
report({ ...result, status: "saved", output: config.output });
|
|
2896
|
+
return 0;
|
|
2897
|
+
}
|
|
2898
|
+
if (!config.token) {
|
|
2899
|
+
await printManualRelease(config, md, "Create it manually at");
|
|
2900
|
+
fail(`no ${forgeName(config)} token found, pass --token or set GITHUB_TOKEN${config.provider === "github" ? ", or log in with gh auth login" : ""}, release skipped`, 1);
|
|
2901
|
+
}
|
|
2902
|
+
if (!await hasTagOnGitea(config.to, config)) {
|
|
2903
|
+
await printManualRelease(config, md, "Create it manually at");
|
|
2904
|
+
fail(`the ref "${config.to}" is not available as a tag on ${forgeName(config)}, release skipped`, 1);
|
|
2905
|
+
}
|
|
2906
|
+
if (!commits.length && await isRepoShallow()) {
|
|
2907
|
+
await printManualRelease(config, md, "Create it manually at");
|
|
2908
|
+
fail("the repo seems to be cloned shallowly, which makes changelog fail to generate, specify `fetch-depth: 0` in your CI config", 1);
|
|
2909
|
+
}
|
|
2910
|
+
result.url = await sendRelease(config, md);
|
|
2911
|
+
if (config.assets?.length) {
|
|
2912
|
+
result.assetsFailed = await uploadAssets(config, config.assets);
|
|
2913
|
+
if (result.assetsFailed > 0)
|
|
2914
|
+
code = 1;
|
|
2915
|
+
}
|
|
2916
|
+
if (config.discordWebhook) {
|
|
2917
|
+
try {
|
|
2918
|
+
await cr(config.discordWebhook, discord);
|
|
2919
|
+
console.log(out().green("Posted to Discord"));
|
|
2920
|
+
result.discord = "posted";
|
|
2921
|
+
} catch (e) {
|
|
2922
|
+
console.error(err().red(`Released, but the Discord post failed: ${String(e)}`));
|
|
2923
|
+
result.discord = "failed";
|
|
2924
|
+
code = 1;
|
|
2925
|
+
}
|
|
2926
|
+
}
|
|
2927
|
+
report(result);
|
|
2928
|
+
return code;
|
|
2929
|
+
} catch (e) {
|
|
2930
|
+
if (generated && !(e instanceof Exit))
|
|
2931
|
+
await printManualRelease(generated.config, generated.md, "Failed to create the release. Create it manually at");
|
|
2932
|
+
return failed(e, parsed.values.debug);
|
|
2933
|
+
}
|
|
2934
|
+
}
|
|
2935
|
+
var UNDO_EXITS = [[0, "it undid it, had nothing to undo, ran --dry-run or the question was declined"], [1, "a step fails"], [2, "a usage error"]];
|
|
2936
|
+
async function undo(argv, report) {
|
|
2937
|
+
const { values: args, positionals } = parse(argv, `usage: changelog undo [tag] [options]
|
|
2938
|
+
|
|
2939
|
+
--json prints {command, status (undone, nothing, dry-run or declined), tag, releaseNote, remoteTag, localTag, commitReset: {hash, subject} or null} on stdout and the progress on stderr, each flag true when that step is (or, on a dry run, would be) taken. It asks no question: the release note is deleted with --note only, and anything to remove needs --yes or --dry-run (exit 2 otherwise).`, undoFlags, { positionals: ["[tag]"], exits: UNDO_EXITS });
|
|
2940
|
+
const json = args.json === true;
|
|
2941
|
+
let tag = positionals[0];
|
|
2942
|
+
const options = withToken(toOptions(args));
|
|
2943
|
+
try {
|
|
2944
|
+
console.log();
|
|
2945
|
+
console.log(out().dim(`changelog v${version}`));
|
|
2946
|
+
if (tag === undefined || tag === "") {
|
|
2947
|
+
tag = (await getGitTags())[0];
|
|
2948
|
+
if (tag === undefined) {
|
|
2949
|
+
console.log(out().yellow("No tags found, nothing to undo."));
|
|
2950
|
+
report({ command: "undo", status: "nothing", tag: null, releaseNote: false, remoteTag: false, localTag: false, commitReset: null });
|
|
2951
|
+
return 0;
|
|
2952
|
+
}
|
|
2953
|
+
console.log(out().yellow(`No tag specified, using the latest tag "${out().bold(tag)}".`));
|
|
2954
|
+
}
|
|
2955
|
+
const config = await resolveConfig({ ...options, to: tag });
|
|
2956
|
+
let originRepo;
|
|
2957
|
+
try {
|
|
2958
|
+
originRepo = await getGiteaRepo();
|
|
2959
|
+
} catch {}
|
|
2960
|
+
const remoteViaGit = Boolean(originRepo) && String(config.releaseRepo) === originRepo;
|
|
2961
|
+
const release = config.token ? await getRelease(config, tag) : null;
|
|
2962
|
+
const remoteTag = remoteViaGit ? await hasRemoteGitTag(tag) : Boolean(config.token) && await hasRemoteTag(config, tag);
|
|
2963
|
+
const localTag = await isRefGitTag(tag);
|
|
2964
|
+
let commitToReset;
|
|
2965
|
+
if (localTag && await getTagCommit(tag) === await getHeadCommit()) {
|
|
2966
|
+
commitToReset = { hash: await getHeadCommit(), subject: await getCommitSubject("HEAD") };
|
|
2967
|
+
}
|
|
2968
|
+
const deleteNote = release !== null && (args.note === true || !json && shouldAskNote({ release, note: args.note, yes: args.yes, dry: args["dry-run"] }) && await ask2(`Also delete the ${forgeName(config)} release note "${release.name || tag}"?`));
|
|
2969
|
+
const actions = [];
|
|
2970
|
+
if (deleteNote)
|
|
2971
|
+
actions.push(`${out().red("release note")} ${tag}`);
|
|
2972
|
+
if (remoteTag)
|
|
2973
|
+
actions.push(`${out().red("remote tag")} ${tag}`);
|
|
2974
|
+
if (localTag)
|
|
2975
|
+
actions.push(`${out().red("local tag")} ${tag}`);
|
|
2976
|
+
if (commitToReset)
|
|
2977
|
+
actions.push(`${out().red("commit")} reset --soft (${commitToReset.hash.slice(0, 7)} "${commitToReset.subject}")`);
|
|
2978
|
+
else if (localTag)
|
|
2979
|
+
actions.push(out().dim(`commit skipped (${tag} is not HEAD)`));
|
|
2980
|
+
const result = { command: "undo", status: "undone", tag, releaseNote: deleteNote, remoteTag, localTag, commitReset: commitToReset === undefined ? null : { hash: commitToReset.hash, subject: commitToReset.subject } };
|
|
2981
|
+
if (!actions.length) {
|
|
2982
|
+
console.log(out().yellow(`Nothing to undo for "${tag}".`));
|
|
2983
|
+
report({ ...result, status: "nothing" });
|
|
2984
|
+
return 0;
|
|
2985
|
+
}
|
|
2986
|
+
if (json && args.yes !== true && args["dry-run"] !== true)
|
|
2987
|
+
fail("--json asks no question, so removing needs --yes (or --dry-run to preview)");
|
|
2988
|
+
console.log();
|
|
2989
|
+
console.log(`About to remove on ${out().bold(String(config.releaseRepo))}:`);
|
|
2990
|
+
for (const action of actions)
|
|
2991
|
+
console.log(` - ${action}`);
|
|
2992
|
+
console.log();
|
|
2993
|
+
if (args["dry-run"]) {
|
|
2994
|
+
console.log(out().yellow("Dry run. Nothing removed."));
|
|
2995
|
+
report({ ...result, status: "dry-run" });
|
|
2996
|
+
return 0;
|
|
2997
|
+
}
|
|
2998
|
+
if (!args.yes && !await ask2("Proceed?")) {
|
|
2999
|
+
console.log(out().yellow("Aborted."));
|
|
3000
|
+
report({ ...result, status: "declined", releaseNote: false, remoteTag: false, localTag: false, commitReset: null });
|
|
3001
|
+
return 0;
|
|
3002
|
+
}
|
|
3003
|
+
if (deleteNote) {
|
|
3004
|
+
await deleteRelease(config, release.id);
|
|
3005
|
+
console.log(out().green(`Deleted release note ${tag}`));
|
|
3006
|
+
}
|
|
3007
|
+
if (remoteTag) {
|
|
3008
|
+
if (remoteViaGit)
|
|
3009
|
+
await deleteRemoteGitTag(tag);
|
|
3010
|
+
else
|
|
3011
|
+
await deleteRemoteTag(config, tag);
|
|
3012
|
+
console.log(out().green(`Deleted remote tag ${tag}`));
|
|
3013
|
+
}
|
|
3014
|
+
if (localTag) {
|
|
3015
|
+
await deleteLocalTag(tag);
|
|
3016
|
+
console.log(out().green(`Deleted local tag ${tag}`));
|
|
3017
|
+
}
|
|
3018
|
+
if (commitToReset) {
|
|
3019
|
+
await softResetLastCommit();
|
|
3020
|
+
console.log(out().green(`Reset commit ${commitToReset.hash.slice(0, 7)} (changes kept in working tree)`));
|
|
3021
|
+
}
|
|
3022
|
+
report(result);
|
|
3023
|
+
return 0;
|
|
3024
|
+
} catch (e) {
|
|
3025
|
+
return failed(e, args.debug);
|
|
3026
|
+
}
|
|
3027
|
+
}
|
|
3028
|
+
process.exitCode = await runCli({
|
|
3029
|
+
name: "changelog",
|
|
3030
|
+
about: "generate the release notes and publish them",
|
|
3031
|
+
replaces: "writing the release notes by hand and posting them through the Forgejo or GitHub UI",
|
|
3032
|
+
examples: [["changelog --dry-run", "the notes since the last tag, nothing published"], ["changelog undo v1.2.0 --dry-run", "what undoing that release would remove"]],
|
|
3033
|
+
commands: {
|
|
3034
|
+
release: { summary: "generate the release notes and publish them (the default)", run: async (argv) => reporting(aliasFlags(argv), release) },
|
|
3035
|
+
undo: { summary: "undo a release: delete the remote/local tag and reset the bump commit", run: async (argv) => reporting(aliasFlags(argv), undo) }
|
|
3036
|
+
},
|
|
3037
|
+
defaultCommand: "release"
|
|
3038
|
+
});
|