@kaynooo/cli-edit 0.0.0-stage → 0.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 +35 -2
- package/dist/cli.js +1145 -0
- package/package.json +39 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kaynooo <contact@kaynooo.fr>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,36 @@
|
|
|
1
|
-
#
|
|
1
|
+
# sub
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Replaces text in files for Claude Code, where a session would otherwise retype a `sed -i`, a `bun -e` editor or a python heredoc: `sub` writes nothing unless every replacement matched as often as expected, and says where it did.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
bun install -g @kaynooo/cli-edit
|
|
7
|
+
sub --from 'a.b(1)' --to 'a.c(2)' src/a.ts
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Multi-line text goes in SEARCH/REPLACE blocks on stdin, from a quoted heredoc that needs no escaping:
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
sub src/a.php <<'EOF'
|
|
14
|
+
<<<<<<< SEARCH
|
|
15
|
+
old lines
|
|
16
|
+
=======
|
|
17
|
+
new lines
|
|
18
|
+
>>>>>>> REPLACE
|
|
19
|
+
EOF
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Behaviour
|
|
23
|
+
|
|
24
|
+
- `--from` is taken literally (`$`, `.`, `(` included) and must match exactly once per file; `--count N` expects N matches, `--all` replaces every match and expects at least one.
|
|
25
|
+
- `--to ''` deletes the match. A value starting with a dash goes as `--from=-x`.
|
|
26
|
+
- Several files at once (the shell's globs, or `rg -l X | xargs sub ...`): each is checked on its own, and one failing file leaves every file untouched.
|
|
27
|
+
- On a failure nothing is written, stderr lists each file and pair that failed, with the lines matched or, for a multiline `--from` found nowhere, the lines its first line is on (usually an indentation mismatch), and the exit code is 1.
|
|
28
|
+
- `--regex` makes `--from` a regular expression (`^` and `$` match each line), `--to` taking `$1` and `$<name>`, or `${1}` and `${name}` when digits or letters follow the reference.
|
|
29
|
+
- Without `--from`, `--to` or `--pairs`, `sub` reads SEARCH/REPLACE blocks on stdin and applies them in order, each on the previous one's result, all or nothing, each checked like a `--from` (once, or as `--count`/`--all` say; `--regex` makes every SEARCH a regular expression). The text between the markers is taken as is, joined by newlines with none after the last line, so a SEARCH ending in a line break takes an empty line before `=======`. An empty REPLACE deletes the SEARCH text; to drop whole lines, put the neighbouring line in both.
|
|
30
|
+
- A line naming a file before a block makes it apply to that file alone, so one call edits several files and needs no file argument; a block without one applies to the file arguments. A file listed but named by no block and given no file-less block is refused.
|
|
31
|
+
- When the text holds a marker line itself (a Markdown `=======` underline), open with more characters, `<<<<<<<<<< SEARCH`, and divide and close with as many `=` and `>`.
|
|
32
|
+
- `--pairs <json|file>` (or `-` for stdin) applies a JSON array of `{ "from", "to", "count"?, "all"?, "regex"? }` in order, each on the previous one's result, all or nothing; a value starting with `[` is the JSON itself, any other key in a pair is refused. `--count`, `--all` and `--regex` are the defaults of pairs that do not set them.
|
|
33
|
+
- A file with CRLF endings matches a literal `--from` typed with plain newlines, and the replacement keeps CRLF.
|
|
34
|
+
- Each written file prints `<path>: N replacements on lines L, +added -removed`; `--diff` adds its unified diff (through the system's `diff`), `--dry-run` shows the same without writing.
|
|
35
|
+
- The file is rewritten in place, so its mode, owner and missing trailing newline stay.
|
|
36
|
+
- Exit codes: 0 written, 1 a replacement did not match as expected, 2 a usage error.
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1145 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
|
|
4
|
+
// src/cli.ts
|
|
5
|
+
import { accessSync, chmodSync, constants, existsSync, readFileSync, realpathSync, renameSync, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
|
|
6
|
+
import { normalize, resolve } from "path";
|
|
7
|
+
import process8 from "process";
|
|
8
|
+
|
|
9
|
+
// ../kit/src/args.ts
|
|
10
|
+
import process4 from "process";
|
|
11
|
+
import { parseArgs } from "util";
|
|
12
|
+
|
|
13
|
+
// ../kit/src/style.ts
|
|
14
|
+
import process from "process";
|
|
15
|
+
|
|
16
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
17
|
+
function x(s) {
|
|
18
|
+
let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
|
|
19
|
+
if (!/^[a-f0-9]+$/.test(r))
|
|
20
|
+
return [0, 0, 0];
|
|
21
|
+
let t = r.length, n = (c) => Number.parseInt(c, 16);
|
|
22
|
+
if (t === 3 || t === 4) {
|
|
23
|
+
let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
|
|
24
|
+
return g !== undefined ? [c, u, h, g] : [c, u, h];
|
|
25
|
+
}
|
|
26
|
+
if (t !== 6 && t !== 8)
|
|
27
|
+
throw Error(`Invalid hex color length: ${t}`);
|
|
28
|
+
let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
|
|
29
|
+
if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
|
|
30
|
+
throw Error(`Invalid hex color value: ${s}`);
|
|
31
|
+
return y !== undefined ? [a, b, o, y] : [a, b, o];
|
|
32
|
+
}
|
|
33
|
+
function A(s) {
|
|
34
|
+
let [r, t, n, a] = s;
|
|
35
|
+
if (a)
|
|
36
|
+
return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
|
|
37
|
+
return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
|
|
38
|
+
}
|
|
39
|
+
function R(s, r, t) {
|
|
40
|
+
s = (s % 360 + 360) % 360, t /= 100;
|
|
41
|
+
let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
|
|
42
|
+
let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
|
|
43
|
+
return Math.round(255 * y);
|
|
44
|
+
};
|
|
45
|
+
return [a(0), a(8), a(4)];
|
|
46
|
+
}
|
|
47
|
+
function k(s) {
|
|
48
|
+
let [r, t, n] = s;
|
|
49
|
+
r /= 255, t /= 255, n /= 255;
|
|
50
|
+
let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
|
|
51
|
+
if (a !== b) {
|
|
52
|
+
let u = a - b;
|
|
53
|
+
if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
|
|
54
|
+
o = (t - n) / u + (t < n ? 6 : 0);
|
|
55
|
+
else if (a === t)
|
|
56
|
+
o = (n - r) / u + 2;
|
|
57
|
+
else
|
|
58
|
+
o = (r - t) / u + 4;
|
|
59
|
+
o /= 6;
|
|
60
|
+
}
|
|
61
|
+
return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
|
|
62
|
+
}
|
|
63
|
+
function H(s, r, t) {
|
|
64
|
+
s = (s % 360 + 360) % 360, r /= 100, t /= 100;
|
|
65
|
+
let n = (a) => {
|
|
66
|
+
let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
|
|
67
|
+
return Math.round(255 * o);
|
|
68
|
+
};
|
|
69
|
+
return [n(5), n(3), n(1)];
|
|
70
|
+
}
|
|
71
|
+
function f(s) {
|
|
72
|
+
let [r, t, n] = s;
|
|
73
|
+
r /= 255, t /= 255, n /= 255;
|
|
74
|
+
let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
|
|
75
|
+
if (o !== 0) {
|
|
76
|
+
if (a === r)
|
|
77
|
+
y = (t - n) / o + (t < n ? 6 : 0);
|
|
78
|
+
else if (a === t)
|
|
79
|
+
y = (n - r) / o + 2;
|
|
80
|
+
else
|
|
81
|
+
y = (r - t) / o + 4;
|
|
82
|
+
y /= 6;
|
|
83
|
+
}
|
|
84
|
+
return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
|
|
85
|
+
}
|
|
86
|
+
function O(s) {
|
|
87
|
+
let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
|
|
88
|
+
if (a === 1)
|
|
89
|
+
return [0, 0, 0, 100];
|
|
90
|
+
let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
|
|
91
|
+
return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
|
|
92
|
+
}
|
|
93
|
+
function v(s, r, t, n) {
|
|
94
|
+
return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
|
|
95
|
+
}
|
|
96
|
+
var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
|
97
|
+
var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
|
|
98
|
+
var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
|
|
99
|
+
function T(s) {
|
|
100
|
+
let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
|
|
101
|
+
return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
|
|
102
|
+
}
|
|
103
|
+
function M(s, r, t) {
|
|
104
|
+
let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
|
|
105
|
+
return [u(o), u(y), u(c)];
|
|
106
|
+
}
|
|
107
|
+
function d(s) {
|
|
108
|
+
let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
|
|
109
|
+
return [i(r, 4), i(a, 4), i(b, 2)];
|
|
110
|
+
}
|
|
111
|
+
function C(s, r, t) {
|
|
112
|
+
let n = t * Math.PI / 180;
|
|
113
|
+
return M(s, r * Math.cos(n), r * Math.sin(n));
|
|
114
|
+
}
|
|
115
|
+
function l(s) {
|
|
116
|
+
let r = s / 255;
|
|
117
|
+
return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
class e {
|
|
121
|
+
r;
|
|
122
|
+
g;
|
|
123
|
+
b;
|
|
124
|
+
a;
|
|
125
|
+
constructor(s, r, t, n = 1) {
|
|
126
|
+
this.r = s, this.g = r, this.b = t, this.a = n;
|
|
127
|
+
}
|
|
128
|
+
static from(s, r) {
|
|
129
|
+
if (s === "hex") {
|
|
130
|
+
let [t, n, a, b] = x(r);
|
|
131
|
+
return new e(t, n, a, b);
|
|
132
|
+
}
|
|
133
|
+
if (s === "rgb") {
|
|
134
|
+
if (Array.isArray(r)) {
|
|
135
|
+
let [o, y, c, u] = r;
|
|
136
|
+
return new e(o, y, c, u);
|
|
137
|
+
}
|
|
138
|
+
let { r: t, g: n, b: a, a: b } = r;
|
|
139
|
+
return new e(t, n, a, b);
|
|
140
|
+
}
|
|
141
|
+
if (s === "hsl") {
|
|
142
|
+
let t, n, a, b;
|
|
143
|
+
if (Array.isArray(r))
|
|
144
|
+
[t, n, a, b] = r;
|
|
145
|
+
else
|
|
146
|
+
({ h: t, s: n, l: a, a: b } = r);
|
|
147
|
+
let [o, y, c] = R(t, n, a);
|
|
148
|
+
return new e(o, y, c, b);
|
|
149
|
+
}
|
|
150
|
+
if (s === "hsv") {
|
|
151
|
+
let t, n, a, b;
|
|
152
|
+
if (Array.isArray(r))
|
|
153
|
+
[t, n, a, b] = r;
|
|
154
|
+
else
|
|
155
|
+
({ h: t, s: n, v: a, a: b } = r);
|
|
156
|
+
let [o, y, c] = H(t, n, a);
|
|
157
|
+
return new e(o, y, c, b);
|
|
158
|
+
}
|
|
159
|
+
if (s === "cmyk") {
|
|
160
|
+
let t, n, a, b, o;
|
|
161
|
+
if (Array.isArray(r))
|
|
162
|
+
[t, n, a, b, o] = r;
|
|
163
|
+
else
|
|
164
|
+
({ c: t, m: n, y: a, k: b, a: o } = r);
|
|
165
|
+
let [y, c, u] = v(t, n, a, b);
|
|
166
|
+
return new e(y, c, u, o);
|
|
167
|
+
}
|
|
168
|
+
if (s === "oklch") {
|
|
169
|
+
let t, n, a, b;
|
|
170
|
+
if (Array.isArray(r))
|
|
171
|
+
[t, n, a, b] = r;
|
|
172
|
+
else
|
|
173
|
+
({ l: t, c: n, h: a, a: b } = r);
|
|
174
|
+
let [o, y, c] = C(t, n, a);
|
|
175
|
+
return new e(o, y, c, b);
|
|
176
|
+
}
|
|
177
|
+
if (s === "oklab") {
|
|
178
|
+
let t, n, a, b;
|
|
179
|
+
if (Array.isArray(r))
|
|
180
|
+
[t, n, a, b] = r;
|
|
181
|
+
else
|
|
182
|
+
({ l: t, a: n, b: a, alpha: b } = r);
|
|
183
|
+
let [o, y, c] = M(t, n, a);
|
|
184
|
+
return new e(o, y, c, b);
|
|
185
|
+
}
|
|
186
|
+
throw Error("Invalid input");
|
|
187
|
+
}
|
|
188
|
+
to(s) {
|
|
189
|
+
switch (s) {
|
|
190
|
+
case "rgb":
|
|
191
|
+
return [this.r, this.g, this.b];
|
|
192
|
+
case "rgba":
|
|
193
|
+
return [this.r, this.g, this.b, this.a];
|
|
194
|
+
case "hex":
|
|
195
|
+
return A([this.r, this.g, this.b]);
|
|
196
|
+
case "hexa":
|
|
197
|
+
return A([this.r, this.g, this.b, this.a]);
|
|
198
|
+
case "hsl":
|
|
199
|
+
return k([this.r, this.g, this.b]);
|
|
200
|
+
case "hsla":
|
|
201
|
+
return [...k([this.r, this.g, this.b]), this.a];
|
|
202
|
+
case "hsv":
|
|
203
|
+
return f([this.r, this.g, this.b]);
|
|
204
|
+
case "hsva":
|
|
205
|
+
return [...f([this.r, this.g, this.b]), this.a];
|
|
206
|
+
case "cmyk":
|
|
207
|
+
return O([this.r, this.g, this.b]);
|
|
208
|
+
case "cmyka":
|
|
209
|
+
return [...O([this.r, this.g, this.b]), this.a];
|
|
210
|
+
case "oklch":
|
|
211
|
+
return d([this.r, this.g, this.b]);
|
|
212
|
+
case "oklcha":
|
|
213
|
+
return [...d([this.r, this.g, this.b]), this.a];
|
|
214
|
+
case "oklab":
|
|
215
|
+
return T([this.r, this.g, this.b]);
|
|
216
|
+
case "oklaba":
|
|
217
|
+
return [...T([this.r, this.g, this.b]), this.a];
|
|
218
|
+
default:
|
|
219
|
+
return [this.r, this.g, this.b];
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
getLuminance() {
|
|
223
|
+
let s = l(this.r), r = l(this.g), t = l(this.b);
|
|
224
|
+
return 0.2126 * s + 0.7152 * r + 0.0722 * t;
|
|
225
|
+
}
|
|
226
|
+
contrastRatio(s) {
|
|
227
|
+
let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
|
|
228
|
+
return (n + 0.05) / (a + 0.05);
|
|
229
|
+
}
|
|
230
|
+
bestContrastForeground() {
|
|
231
|
+
let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
|
|
232
|
+
return t >= n ? s : r;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
|
|
237
|
+
var r = 39;
|
|
238
|
+
var o = 49;
|
|
239
|
+
var f2 = "\x1B[";
|
|
240
|
+
var C2 = { 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, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
|
|
241
|
+
let [a, l, s] = e.from("hex", i).to("rgb");
|
|
242
|
+
return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
|
|
243
|
+
}, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
|
|
244
|
+
var b = new Set(["", "1", "2", "3", "true"]);
|
|
245
|
+
function h(i, n = globalThis.process?.env ?? {}) {
|
|
246
|
+
if (n.FORCE_COLOR !== undefined)
|
|
247
|
+
return b.has(n.FORCE_COLOR);
|
|
248
|
+
if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
|
|
249
|
+
return false;
|
|
250
|
+
return i?.isTTY === true;
|
|
251
|
+
}
|
|
252
|
+
function d2(i, n, a) {
|
|
253
|
+
if (!h(a.stream ?? globalThis.process?.stdout, a.env))
|
|
254
|
+
return n;
|
|
255
|
+
let l = "", s = "";
|
|
256
|
+
for (let g = 0, y = i.length;g < y; g++) {
|
|
257
|
+
let [c, p] = i[g];
|
|
258
|
+
l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
|
|
259
|
+
}
|
|
260
|
+
return l + n + s;
|
|
261
|
+
}
|
|
262
|
+
function u(i, n = []) {
|
|
263
|
+
return new Proxy((l) => d2(n, l, i), { get(l, s) {
|
|
264
|
+
let g = C2[s];
|
|
265
|
+
if (Array.isArray(g))
|
|
266
|
+
return u(i, [...n, g]);
|
|
267
|
+
if (typeof g === "function")
|
|
268
|
+
return (...y) => u(i, [...n, g(...y)]);
|
|
269
|
+
throw Error(`Unknown style: ${String(s)}`);
|
|
270
|
+
} });
|
|
271
|
+
}
|
|
272
|
+
function le(i = {}) {
|
|
273
|
+
return u(i);
|
|
274
|
+
}
|
|
275
|
+
var t = le();
|
|
276
|
+
|
|
277
|
+
// ../kit/src/style.ts
|
|
278
|
+
function takesControlCodes(stream, env = process.env) {
|
|
279
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
|
|
280
|
+
}
|
|
281
|
+
function paint(stream, env = process.env) {
|
|
282
|
+
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
283
|
+
}
|
|
284
|
+
var STATUSES = {
|
|
285
|
+
passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
|
|
286
|
+
failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
|
|
287
|
+
running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
|
|
288
|
+
queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
|
|
289
|
+
skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
|
|
290
|
+
};
|
|
291
|
+
var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
|
|
292
|
+
|
|
293
|
+
// ../kit/src/format.ts
|
|
294
|
+
function upTo(text, separator) {
|
|
295
|
+
const end = text.indexOf(separator);
|
|
296
|
+
return end === -1 ? text : text.slice(0, end);
|
|
297
|
+
}
|
|
298
|
+
var ESCAPE = String.fromCharCode(27);
|
|
299
|
+
|
|
300
|
+
// ../kit/src/help.ts
|
|
301
|
+
import process2 from "process";
|
|
302
|
+
var OPTIONAL = /\[[^\]]+\]/g;
|
|
303
|
+
var USAGE_PREFIX = /^usage:\s*/i;
|
|
304
|
+
var FULL_STOP = /\.$/;
|
|
305
|
+
function usageLine(usage, colors = paint(process2.stdout)) {
|
|
306
|
+
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
307
|
+
}
|
|
308
|
+
function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
|
|
309
|
+
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
|
|
310
|
+
`);
|
|
311
|
+
}
|
|
312
|
+
function replacesRows(replaces, colors = paint(process2.stdout)) {
|
|
313
|
+
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
314
|
+
}
|
|
315
|
+
function wantsHelpJson(env = process2.env) {
|
|
316
|
+
return env.KIT_HELP === "json";
|
|
317
|
+
}
|
|
318
|
+
function description(usage, { examples = [], replaces } = {}) {
|
|
319
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
320
|
+
`);
|
|
321
|
+
const first = lines[0];
|
|
322
|
+
const colon = first.indexOf(": ");
|
|
323
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
324
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
325
|
+
return {
|
|
326
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
327
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
328
|
+
...replaces === undefined ? {} : { replaces },
|
|
329
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
function exampleRows(examples, colors = paint(process2.stdout)) {
|
|
333
|
+
if (examples.length === 0)
|
|
334
|
+
return [];
|
|
335
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
336
|
+
}
|
|
337
|
+
function optionRows(options, colors = paint(process2.stdout)) {
|
|
338
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
339
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
340
|
+
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
341
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
342
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
343
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
|
|
344
|
+
});
|
|
345
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
346
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// ../kit/src/text.ts
|
|
350
|
+
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
351
|
+
function distance(a, b) {
|
|
352
|
+
let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
|
|
353
|
+
for (const [i, left] of [...a].entries()) {
|
|
354
|
+
const current = [i + 1];
|
|
355
|
+
for (const [j, right] of [...b].entries())
|
|
356
|
+
current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
|
|
357
|
+
previous = current;
|
|
358
|
+
}
|
|
359
|
+
return previous[b.length] ?? 0;
|
|
360
|
+
}
|
|
361
|
+
function closest(name, names) {
|
|
362
|
+
const started = names.find((known) => known.startsWith(name));
|
|
363
|
+
if (started !== undefined)
|
|
364
|
+
return started;
|
|
365
|
+
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
366
|
+
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
367
|
+
}
|
|
368
|
+
// ../kit/src/input.ts
|
|
369
|
+
import process3 from "process";
|
|
370
|
+
var WHOLE = /^\d+$/;
|
|
371
|
+
function wholeNumber(value, name, fallback, min = 1) {
|
|
372
|
+
if (value === undefined)
|
|
373
|
+
return fallback;
|
|
374
|
+
const number = Number(value);
|
|
375
|
+
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
376
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
377
|
+
return number;
|
|
378
|
+
}
|
|
379
|
+
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
380
|
+
if (path === "-") {
|
|
381
|
+
if (process3.stdin.isTTY)
|
|
382
|
+
fail(noStdin);
|
|
383
|
+
return Bun.stdin.text();
|
|
384
|
+
}
|
|
385
|
+
const file = Bun.file(path);
|
|
386
|
+
if (!await file.exists())
|
|
387
|
+
fail(`no file ${path}`);
|
|
388
|
+
return file.text();
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// ../kit/src/args.ts
|
|
392
|
+
var DASHES = /^-+/;
|
|
393
|
+
class Exit extends Error {
|
|
394
|
+
code;
|
|
395
|
+
hint;
|
|
396
|
+
constructor(message, code, hint) {
|
|
397
|
+
super(message);
|
|
398
|
+
this.code = code;
|
|
399
|
+
this.hint = hint;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
function fail(message, code = 2, hint) {
|
|
403
|
+
throw new Exit(message, code, hint);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
class UsageError extends Exit {
|
|
407
|
+
constructor(message, hint) {
|
|
408
|
+
super(message, 2, hint);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
function badUsage(message) {
|
|
412
|
+
throw new UsageError(message);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
class HelpShown extends Exit {
|
|
416
|
+
constructor() {
|
|
417
|
+
super("help shown", 0);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
class Completing {
|
|
422
|
+
options;
|
|
423
|
+
positionals;
|
|
424
|
+
candidates;
|
|
425
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
426
|
+
this.options = options;
|
|
427
|
+
this.positionals = positionals;
|
|
428
|
+
this.candidates = candidates;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
var completion = { active: false };
|
|
432
|
+
var OUTPUT_OPTIONS = {
|
|
433
|
+
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
434
|
+
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
435
|
+
};
|
|
436
|
+
function applyOutput(color, plain, env = process4.env) {
|
|
437
|
+
const when = plain === true ? "never" : color ?? "auto";
|
|
438
|
+
if (when === "auto")
|
|
439
|
+
return;
|
|
440
|
+
if (when !== "always" && when !== "never")
|
|
441
|
+
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
442
|
+
if (when === "always") {
|
|
443
|
+
env.FORCE_COLOR = "1";
|
|
444
|
+
delete env.NO_COLOR;
|
|
445
|
+
} else {
|
|
446
|
+
env.NO_COLOR = "1";
|
|
447
|
+
delete env.FORCE_COLOR;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
function parse(args, usage, options, settings = {}) {
|
|
451
|
+
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
452
|
+
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
453
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
454
|
+
if (completion.active)
|
|
455
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
456
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
457
|
+
let parsed;
|
|
458
|
+
try {
|
|
459
|
+
parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
460
|
+
} catch (error) {
|
|
461
|
+
const message = parseError(error);
|
|
462
|
+
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
463
|
+
}
|
|
464
|
+
const values = parsed.values;
|
|
465
|
+
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
466
|
+
if (values.help === true) {
|
|
467
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
|
|
468
|
+
throw new HelpShown;
|
|
469
|
+
}
|
|
470
|
+
checkChoices(parsed.values, all);
|
|
471
|
+
checkConflicts(parsed.values, all);
|
|
472
|
+
if (settings.positionals !== undefined)
|
|
473
|
+
checkPositionals(parsed.positionals, settings.positionals);
|
|
474
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
475
|
+
}
|
|
476
|
+
function splitRest(args, passes) {
|
|
477
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
478
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
479
|
+
}
|
|
480
|
+
function splitTrailing(args, options, count) {
|
|
481
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
482
|
+
let seen = 0;
|
|
483
|
+
if (count === 0)
|
|
484
|
+
return { own: args, rest: undefined };
|
|
485
|
+
for (let at = 0;at < args.length; at++) {
|
|
486
|
+
const word = args[at];
|
|
487
|
+
if (word === "--")
|
|
488
|
+
break;
|
|
489
|
+
if (word.startsWith("-")) {
|
|
490
|
+
if (takesValue(word))
|
|
491
|
+
at++;
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
seen++;
|
|
495
|
+
if (seen === count)
|
|
496
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
497
|
+
}
|
|
498
|
+
return { own: args, rest: undefined };
|
|
499
|
+
}
|
|
500
|
+
function listed(options, allowNegative) {
|
|
501
|
+
if (!allowNegative)
|
|
502
|
+
return options;
|
|
503
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
504
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
505
|
+
return [[name, option]];
|
|
506
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
507
|
+
}));
|
|
508
|
+
}
|
|
509
|
+
function withBare(args, options) {
|
|
510
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
511
|
+
if (bare.size === 0)
|
|
512
|
+
return args;
|
|
513
|
+
const separator = args.indexOf("--");
|
|
514
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
515
|
+
return [...own.flatMap((arg, index) => {
|
|
516
|
+
const optional = bare.get(arg);
|
|
517
|
+
const next = own[index + 1];
|
|
518
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
519
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
520
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
521
|
+
}
|
|
522
|
+
function checkConflicts(values, options) {
|
|
523
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
524
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
525
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
526
|
+
if (other !== undefined)
|
|
527
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
function checkChoices(values, options) {
|
|
531
|
+
for (const [name, option] of Object.entries(options)) {
|
|
532
|
+
if (option.choices === undefined)
|
|
533
|
+
continue;
|
|
534
|
+
const given = values[name];
|
|
535
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
536
|
+
if (typeof value === "string")
|
|
537
|
+
oneOf(value, name, option.choices);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
function oneOf(value, name, choices) {
|
|
542
|
+
if (!choices.includes(value))
|
|
543
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
544
|
+
return value;
|
|
545
|
+
}
|
|
546
|
+
function checkPositionals(given, names) {
|
|
547
|
+
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
548
|
+
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
549
|
+
if (given.length < required)
|
|
550
|
+
badUsage(`missing ${names[given.length]}`);
|
|
551
|
+
if (!variadic && given.length > names.length)
|
|
552
|
+
badUsage(`unexpected argument ${given[names.length]}`);
|
|
553
|
+
}
|
|
554
|
+
function joinDashValues(args, options) {
|
|
555
|
+
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
556
|
+
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
557
|
+
const joined = [];
|
|
558
|
+
for (let i = 0;i < args.length; i++) {
|
|
559
|
+
const arg = args[i] ?? "";
|
|
560
|
+
if (arg === "--")
|
|
561
|
+
return [...joined, ...args.slice(i)];
|
|
562
|
+
const name = longOf.get(arg);
|
|
563
|
+
const next = args[i + 1];
|
|
564
|
+
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
565
|
+
joined.push(`--${name}=${next}`);
|
|
566
|
+
i++;
|
|
567
|
+
} else {
|
|
568
|
+
joined.push(arg);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
return joined;
|
|
572
|
+
}
|
|
573
|
+
function parseError(error) {
|
|
574
|
+
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
575
|
+
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
576
|
+
}
|
|
577
|
+
var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
578
|
+
function nearestOption(message, options, allowNegative) {
|
|
579
|
+
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
580
|
+
if (typed === undefined)
|
|
581
|
+
return;
|
|
582
|
+
const word = typed.replace(DASHES, "");
|
|
583
|
+
if (word.length < 2 && !typed.startsWith("--"))
|
|
584
|
+
return;
|
|
585
|
+
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
586
|
+
...option.short === undefined ? [] : [`-${option.short}`],
|
|
587
|
+
`--${name}`,
|
|
588
|
+
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
589
|
+
]);
|
|
590
|
+
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
591
|
+
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
592
|
+
}
|
|
593
|
+
// ../kit/src/progress.ts
|
|
594
|
+
var ESC = String.fromCharCode(27);
|
|
595
|
+
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
596
|
+
var RESET_STYLE = `${ESC}[0m`;
|
|
597
|
+
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
598
|
+
// ../kit/src/cli.ts
|
|
599
|
+
import process6 from "process";
|
|
600
|
+
|
|
601
|
+
// ../kit/src/usage.ts
|
|
602
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
603
|
+
import { homedir } from "os";
|
|
604
|
+
import { dirname, isAbsolute, join } from "path";
|
|
605
|
+
import process5 from "process";
|
|
606
|
+
|
|
607
|
+
// ../kit/src/logs.ts
|
|
608
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
609
|
+
var CLI_FOLDER = "kaynooo-cli";
|
|
610
|
+
|
|
611
|
+
// ../kit/src/usage.ts
|
|
612
|
+
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
613
|
+
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
614
|
+
var LONGEST_NAME = 40;
|
|
615
|
+
var usageError;
|
|
616
|
+
function noteUsageError(message) {
|
|
617
|
+
usageError = message;
|
|
618
|
+
}
|
|
619
|
+
function stateHome(env = process5.env) {
|
|
620
|
+
const dir = env.XDG_STATE_HOME;
|
|
621
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
|
|
622
|
+
}
|
|
623
|
+
function usagePath(env = process5.env) {
|
|
624
|
+
return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
625
|
+
}
|
|
626
|
+
function usageRecorded(env = process5.env) {
|
|
627
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
628
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
629
|
+
}
|
|
630
|
+
function flagNames(argv) {
|
|
631
|
+
const end = argv.indexOf("--");
|
|
632
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
633
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
634
|
+
}
|
|
635
|
+
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
636
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
637
|
+
usageError = undefined;
|
|
638
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
639
|
+
}
|
|
640
|
+
function recordUsage(entry, env = process5.env) {
|
|
641
|
+
if (!usageRecorded(env))
|
|
642
|
+
return;
|
|
643
|
+
try {
|
|
644
|
+
const path = usagePath(env);
|
|
645
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
646
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
647
|
+
`, { mode: 384 });
|
|
648
|
+
} catch {}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// ../kit/src/cli.ts
|
|
652
|
+
var LEVEL_OPTIONS = {
|
|
653
|
+
...OUTPUT_OPTIONS,
|
|
654
|
+
help: { type: "boolean", short: "h", description: "show this help" }
|
|
655
|
+
};
|
|
656
|
+
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
657
|
+
function printError(prefix, message, hint, cause) {
|
|
658
|
+
const colors = paint(process6.stderr);
|
|
659
|
+
const styled = takesControlCodes(process6.stderr);
|
|
660
|
+
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
661
|
+
const under = (label, text, tint) => text === undefined ? "" : `
|
|
662
|
+
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
663
|
+
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
664
|
+
}
|
|
665
|
+
function printJsonError(message, hint, cause) {
|
|
666
|
+
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
667
|
+
}
|
|
668
|
+
function wantsJson(argv) {
|
|
669
|
+
const end = argv.indexOf("--");
|
|
670
|
+
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
671
|
+
}
|
|
672
|
+
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
673
|
+
if (error instanceof HelpShown)
|
|
674
|
+
return 0;
|
|
675
|
+
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
676
|
+
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
677
|
+
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
678
|
+
if (error instanceof UsageError)
|
|
679
|
+
noteUsageError(error.message);
|
|
680
|
+
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
681
|
+
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
682
|
+
return error instanceof Exit ? error.code : 1;
|
|
683
|
+
}
|
|
684
|
+
var COMPLETE = "__complete";
|
|
685
|
+
var FILES = "__files__";
|
|
686
|
+
async function completingOf(run) {
|
|
687
|
+
completion.active = true;
|
|
688
|
+
try {
|
|
689
|
+
await run([]);
|
|
690
|
+
} catch (error) {
|
|
691
|
+
if (error instanceof Completing)
|
|
692
|
+
return error;
|
|
693
|
+
} finally {
|
|
694
|
+
completion.active = false;
|
|
695
|
+
}
|
|
696
|
+
return new Completing({});
|
|
697
|
+
}
|
|
698
|
+
function candidateLine(candidate) {
|
|
699
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
700
|
+
}
|
|
701
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
702
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
703
|
+
let index = 0;
|
|
704
|
+
let at = 0;
|
|
705
|
+
while (at < before.length) {
|
|
706
|
+
const word = before[at];
|
|
707
|
+
if (word === "--") {
|
|
708
|
+
index += before.length - at - 1;
|
|
709
|
+
break;
|
|
710
|
+
}
|
|
711
|
+
if (!word.startsWith("-"))
|
|
712
|
+
index++;
|
|
713
|
+
else if (takesValue(word))
|
|
714
|
+
at++;
|
|
715
|
+
at++;
|
|
716
|
+
}
|
|
717
|
+
const last = positionals.at(-1);
|
|
718
|
+
if (index < positionals.length)
|
|
719
|
+
return positionals[index];
|
|
720
|
+
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
721
|
+
}
|
|
722
|
+
async function leafCandidates(run, words) {
|
|
723
|
+
const completing = await completingOf(run);
|
|
724
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
725
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
726
|
+
const flag = words.at(-2);
|
|
727
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
728
|
+
if (option?.type === "string") {
|
|
729
|
+
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
730
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
731
|
+
}
|
|
732
|
+
const name = positionalBeingTyped(words.slice(0, -1), completing);
|
|
733
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
734
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
735
|
+
}
|
|
736
|
+
async function printCandidates(found) {
|
|
737
|
+
for (const line of await found)
|
|
738
|
+
console.log(line);
|
|
739
|
+
return 0;
|
|
740
|
+
}
|
|
741
|
+
async function runMain({ name, version, run, redact, usage }, argv = process6.argv.slice(2)) {
|
|
742
|
+
if (argv[0] === COMPLETE)
|
|
743
|
+
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
744
|
+
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
745
|
+
console.log(version);
|
|
746
|
+
return 0;
|
|
747
|
+
}
|
|
748
|
+
let code;
|
|
749
|
+
try {
|
|
750
|
+
code = await run(argv);
|
|
751
|
+
} catch (error) {
|
|
752
|
+
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
753
|
+
}
|
|
754
|
+
if (usage !== false)
|
|
755
|
+
recordUsage(usageEntry(name, undefined, argv, code));
|
|
756
|
+
return code;
|
|
757
|
+
}
|
|
758
|
+
// ../kit/src/secrets.ts
|
|
759
|
+
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
760
|
+
// ../kit/src/sessions.ts
|
|
761
|
+
var {Glob } = globalThis.Bun;
|
|
762
|
+
var SESSION_FILES = new Glob("*.json");
|
|
763
|
+
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
764
|
+
// package.json
|
|
765
|
+
var version = "0.4.1";
|
|
766
|
+
|
|
767
|
+
// src/blocks.ts
|
|
768
|
+
var LINE_BREAK = /\r?\n/;
|
|
769
|
+
var OPENER = /^(<{7,}) SEARCH$/;
|
|
770
|
+
function parseBlocks(text) {
|
|
771
|
+
const blocks = [];
|
|
772
|
+
const lines = text.split(LINE_BREAK);
|
|
773
|
+
let file;
|
|
774
|
+
let i = 0;
|
|
775
|
+
while (i < lines.length) {
|
|
776
|
+
const line = lines[i] ?? "";
|
|
777
|
+
const opener = OPENER.exec(line);
|
|
778
|
+
i++;
|
|
779
|
+
if (opener === null) {
|
|
780
|
+
if (line.trim() === "")
|
|
781
|
+
continue;
|
|
782
|
+
if (file !== undefined)
|
|
783
|
+
return `line ${i}: "${line}" after the file name "${file}", which wants a <<<<<<< SEARCH block next`;
|
|
784
|
+
file = line.trim();
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
const width = (opener[1] ?? "").length;
|
|
788
|
+
const divider = "=".repeat(width);
|
|
789
|
+
const closer = `${">".repeat(width)} REPLACE`;
|
|
790
|
+
const start = i;
|
|
791
|
+
const search = [];
|
|
792
|
+
const replace = [];
|
|
793
|
+
let target = search;
|
|
794
|
+
let closed = false;
|
|
795
|
+
for (;i < lines.length; i++) {
|
|
796
|
+
const inner = lines[i] ?? "";
|
|
797
|
+
if (inner === closer && target === replace) {
|
|
798
|
+
closed = true;
|
|
799
|
+
i++;
|
|
800
|
+
break;
|
|
801
|
+
}
|
|
802
|
+
if (inner === divider && target === search)
|
|
803
|
+
target = replace;
|
|
804
|
+
else
|
|
805
|
+
target.push(inner);
|
|
806
|
+
}
|
|
807
|
+
if (!closed)
|
|
808
|
+
return `line ${start}: the block never reaches its ${target === search ? `${divider} line and ` : ""}${closer} line`;
|
|
809
|
+
blocks.push({ file, from: search.join(`
|
|
810
|
+
`), to: replace.join(`
|
|
811
|
+
`) });
|
|
812
|
+
file = undefined;
|
|
813
|
+
}
|
|
814
|
+
if (file !== undefined)
|
|
815
|
+
return `the file name "${file}" is not followed by a block`;
|
|
816
|
+
return blocks.length === 0 ? "no <<<<<<< SEARCH block found" : blocks;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// src/diff.ts
|
|
820
|
+
import { mkdtempSync, rmSync, writeFileSync } from "fs";
|
|
821
|
+
import { tmpdir } from "os";
|
|
822
|
+
import { join as join2 } from "path";
|
|
823
|
+
async function diffTexts(path, before, after) {
|
|
824
|
+
const dir = mkdtempSync(join2(tmpdir(), "sub-"));
|
|
825
|
+
try {
|
|
826
|
+
writeFileSync(join2(dir, "before"), before);
|
|
827
|
+
writeFileSync(join2(dir, "after"), after);
|
|
828
|
+
let child;
|
|
829
|
+
try {
|
|
830
|
+
child = Bun.spawn(["diff", "-u", "--label", `a/${path}`, "--label", `b/${path}`, join2(dir, "before"), join2(dir, "after")], { stdout: "pipe", stderr: "pipe" });
|
|
831
|
+
} catch {
|
|
832
|
+
throw new Error("diff is not installed, which sub needs to show its changes");
|
|
833
|
+
}
|
|
834
|
+
const unified = await new Response(child.stdout).text();
|
|
835
|
+
await child.exited;
|
|
836
|
+
const body = unified.split(`
|
|
837
|
+
`).slice(2);
|
|
838
|
+
return {
|
|
839
|
+
unified,
|
|
840
|
+
added: body.filter((line) => line.startsWith("+")).length,
|
|
841
|
+
removed: body.filter((line) => line.startsWith("-")).length
|
|
842
|
+
};
|
|
843
|
+
} finally {
|
|
844
|
+
rmSync(dir, { recursive: true, force: true });
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// src/replace.ts
|
|
849
|
+
var CRLF = /\r?\n/g;
|
|
850
|
+
var BRACED_GROUP = /\$\$|\$\{(\w+)\}/g;
|
|
851
|
+
var DIGITS = /^\d+$/;
|
|
852
|
+
var LONGEST_LIST = 8;
|
|
853
|
+
function linesOf(text, indexes) {
|
|
854
|
+
const lines = [];
|
|
855
|
+
let line = 1;
|
|
856
|
+
let at = 0;
|
|
857
|
+
for (const index of indexes) {
|
|
858
|
+
for (;at < index; at++) {
|
|
859
|
+
if (text[at] === `
|
|
860
|
+
`)
|
|
861
|
+
line++;
|
|
862
|
+
}
|
|
863
|
+
lines.push(line);
|
|
864
|
+
}
|
|
865
|
+
return lines;
|
|
866
|
+
}
|
|
867
|
+
function listLines(lines) {
|
|
868
|
+
const shown = lines.slice(0, LONGEST_LIST).join(", ");
|
|
869
|
+
return lines.length > LONGEST_LIST ? `${shown} and ${lines.length - LONGEST_LIST} more` : shown;
|
|
870
|
+
}
|
|
871
|
+
function literalIndexes(text, from) {
|
|
872
|
+
const found = [];
|
|
873
|
+
for (let at = text.indexOf(from);at !== -1; at = text.indexOf(from, at + from.length))
|
|
874
|
+
found.push(at);
|
|
875
|
+
return found;
|
|
876
|
+
}
|
|
877
|
+
function firstLineHint(text, from) {
|
|
878
|
+
const first = from.split(`
|
|
879
|
+
`).find((line) => line.trim() !== "")?.trim();
|
|
880
|
+
if (first === undefined || first === from.trim())
|
|
881
|
+
return "";
|
|
882
|
+
const lines = text.split(`
|
|
883
|
+
`).flatMap((line, i) => line.includes(first) ? [i + 1] : []);
|
|
884
|
+
return lines.length === 0 ? "" : ` (its first line is on line${lines.length > 1 ? "s" : ""} ${listLines(lines)})`;
|
|
885
|
+
}
|
|
886
|
+
function compile(source) {
|
|
887
|
+
return new RegExp(source, "gm");
|
|
888
|
+
}
|
|
889
|
+
function bracedGroups(to) {
|
|
890
|
+
return to.replace(BRACED_GROUP, (whole, group) => {
|
|
891
|
+
if (group === undefined)
|
|
892
|
+
return whole;
|
|
893
|
+
if (!DIGITS.test(group))
|
|
894
|
+
return `$<${group}>`;
|
|
895
|
+
return Number(group) === 0 ? "$&" : `$${group.padStart(2, "0")}`;
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
function applyPairs(original, pairs) {
|
|
899
|
+
const crlf = original.includes(`\r
|
|
900
|
+
`);
|
|
901
|
+
const lines = [];
|
|
902
|
+
const problems = [];
|
|
903
|
+
let text = original;
|
|
904
|
+
for (const [i, pair] of pairs.entries()) {
|
|
905
|
+
const label = pairs.length > 1 ? `pair ${i + 1}: ` : "";
|
|
906
|
+
const from = crlf && pair.regex !== true ? pair.from.replace(CRLF, `\r
|
|
907
|
+
`) : pair.from;
|
|
908
|
+
const to = crlf && pair.regex !== true ? pair.to.replace(CRLF, `\r
|
|
909
|
+
`) : pair.to;
|
|
910
|
+
const pattern = pair.regex === true ? compile(from) : undefined;
|
|
911
|
+
const indexes = pattern === undefined ? literalIndexes(text, from) : [...text.matchAll(pattern)].map((match) => match.index);
|
|
912
|
+
const found = linesOf(text, indexes);
|
|
913
|
+
const expected = pair.count ?? 1;
|
|
914
|
+
if (pair.all === true ? indexes.length === 0 : indexes.length !== expected) {
|
|
915
|
+
const wanted = pair.all === true ? "at least 1" : String(expected);
|
|
916
|
+
let where = ` on lines ${listLines(found)}: add context to --from, or pass --count ${indexes.length} or --all`;
|
|
917
|
+
if (indexes.length === 0)
|
|
918
|
+
where = pattern === undefined ? firstLineHint(text, from) : "";
|
|
919
|
+
problems.push(`${label}matched ${indexes.length} time${indexes.length === 1 ? "" : "s"}, expected ${wanted}${where}`);
|
|
920
|
+
continue;
|
|
921
|
+
}
|
|
922
|
+
lines.push(...found);
|
|
923
|
+
text = pattern === undefined ? text.split(from).join(to) : text.replace(pattern, bracedGroups(to));
|
|
924
|
+
}
|
|
925
|
+
return { text, lines, problems };
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
// src/cli.ts
|
|
929
|
+
var USAGE = `sub [options] <file>...: replaces text in files, writing nothing unless every replacement matches as often as expected
|
|
930
|
+
|
|
931
|
+
Multi-line text: give no --from, --to or --pairs and pipe SEARCH/REPLACE blocks on stdin from a quoted heredoc, which needs no escaping. The blocks apply in order to the files on the command line, each matching exactly once unless --count or --all says otherwise:
|
|
932
|
+
|
|
933
|
+
sub src/a.php <<'EOF'
|
|
934
|
+
<<<<<<< SEARCH
|
|
935
|
+
old lines
|
|
936
|
+
=======
|
|
937
|
+
new lines
|
|
938
|
+
>>>>>>> REPLACE
|
|
939
|
+
EOF
|
|
940
|
+
|
|
941
|
+
A line naming a file before a block makes it apply to that file alone, so one call edits several files (no file argument needed when every block names one). An empty REPLACE deletes the SEARCH text; to drop whole lines, put the neighbouring line in both. When the text holds a marker line itself (a Markdown '=======' underline), open with more characters, '<<<<<<<<<< SEARCH', and divide and close with as many '=' and '>' too.
|
|
942
|
+
|
|
943
|
+
Exits 0 when it wrote every replacement, 1 when one did not match or a file cannot be written (nothing is written), 2 on a usage error.`;
|
|
944
|
+
var OPTIONS = {
|
|
945
|
+
from: { type: "string", short: "f", description: "text to find, taken literally" },
|
|
946
|
+
to: { type: "string", short: "t", description: "text to put in its place, empty to delete it" },
|
|
947
|
+
count: { type: "string", short: "n", description: "matches expected in each file (default 1)" },
|
|
948
|
+
all: { type: "boolean", short: "a", description: "replace every match, expecting at least one in each file" },
|
|
949
|
+
regex: { type: "boolean", short: "r", description: "--from is a regular expression (^ and $ match each line), --to may use $1, ${1}, $<name> and ${name}" },
|
|
950
|
+
pairs: { type: "string", short: "p", description: "JSON array of {from, to, count?, all?, regex?} applied in order: inline when it starts with [, else a file or - for stdin" },
|
|
951
|
+
diff: { type: "boolean", short: "d", description: "print each file's unified diff" },
|
|
952
|
+
"dry-run": { type: "boolean", description: "show what would change without writing" }
|
|
953
|
+
};
|
|
954
|
+
var PAIR_KEYS = ["from", "to", "count", "all", "regex"];
|
|
955
|
+
function checkPattern(pair, label) {
|
|
956
|
+
if (pair.from === "")
|
|
957
|
+
fail(`${label}--from is empty`);
|
|
958
|
+
if (pair.regex !== true)
|
|
959
|
+
return;
|
|
960
|
+
try {
|
|
961
|
+
compile(pair.from);
|
|
962
|
+
} catch (error) {
|
|
963
|
+
fail(`${label}--from is no valid regular expression: ${error instanceof Error ? error.message : String(error)}`);
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
function pairFrom(item, i, defaults) {
|
|
967
|
+
const label = `pair ${i + 1}: `;
|
|
968
|
+
if (typeof item !== "object" || item === null || Array.isArray(item))
|
|
969
|
+
fail(`${label}give an object {from, to}`);
|
|
970
|
+
const { from, to, count, all, regex, ...rest } = item;
|
|
971
|
+
const unknown = Object.keys(rest);
|
|
972
|
+
if (unknown.length > 0)
|
|
973
|
+
fail(`${label}unknown key${unknown.length === 1 ? "" : "s"} ${unknown.join(", ")}, known: ${PAIR_KEYS.join(", ")}`);
|
|
974
|
+
if (typeof from !== "string" || typeof to !== "string")
|
|
975
|
+
fail(`${label}from and to must both be strings`);
|
|
976
|
+
if (count !== undefined && (typeof count !== "number" || !Number.isInteger(count) || count < 1))
|
|
977
|
+
fail(`${label}count takes a whole number from 1`);
|
|
978
|
+
if (all !== undefined && typeof all !== "boolean" || regex !== undefined && typeof regex !== "boolean")
|
|
979
|
+
fail(`${label}all and regex take true or false`);
|
|
980
|
+
const pair = { from, to, count: count ?? defaults.count ?? 1, all: all ?? defaults.all, regex: regex ?? defaults.regex };
|
|
981
|
+
checkPattern(pair, label);
|
|
982
|
+
return pair;
|
|
983
|
+
}
|
|
984
|
+
async function readPairs(path, defaults) {
|
|
985
|
+
let items;
|
|
986
|
+
try {
|
|
987
|
+
items = JSON.parse(path.trimStart().startsWith("[") ? path : await readInput(path, { noStdin: "pipe the pairs on stdin, or give their file to --pairs" }));
|
|
988
|
+
} catch (error) {
|
|
989
|
+
if (error instanceof Exit)
|
|
990
|
+
throw error;
|
|
991
|
+
fail(`--pairs is no valid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
992
|
+
}
|
|
993
|
+
if (!Array.isArray(items) || items.length === 0)
|
|
994
|
+
fail("--pairs takes a JSON array of at least one {from, to}");
|
|
995
|
+
return items.map((item, i) => pairFrom(item, i, defaults));
|
|
996
|
+
}
|
|
997
|
+
function plural(count, word) {
|
|
998
|
+
return `${count} ${word}${count === 1 ? "" : "s"}`;
|
|
999
|
+
}
|
|
1000
|
+
function writable(path) {
|
|
1001
|
+
try {
|
|
1002
|
+
accessSync(path, constants.W_OK);
|
|
1003
|
+
return true;
|
|
1004
|
+
} catch {
|
|
1005
|
+
return false;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
1009
|
+
function readUtf8(path) {
|
|
1010
|
+
try {
|
|
1011
|
+
return UTF8.decode(readFileSync(path));
|
|
1012
|
+
} catch {
|
|
1013
|
+
return;
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
function canonical(path) {
|
|
1017
|
+
try {
|
|
1018
|
+
return realpathSync(path);
|
|
1019
|
+
} catch {
|
|
1020
|
+
return resolve(path);
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
function dedupe(paths) {
|
|
1024
|
+
const byFile = new Map;
|
|
1025
|
+
for (const path of paths) {
|
|
1026
|
+
const key = canonical(path);
|
|
1027
|
+
if (!byFile.has(key))
|
|
1028
|
+
byFile.set(key, path);
|
|
1029
|
+
}
|
|
1030
|
+
return [...byFile.values()];
|
|
1031
|
+
}
|
|
1032
|
+
function writeAtomic(path, text) {
|
|
1033
|
+
const target = realpathSync(path);
|
|
1034
|
+
const temp = `${target}.sub-${process8.pid}`;
|
|
1035
|
+
try {
|
|
1036
|
+
writeFileSync2(temp, text);
|
|
1037
|
+
chmodSync(temp, (statSync(target, { throwIfNoEntry: false })?.mode ?? 420) & 4095);
|
|
1038
|
+
renameSync(temp, target);
|
|
1039
|
+
} catch (error) {
|
|
1040
|
+
rmSync2(temp, { force: true });
|
|
1041
|
+
throw error;
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
async function plan(values, files, defaults) {
|
|
1045
|
+
const edits = new Map;
|
|
1046
|
+
const spellings = new Map(files.map((path) => [canonical(path), path]));
|
|
1047
|
+
if (values.pairs !== undefined || values.from !== undefined || values.to !== undefined) {
|
|
1048
|
+
if (files.length === 0)
|
|
1049
|
+
fail(`give at least one file
|
|
1050
|
+
|
|
1051
|
+
${USAGE}`);
|
|
1052
|
+
let pairs;
|
|
1053
|
+
if (values.pairs !== undefined) {
|
|
1054
|
+
if (values.from !== undefined || values.to !== undefined)
|
|
1055
|
+
fail("give either --pairs or --from and --to");
|
|
1056
|
+
pairs = await readPairs(values.pairs, defaults);
|
|
1057
|
+
} else {
|
|
1058
|
+
if (values.from === undefined || values.to === undefined)
|
|
1059
|
+
fail(`give --from and --to (--to '' deletes), or --pairs
|
|
1060
|
+
|
|
1061
|
+
${USAGE}`);
|
|
1062
|
+
pairs = [{ from: values.from, to: values.to, count: defaults.count ?? 1, all: defaults.all, regex: defaults.regex }];
|
|
1063
|
+
checkPattern(pairs[0], "");
|
|
1064
|
+
}
|
|
1065
|
+
for (const path of files)
|
|
1066
|
+
edits.set(path, pairs);
|
|
1067
|
+
return edits;
|
|
1068
|
+
}
|
|
1069
|
+
const blocks = parseBlocks(await readInput("-", { noStdin: `give --from and --to, or pipe SEARCH/REPLACE blocks on stdin
|
|
1070
|
+
|
|
1071
|
+
${USAGE}` }));
|
|
1072
|
+
if (typeof blocks === "string")
|
|
1073
|
+
fail(`blocks: ${blocks}`);
|
|
1074
|
+
for (const [i, block] of blocks.entries()) {
|
|
1075
|
+
const pair = { from: block.from, to: block.to, count: defaults.count ?? 1, all: defaults.all, regex: defaults.regex };
|
|
1076
|
+
const named = block.file === undefined ? undefined : normalize(block.file);
|
|
1077
|
+
const targets = named === undefined ? files : [spellings.get(canonical(named)) ?? named];
|
|
1078
|
+
if (named !== undefined && !spellings.has(canonical(named)))
|
|
1079
|
+
spellings.set(canonical(named), named);
|
|
1080
|
+
checkPattern(pair, `block ${i + 1}: `);
|
|
1081
|
+
if (targets.length === 0)
|
|
1082
|
+
fail(`block ${i + 1} names no file and none is given as an argument`);
|
|
1083
|
+
for (const path of targets)
|
|
1084
|
+
edits.set(path, [...edits.get(path) ?? [], pair]);
|
|
1085
|
+
}
|
|
1086
|
+
for (const path of files) {
|
|
1087
|
+
if (!edits.has(path))
|
|
1088
|
+
fail(`no block applies to ${path}`);
|
|
1089
|
+
}
|
|
1090
|
+
return edits;
|
|
1091
|
+
}
|
|
1092
|
+
async function main(argv) {
|
|
1093
|
+
const parsed = parse(argv, USAGE, OPTIONS, { replaces: "sed -i and one-off bun -e or python editors", examples: [["sub src/a.php <<'EOF' (SEARCH/REPLACE blocks, see above)", "multi-line text, no escaping"], ["sub --from oldName --to newName --all src/a.ts src/b.ts", "every match in two files"], ['sub --regex --from "v(\\d+)" --to "v$1.0" --dry-run --diff README.md', "the diff, nothing written"]] });
|
|
1094
|
+
const { values, positionals } = parsed;
|
|
1095
|
+
const files = dedupe(positionals.map((path) => normalize(path)));
|
|
1096
|
+
if (values.count !== undefined && values.all === true)
|
|
1097
|
+
fail("--count and --all exclude each other");
|
|
1098
|
+
const defaults = { count: values.count === undefined ? undefined : wholeNumber(values.count, "count", 1), all: values.all === true, regex: values.regex === true };
|
|
1099
|
+
const edits = await plan(values, files, defaults);
|
|
1100
|
+
const changes = [];
|
|
1101
|
+
const problems = [];
|
|
1102
|
+
for (const [path, pairs] of edits) {
|
|
1103
|
+
if (!existsSync(path)) {
|
|
1104
|
+
problems.push(`${path}: no such file`);
|
|
1105
|
+
continue;
|
|
1106
|
+
}
|
|
1107
|
+
const before = readUtf8(path);
|
|
1108
|
+
if (before === undefined) {
|
|
1109
|
+
problems.push(`${path}: not valid UTF-8, left alone`);
|
|
1110
|
+
continue;
|
|
1111
|
+
}
|
|
1112
|
+
const applied = applyPairs(before, pairs);
|
|
1113
|
+
problems.push(...applied.problems.map((problem) => `${path}: ${problem}`));
|
|
1114
|
+
if (applied.problems.length === 0 && values["dry-run"] !== true && !writable(path))
|
|
1115
|
+
problems.push(`${path}: not writable`);
|
|
1116
|
+
changes.push({ path, before, after: applied.text, lines: applied.lines });
|
|
1117
|
+
}
|
|
1118
|
+
if (problems.length > 0) {
|
|
1119
|
+
console.error(`sub: nothing written
|
|
1120
|
+
${problems.join(`
|
|
1121
|
+
`)}`);
|
|
1122
|
+
return 1;
|
|
1123
|
+
}
|
|
1124
|
+
try {
|
|
1125
|
+
for (const change of changes)
|
|
1126
|
+
change.diff = await diffTexts(change.path, change.before, change.after);
|
|
1127
|
+
} catch (error) {
|
|
1128
|
+
console.error(`sub: nothing written
|
|
1129
|
+
${error instanceof Error ? error.message : String(error)}`);
|
|
1130
|
+
return 1;
|
|
1131
|
+
}
|
|
1132
|
+
for (const { path, before, after, lines, diff } of changes) {
|
|
1133
|
+
if (diff === undefined)
|
|
1134
|
+
continue;
|
|
1135
|
+
if (values["dry-run"] !== true && after !== before)
|
|
1136
|
+
writeAtomic(path, after);
|
|
1137
|
+
console.log(`${path}: ${plural(lines.length, "replacement")} on line${lines.length === 1 ? "" : "s"} ${listLines(lines)}, +${diff.added} -${diff.removed}`);
|
|
1138
|
+
if (values.diff === true && diff.unified !== "")
|
|
1139
|
+
process8.stdout.write(diff.unified);
|
|
1140
|
+
}
|
|
1141
|
+
if (values["dry-run"] === true)
|
|
1142
|
+
console.log("dry run: nothing written");
|
|
1143
|
+
return 0;
|
|
1144
|
+
}
|
|
1145
|
+
process8.exitCode = await runMain({ name: "sub", version, run: main });
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-edit",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.4.1",
|
|
5
|
+
"description": "sub: text replaced in files for Claude Code, written only when every replacement matches as often as expected.",
|
|
6
|
+
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"homepage": "https://git.kaynooo.fr/kaynooo/cli/src/branch/main/packages/edit#readme",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://git.kaynooo.fr/kaynooo/cli.git",
|
|
12
|
+
"directory": "packages/edit"
|
|
13
|
+
},
|
|
14
|
+
"bugs": "https://git.kaynooo.fr/kaynooo/cli/issues",
|
|
15
|
+
"keywords": [
|
|
16
|
+
"claude-code",
|
|
17
|
+
"cli",
|
|
18
|
+
"edit",
|
|
19
|
+
"replace",
|
|
20
|
+
"sed"
|
|
21
|
+
],
|
|
22
|
+
"bin": {
|
|
23
|
+
"sub": "./dist/cli.js"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"engines": {
|
|
29
|
+
"bun": ">=1.4.3"
|
|
30
|
+
},
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"registry": "https://git.kaynooo.fr/api/packages/kaynooo/npm/"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "$npm_execpath build src/cli.ts --target bun --outdir dist",
|
|
36
|
+
"sub": "$npm_execpath src/cli.ts"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@kaynooo/cli-kit": "0.20.0"
|
|
40
|
+
}
|
|
41
|
+
}
|