opencode-fs-plugin 1.1.0 → 1.2.0
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/INSTALL.md +9 -9
- package/README.md +15 -15
- package/SPEC.md +11 -7
- package/package.json +1 -1
- package/skills/filesystem/SKILL.md +85 -7
- package/src/tools/du.ts +5 -7
- package/src/tools/find.ts +302 -44
- package/src/tools/ls.ts +108 -13
- package/src/tools/pipe.ts +6 -3
- package/src/tools/sort.ts +181 -14
- package/src/tools/stat.ts +62 -1
- package/src/tools/tail.ts +107 -3
- package/src/tools/tar.ts +42 -3
- package/src/tools/zip.ts +33 -4
package/src/tools/find.ts
CHANGED
|
@@ -7,7 +7,8 @@ import * as fs from "node:fs/promises";
|
|
|
7
7
|
import * as path from "node:path";
|
|
8
8
|
import picomatch from "picomatch";
|
|
9
9
|
import { Type, type Static } from "@sinclair/typebox";
|
|
10
|
-
import {
|
|
10
|
+
import { FsError } from "../core/errors.js";
|
|
11
|
+
import { lookupGroup, lookupUser, modeString, num, typeName, walk } from "../core/fsutil.js";
|
|
11
12
|
import { parseSize } from "../core/format.js";
|
|
12
13
|
import { textResult, type ToolSpec } from "../core/types.js";
|
|
13
14
|
|
|
@@ -17,6 +18,10 @@ const Schema = Type.Object(
|
|
|
17
18
|
name: Type.Optional(Type.String({ description: "Filename glob (`-name`)." })),
|
|
18
19
|
iname: Type.Optional(Type.String({ description: "Case-insensitive filename glob (`-iname`)." })),
|
|
19
20
|
pathPattern: Type.Optional(Type.String({ description: "Path glob (`-path`)." })),
|
|
21
|
+
lname: Type.Optional(Type.String({ description: "Symlink target glob (`-lname`)." })),
|
|
22
|
+
ilname: Type.Optional(Type.String({ description: "Case-insensitive symlink target glob (`-ilname`)." })),
|
|
23
|
+
regex: Type.Optional(Type.String({ description: "Full-path regular expression (`-regex`)." })),
|
|
24
|
+
iregex: Type.Optional(Type.String({ description: "Case-insensitive full-path regex (`-iregex`)." })),
|
|
20
25
|
type: Type.Optional(
|
|
21
26
|
Type.Union([Type.Literal("f"), Type.Literal("d"), Type.Literal("l"), Type.Literal("p"), Type.Literal("s")], {
|
|
22
27
|
description: "Entry type (`-type`).",
|
|
@@ -29,7 +34,17 @@ const Schema = Type.Object(
|
|
|
29
34
|
minDepth: Type.Optional(Type.Integer({ minimum: 0, description: "Minimum depth (`-mindepth`)." })),
|
|
30
35
|
empty: Type.Optional(Type.Boolean({ description: "Empty files or directories (`-empty`)." })),
|
|
31
36
|
perm: Type.Optional(Type.String({ description: "Octal permission mode (`-perm`)." })),
|
|
37
|
+
uid: Type.Optional(Type.Integer({ minimum: 0, description: "Numeric owner uid (`-uid`)." })),
|
|
38
|
+
gid: Type.Optional(Type.Integer({ minimum: 0, description: "Numeric group gid (`-gid`)." })),
|
|
39
|
+
user: Type.Optional(Type.String({ description: "Owner name or uid (`-user`)." })),
|
|
40
|
+
group: Type.Optional(Type.String({ description: "Group name or gid (`-group`)." })),
|
|
41
|
+
links: Type.Optional(Type.String({ description: "Hard-link count expression, e.g. +1 (`-links`)." })),
|
|
42
|
+
inum: Type.Optional(Type.Integer({ minimum: 0, description: "Exact inode number (`-inum`)." })),
|
|
43
|
+
samefile: Type.Optional(Type.String({ description: "Same device and inode as this path (`-samefile`)." })),
|
|
44
|
+
fstype: Type.Optional(Type.String({ description: "Filesystem type, e.g. ext4, tmpfs, nfs (`-fstype`)." })),
|
|
32
45
|
newer: Type.Optional(Type.String({ description: "Only entries newer than this file (`-newer`)." })),
|
|
46
|
+
newerXY: Type.Optional(Type.String({ description: "GNU -newerXY expression as XY:path, e.g. mm:/tmp/ref." })),
|
|
47
|
+
printf: Type.Optional(Type.String({ description: "Per-match format string (`-printf`)." })),
|
|
33
48
|
follow: Type.Optional(Type.Boolean({ description: "Follow symlinks (`-L`)." })),
|
|
34
49
|
print0: Type.Optional(Type.Boolean({ description: "NUL-separated output (`-print0`)." })),
|
|
35
50
|
sort: Type.Optional(Type.Boolean({ description: "Sort results lexically. Default: true." })),
|
|
@@ -39,33 +54,90 @@ const Schema = Type.Object(
|
|
|
39
54
|
|
|
40
55
|
type Input = Static<typeof Schema>;
|
|
41
56
|
|
|
57
|
+
interface NewerXY {
|
|
58
|
+
x: "a" | "c" | "m" | "B";
|
|
59
|
+
y: "a" | "c" | "m" | "B";
|
|
60
|
+
value: number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface Patterns {
|
|
64
|
+
nameMatch?: ((value: string) => boolean) | undefined;
|
|
65
|
+
inameMatch?: ((value: string) => boolean) | undefined;
|
|
66
|
+
pathMatch?: ((value: string) => boolean) | undefined;
|
|
67
|
+
lnameMatch?: ((value: string) => boolean) | undefined;
|
|
68
|
+
ilnameMatch?: ((value: string) => boolean) | undefined;
|
|
69
|
+
regex?: RegExp | undefined;
|
|
70
|
+
iregex?: RegExp | undefined;
|
|
71
|
+
newer?: number | undefined;
|
|
72
|
+
newerXY?: NewerXY | undefined;
|
|
73
|
+
samefile?: { dev: number; ino: number } | undefined;
|
|
74
|
+
uid?: number | null | undefined;
|
|
75
|
+
gid?: number | null | undefined;
|
|
76
|
+
fstype?: string | undefined;
|
|
77
|
+
fstypeCache: Map<string, string>;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const FS_TYPES = new Map<number, string>([
|
|
81
|
+
[0xef53, "ext4"],
|
|
82
|
+
[0x01021994, "tmpfs"],
|
|
83
|
+
[0x794c7630, "overlay"],
|
|
84
|
+
[0x58465342, "xfs"],
|
|
85
|
+
[0x9123683e, "btrfs"],
|
|
86
|
+
[0x6969, "nfs"],
|
|
87
|
+
[0xff534d42, "cifs"],
|
|
88
|
+
[0xfe534d42, "smb2"],
|
|
89
|
+
[0x65735546, "fuse"],
|
|
90
|
+
[0x01021997, "9p"],
|
|
91
|
+
[0x858458f6, "ramfs"],
|
|
92
|
+
[0x9fa0, "proc"],
|
|
93
|
+
[0x62656572, "sysfs"],
|
|
94
|
+
[0x1cd1, "devtmpfs"],
|
|
95
|
+
[0x73717368, "squashfs"],
|
|
96
|
+
[0x2fc12fc1, "zfs"],
|
|
97
|
+
[0x4d44, "vfat"],
|
|
98
|
+
[0x2011bab0, "exfat"],
|
|
99
|
+
]);
|
|
100
|
+
|
|
101
|
+
let userMap: Map<string, number> | undefined;
|
|
102
|
+
let groupMap: Map<string, number> | undefined;
|
|
103
|
+
|
|
42
104
|
export const findTool: ToolSpec<Input> = {
|
|
43
105
|
name: "find",
|
|
44
106
|
description:
|
|
45
|
-
"Find entries with
|
|
46
|
-
"`-size`, `-mtime`, `-mmin`, `-maxdepth`, `-mindepth`, `-empty`, `-perm`,
|
|
107
|
+
"Find entries with Linux-like predicates: `-name`, `-iname`, `-path`, `-lname`, `-regex`, " +
|
|
108
|
+
"`-type`, `-size`, `-mtime`, `-mmin`, `-maxdepth`, `-mindepth`, `-empty`, `-perm`, " +
|
|
109
|
+
"`-uid`, `-gid`, `-user`, `-group`, `-links`, `-inum`, `-samefile`, `-fstype`, `-newer`, " +
|
|
110
|
+
"`-newerXY`, `-printf`, `-L`, `-print0`.",
|
|
47
111
|
schema: Schema,
|
|
48
112
|
pipeable: false,
|
|
49
113
|
mutates: false,
|
|
50
114
|
async run(ctx, input) {
|
|
51
115
|
/* v8 ignore next */
|
|
52
116
|
const paths = input.paths ?? ["."];
|
|
53
|
-
const
|
|
54
|
-
? undefined
|
|
55
|
-
:
|
|
56
|
-
|
|
57
|
-
? undefined
|
|
58
|
-
: picomatch(input.
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
:
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
117
|
+
const patterns: Patterns = {
|
|
118
|
+
nameMatch: input.name === undefined ? undefined : picomatch(input.name, { dot: true }),
|
|
119
|
+
inameMatch: input.iname === undefined ? undefined : picomatch(input.iname, { dot: true, nocase: true }),
|
|
120
|
+
pathMatch: input.pathPattern === undefined ? undefined : picomatch(input.pathPattern, { dot: true }),
|
|
121
|
+
lnameMatch: input.lname === undefined ? undefined : picomatch(input.lname, { dot: true }),
|
|
122
|
+
ilnameMatch: input.ilname === undefined ? undefined : picomatch(input.ilname, { dot: true, nocase: true }),
|
|
123
|
+
regex: input.regex === undefined ? undefined : new RegExp(input.regex),
|
|
124
|
+
iregex: input.iregex === undefined ? undefined : new RegExp(input.iregex, "i"),
|
|
125
|
+
fstype: input.fstype,
|
|
126
|
+
fstypeCache: new Map(),
|
|
127
|
+
};
|
|
128
|
+
if (input.newer !== undefined) {
|
|
129
|
+
const reference = await referenceStats(ctx, input.newer);
|
|
130
|
+
patterns.newer = num(reference.mtimeMs);
|
|
131
|
+
}
|
|
132
|
+
if (input.newerXY !== undefined) patterns.newerXY = await parseNewerXY(ctx, input.newerXY);
|
|
133
|
+
if (input.samefile !== undefined) {
|
|
134
|
+
const reference = await referenceStats(ctx, input.samefile);
|
|
135
|
+
patterns.samefile = { dev: num(reference.dev), ino: num(reference.ino) };
|
|
136
|
+
}
|
|
137
|
+
patterns.uid = input.uid ?? await resolveId(input.user, "user");
|
|
138
|
+
patterns.gid = input.gid ?? await resolveId(input.group, "group");
|
|
68
139
|
|
|
140
|
+
const results: string[] = [];
|
|
69
141
|
for (const requested of paths) {
|
|
70
142
|
const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
|
|
71
143
|
await ctx.permission.assert([{ target, boundary: target.full }]);
|
|
@@ -75,17 +147,15 @@ export const findTool: ToolSpec<Input> = {
|
|
|
75
147
|
: await ctx.sandbox.lstat(target.full, requested);
|
|
76
148
|
/* v8 ignore next */
|
|
77
149
|
if (!rootStats.isDirectory()) {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
results.push(requested);
|
|
150
|
+
if (await matches(target.full, rootStats, input, patterns, 0)) {
|
|
151
|
+
results.push(await render(requested, target.full, rootStats, input, patterns, target.full, 0));
|
|
81
152
|
}
|
|
82
153
|
continue;
|
|
83
154
|
}
|
|
84
155
|
/* v8 ignore next */
|
|
85
156
|
if (input.maxDepth === 0) {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
results.push(requested);
|
|
157
|
+
if (await matches(target.full, rootStats, input, patterns, 0)) {
|
|
158
|
+
results.push(await render(requested, target.full, rootStats, input, patterns, target.full, 0));
|
|
89
159
|
}
|
|
90
160
|
continue;
|
|
91
161
|
}
|
|
@@ -96,14 +166,18 @@ export const findTool: ToolSpec<Input> = {
|
|
|
96
166
|
includeHidden: true,
|
|
97
167
|
signal: ctx.signal,
|
|
98
168
|
})) {
|
|
99
|
-
const relative = path.relative(target.full, entry.path)
|
|
100
|
-
|
|
101
|
-
if (
|
|
102
|
-
|
|
169
|
+
const relative = path.relative(target.full, entry.path);
|
|
170
|
+
const depth = relative.split(path.sep).length;
|
|
171
|
+
if (input.minDepth !== undefined && depth < input.minDepth) continue;
|
|
172
|
+
if (await matches(entry.path, entry.stats, input, patterns, depth)) {
|
|
173
|
+
results.push(await render(entry.path, entry.path, entry.stats, input, patterns, target.full, depth));
|
|
103
174
|
}
|
|
104
175
|
}
|
|
105
176
|
}
|
|
106
177
|
if (input.sort !== false) results.sort((a, b) => a.localeCompare(b));
|
|
178
|
+
if (input.printf !== undefined) {
|
|
179
|
+
return textResult(results.join(""), { found: results.length });
|
|
180
|
+
}
|
|
107
181
|
const separator = input.print0 === true ? "\0" : "\n";
|
|
108
182
|
/* v8 ignore next */
|
|
109
183
|
const text = results.length === 0 ? "" : results.join(separator) + separator;
|
|
@@ -115,42 +189,32 @@ async function matches(
|
|
|
115
189
|
full: string,
|
|
116
190
|
stats: Awaited<ReturnType<typeof fs.lstat>>,
|
|
117
191
|
input: Input,
|
|
118
|
-
patterns:
|
|
119
|
-
|
|
120
|
-
inameMatch?: ((value: string) => boolean) | undefined;
|
|
121
|
-
pathMatch?: ((value: string) => boolean) | undefined;
|
|
122
|
-
newer?: number | undefined;
|
|
123
|
-
},
|
|
192
|
+
patterns: Patterns,
|
|
193
|
+
depth: number,
|
|
124
194
|
): Promise<boolean> {
|
|
125
195
|
const base = path.basename(full);
|
|
126
196
|
if (patterns.nameMatch !== undefined && !patterns.nameMatch(base)) return false;
|
|
127
|
-
/* v8 ignore next */
|
|
128
197
|
if (patterns.inameMatch !== undefined && !patterns.inameMatch(base)) return false;
|
|
129
|
-
/* v8 ignore next */
|
|
130
198
|
if (patterns.pathMatch !== undefined && !patterns.pathMatch(full)) return false;
|
|
199
|
+
if (patterns.regex !== undefined && !patterns.regex.test(full)) return false;
|
|
200
|
+
if (patterns.iregex !== undefined && !patterns.iregex.test(full)) return false;
|
|
131
201
|
if (input.type !== undefined && typeOf(stats) !== input.type) return false;
|
|
132
202
|
if (input.size !== undefined) {
|
|
133
|
-
/* v8 ignore next 3 */
|
|
134
203
|
const sign = input.size.startsWith("+") ? 1 : input.size.startsWith("-") ? -1 : 0;
|
|
135
204
|
const body = sign === 0 ? input.size : input.size.slice(1);
|
|
136
205
|
const size = parseSize(body);
|
|
137
|
-
/* v8 ignore next */
|
|
138
206
|
if (sign === 1 && stats.size <= size) return false;
|
|
139
|
-
/* v8 ignore next */
|
|
140
207
|
if (sign === -1 && stats.size >= size) return false;
|
|
141
|
-
/* v8 ignore next */
|
|
142
208
|
if (sign === 0 && stats.size !== size) return false;
|
|
143
209
|
}
|
|
144
210
|
if (input.mtime !== undefined) {
|
|
145
211
|
const age = (Date.now() - num(stats.mtimeMs)) / 86_400_000;
|
|
146
212
|
if (!ageMatches(age, input.mtime)) return false;
|
|
147
213
|
}
|
|
148
|
-
/* v8 ignore next 4 */
|
|
149
214
|
if (input.mmin !== undefined) {
|
|
150
215
|
const age = (Date.now() - num(stats.mtimeMs)) / 60_000;
|
|
151
216
|
if (!ageMatches(age, input.mmin)) return false;
|
|
152
217
|
}
|
|
153
|
-
/* v8 ignore next 6 */
|
|
154
218
|
if (input.empty === true) {
|
|
155
219
|
if (stats.isDirectory()) {
|
|
156
220
|
if ((await fs.readdir(full)).length > 0) return false;
|
|
@@ -158,9 +222,205 @@ async function matches(
|
|
|
158
222
|
}
|
|
159
223
|
if (input.perm !== undefined && (num(stats.mode) & 0o7777) !== Number.parseInt(input.perm, 8)) return false;
|
|
160
224
|
if (patterns.newer !== undefined && num(stats.mtimeMs) <= patterns.newer) return false;
|
|
225
|
+
if (patterns.newerXY !== undefined && timeValue(stats, patterns.newerXY.x) <= patterns.newerXY.value) return false;
|
|
226
|
+
if (patterns.samefile !== undefined) {
|
|
227
|
+
if (num(stats.dev) !== patterns.samefile.dev || num(stats.ino) !== patterns.samefile.ino) return false;
|
|
228
|
+
}
|
|
229
|
+
if (patterns.uid !== undefined) {
|
|
230
|
+
if (patterns.uid === null || num(stats.uid) !== patterns.uid) return false;
|
|
231
|
+
}
|
|
232
|
+
if (patterns.gid !== undefined) {
|
|
233
|
+
if (patterns.gid === null || num(stats.gid) !== patterns.gid) return false;
|
|
234
|
+
}
|
|
235
|
+
if (input.links !== undefined && !countMatches(num(stats.nlink), input.links)) return false;
|
|
236
|
+
if (input.inum !== undefined && num(stats.ino) !== input.inum) return false;
|
|
237
|
+
if (patterns.lnameMatch !== undefined || patterns.ilnameMatch !== undefined) {
|
|
238
|
+
if (!stats.isSymbolicLink()) return false;
|
|
239
|
+
/* v8 ignore next -- a symlink readable by lstat is normally readable here */
|
|
240
|
+
const target = await fs.readlink(full).catch(() => "");
|
|
241
|
+
if (patterns.lnameMatch !== undefined && !patterns.lnameMatch(target)) return false;
|
|
242
|
+
if (patterns.ilnameMatch !== undefined && !patterns.ilnameMatch(target)) return false;
|
|
243
|
+
}
|
|
244
|
+
if (patterns.fstype !== undefined) {
|
|
245
|
+
const type = await filesystemType(full, stats, patterns.fstypeCache);
|
|
246
|
+
if (type !== patterns.fstype) return false;
|
|
247
|
+
}
|
|
248
|
+
void depth;
|
|
161
249
|
return true;
|
|
162
250
|
}
|
|
163
251
|
|
|
252
|
+
async function render(
|
|
253
|
+
display: string,
|
|
254
|
+
full: string,
|
|
255
|
+
stats: Awaited<ReturnType<typeof fs.lstat>>,
|
|
256
|
+
input: Input,
|
|
257
|
+
patterns: Patterns,
|
|
258
|
+
root: string,
|
|
259
|
+
depth: number,
|
|
260
|
+
): Promise<string> {
|
|
261
|
+
if (input.printf === undefined) return display;
|
|
262
|
+
return printf(display, full, stats, input, patterns, root, depth);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function referenceStats(
|
|
266
|
+
ctx: Parameters<ToolSpec<Input>["run"]>[0],
|
|
267
|
+
reference: string,
|
|
268
|
+
): Promise<Awaited<ReturnType<typeof fs.lstat>>> {
|
|
269
|
+
const target = await ctx.sandbox.resolveExisting(reference, { allowRoot: true });
|
|
270
|
+
await ctx.permission.assert([{ target, boundary: target.full }]);
|
|
271
|
+
return ctx.sandbox.lstat(target.full, reference);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async function parseNewerXY(
|
|
275
|
+
ctx: Parameters<ToolSpec<Input>["run"]>[0],
|
|
276
|
+
expression: string,
|
|
277
|
+
): Promise<NewerXY> {
|
|
278
|
+
const match = /^([acmB])([acmB]):(.+)$/.exec(expression);
|
|
279
|
+
if (match === null) throw new FsError("newerXY must look like mm:/path.", "invalid");
|
|
280
|
+
const reference = await referenceStats(ctx, match[3] as string);
|
|
281
|
+
return { x: match[1] as NewerXY["x"], y: match[2] as NewerXY["y"], value: timeValue(reference, match[2] as NewerXY["y"]) };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const TIME_FIELDS = {
|
|
285
|
+
a: "atimeMs",
|
|
286
|
+
c: "ctimeMs",
|
|
287
|
+
m: "mtimeMs",
|
|
288
|
+
B: "birthtimeMs",
|
|
289
|
+
} as const;
|
|
290
|
+
|
|
291
|
+
function timeValue(stats: Awaited<ReturnType<typeof fs.lstat>>, field: "a" | "c" | "m" | "B"): number {
|
|
292
|
+
return num((stats as unknown as Record<(typeof TIME_FIELDS)[typeof field], number>)[TIME_FIELDS[field]]);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function resolveId(value: string | undefined, kind: "user" | "group"): Promise<number | null | undefined> {
|
|
296
|
+
if (value === undefined) return undefined;
|
|
297
|
+
if (/^\d+$/.test(value)) return Number(value);
|
|
298
|
+
const map = kind === "user" ? await loadUserMap() : await loadGroupMap();
|
|
299
|
+
return map.get(value) ?? null;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async function loadUserMap(): Promise<Map<string, number>> {
|
|
303
|
+
if (userMap !== undefined) return userMap;
|
|
304
|
+
userMap = new Map();
|
|
305
|
+
/* v8 ignore next -- /etc/passwd exists on supported Linux systems */
|
|
306
|
+
const text = await fs.readFile("/etc/passwd", "utf8").catch(() => "");
|
|
307
|
+
for (const line of text.split("\n")) {
|
|
308
|
+
const fields = line.split(":");
|
|
309
|
+
if (fields.length > 2) userMap.set(fields[0] as string, Number(fields[2]));
|
|
310
|
+
}
|
|
311
|
+
return userMap;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function loadGroupMap(): Promise<Map<string, number>> {
|
|
315
|
+
if (groupMap !== undefined) return groupMap;
|
|
316
|
+
groupMap = new Map();
|
|
317
|
+
/* v8 ignore next -- /etc/group exists on supported Linux systems */
|
|
318
|
+
const text = await fs.readFile("/etc/group", "utf8").catch(() => "");
|
|
319
|
+
for (const line of text.split("\n")) {
|
|
320
|
+
const fields = line.split(":");
|
|
321
|
+
if (fields.length > 2) groupMap.set(fields[0] as string, Number(fields[2]));
|
|
322
|
+
}
|
|
323
|
+
return groupMap;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
async function filesystemType(
|
|
327
|
+
full: string,
|
|
328
|
+
stats: Awaited<ReturnType<typeof fs.lstat>>,
|
|
329
|
+
cache: Map<string, string>,
|
|
330
|
+
): Promise<string> {
|
|
331
|
+
const key = String(stats.dev);
|
|
332
|
+
const cached = cache.get(key);
|
|
333
|
+
if (cached !== undefined) return cached;
|
|
334
|
+
let name = "unknown";
|
|
335
|
+
try {
|
|
336
|
+
const fsStats = await fs.statfs(full);
|
|
337
|
+
/* v8 ignore next -- unknown filesystems fall back to their numeric magic */
|
|
338
|
+
name = FS_TYPES.get(Number(fsStats.type)) ?? `0x${Number(fsStats.type).toString(16)}`;
|
|
339
|
+
} catch {}
|
|
340
|
+
cache.set(key, name);
|
|
341
|
+
return name;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
async function printf(
|
|
345
|
+
display: string,
|
|
346
|
+
full: string,
|
|
347
|
+
stats: Awaited<ReturnType<typeof fs.lstat>>,
|
|
348
|
+
input: Input,
|
|
349
|
+
patterns: Patterns,
|
|
350
|
+
root: string,
|
|
351
|
+
depth: number,
|
|
352
|
+
): Promise<string> {
|
|
353
|
+
/* v8 ignore next -- a symlink readable by lstat is normally readable here */
|
|
354
|
+
const link = stats.isSymbolicLink() ? await fs.readlink(full).catch(() => "") : "";
|
|
355
|
+
const relative = path.relative(root, full);
|
|
356
|
+
const values: Record<string, string> = {
|
|
357
|
+
p: display,
|
|
358
|
+
f: path.basename(display),
|
|
359
|
+
h: path.dirname(display),
|
|
360
|
+
P: relative,
|
|
361
|
+
s: String(num(stats.size)),
|
|
362
|
+
m: (num(stats.mode) & 0o7777).toString(8),
|
|
363
|
+
M: modeString(stats),
|
|
364
|
+
u: String(num(stats.uid)),
|
|
365
|
+
U: await lookupUser(num(stats.uid)),
|
|
366
|
+
g: String(num(stats.gid)),
|
|
367
|
+
G: await lookupGroup(num(stats.gid)),
|
|
368
|
+
y: typeOf(stats),
|
|
369
|
+
Y: typeName(stats),
|
|
370
|
+
i: String(num(stats.ino)),
|
|
371
|
+
n: String(num(stats.nlink)),
|
|
372
|
+
d: String(depth),
|
|
373
|
+
l: link,
|
|
374
|
+
b: String(num(stats.blocks)),
|
|
375
|
+
k: String(Math.ceil(num(stats.blocks) / 2)),
|
|
376
|
+
D: String(num(stats.dev)),
|
|
377
|
+
F: await filesystemType(full, stats, patterns.fstypeCache),
|
|
378
|
+
a: stats.atime.toISOString(),
|
|
379
|
+
A: stats.atime.toISOString(),
|
|
380
|
+
c: stats.ctime.toISOString(),
|
|
381
|
+
C: stats.ctime.toISOString(),
|
|
382
|
+
t: stats.mtime.toISOString(),
|
|
383
|
+
T: stats.mtime.toISOString(),
|
|
384
|
+
};
|
|
385
|
+
const format = input.printf as string;
|
|
386
|
+
let output = "";
|
|
387
|
+
for (let index = 0; index < format.length; index++) {
|
|
388
|
+
const char = format[index] as string;
|
|
389
|
+
if (char === "\\") {
|
|
390
|
+
const escaped = format[++index] as string | undefined;
|
|
391
|
+
output += escaped === "n" ? "\n" : escaped === "t" ? "\t" : escaped === "0" ? "\0" : escaped === "\\" ? "\\" : `\\${escaped ?? ""}`;
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
if (char !== "%") {
|
|
395
|
+
output += char;
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
const next = format[++index] as string | undefined;
|
|
399
|
+
if (next === undefined) {
|
|
400
|
+
output += "%";
|
|
401
|
+
break;
|
|
402
|
+
}
|
|
403
|
+
if (next === "%") {
|
|
404
|
+
output += "%";
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
407
|
+
if ((next === "A" || next === "C" || next === "T") && format[index + 1] === "@") {
|
|
408
|
+
const value = next === "A" ? stats.atimeMs : next === "C" ? stats.ctimeMs : stats.mtimeMs;
|
|
409
|
+
output += String(Math.floor(num(value) / 1000));
|
|
410
|
+
index++;
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
output += values[next] ?? `%${next}`;
|
|
414
|
+
}
|
|
415
|
+
return output;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function countMatches(value: number, expression: string): boolean {
|
|
419
|
+
if (expression.startsWith("+")) return value > Number(expression.slice(1));
|
|
420
|
+
if (expression.startsWith("-")) return value < Number(expression.slice(1));
|
|
421
|
+
return value === Number(expression);
|
|
422
|
+
}
|
|
423
|
+
|
|
164
424
|
function ageMatches(age: number, expression: string): boolean {
|
|
165
425
|
if (expression.startsWith("+")) return age > Number(expression.slice(1));
|
|
166
426
|
if (expression.startsWith("-")) return age < Number(expression.slice(1));
|
|
@@ -177,5 +437,3 @@ function typeOf(stats: Awaited<ReturnType<typeof fs.lstat>>): string {
|
|
|
177
437
|
if (stats.isSocket()) return "s";
|
|
178
438
|
return "f";
|
|
179
439
|
}
|
|
180
|
-
|
|
181
|
-
|
package/src/tools/ls.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import * as fs from "node:fs/promises";
|
|
7
7
|
import * as path from "node:path";
|
|
8
|
+
import picomatch from "picomatch";
|
|
8
9
|
import { Type, type Static } from "@sinclair/typebox";
|
|
9
10
|
import { FsError, fromErrno } from "../core/errors.js";
|
|
10
11
|
import { formatDate, lookupGroup, lookupUser, modeString, num, typeName } from "../core/fsutil.js";
|
|
@@ -22,6 +23,24 @@ const Schema = Type.Object(
|
|
|
22
23
|
directory: Type.Optional(Type.Boolean({ description: "List directories themselves, not their contents (`-d`)." })),
|
|
23
24
|
inode: Type.Optional(Type.Boolean({ description: "Print inode numbers (`-i`)." })),
|
|
24
25
|
classify: Type.Optional(Type.Boolean({ description: "Append file type indicators (`-F`)." })),
|
|
26
|
+
size: Type.Optional(Type.Boolean({ description: "Print allocated block counts (`-s`)." })),
|
|
27
|
+
numericIds: Type.Optional(Type.Boolean({ description: "Use numeric uid/gid and long format (`-n`)." })),
|
|
28
|
+
noGroup: Type.Optional(Type.Boolean({ description: "Long format without group (`-g`)." })),
|
|
29
|
+
noOwner: Type.Optional(Type.Boolean({ description: "Long format without owner (`-o`)." })),
|
|
30
|
+
slash: Type.Optional(Type.Boolean({ description: "Append `/` to directories (`-p`)." })),
|
|
31
|
+
quote: Type.Optional(Type.Boolean({ description: "Quote names with C-style escapes (`-Q`)." })),
|
|
32
|
+
versionSort: Type.Optional(Type.Boolean({ description: "Natural version sort (`-v`)." })),
|
|
33
|
+
extensionSort: Type.Optional(Type.Boolean({ description: "Sort by extension (`-X`)." })),
|
|
34
|
+
fullTime: Type.Optional(Type.Boolean({ description: "Full ISO timestamps (`--full-time`)." })),
|
|
35
|
+
timeStyle: Type.Optional(
|
|
36
|
+
Type.Union(
|
|
37
|
+
[Type.Literal("full-iso"), Type.Literal("long-iso"), Type.Literal("iso"), Type.Literal("locale")],
|
|
38
|
+
{ description: "Timestamp style (`--time-style`)." },
|
|
39
|
+
),
|
|
40
|
+
),
|
|
41
|
+
hide: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Hide matching names (`--hide`)." })),
|
|
42
|
+
ignore: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Ignore matching names (`--ignore`)." })),
|
|
43
|
+
groupDirectoriesFirst: Type.Optional(Type.Boolean({ description: "List directories before files (`--group-directories-first`)." })),
|
|
25
44
|
sortBy: Type.Optional(
|
|
26
45
|
Type.Union([Type.Literal("name"), Type.Literal("size"), Type.Literal("time"), Type.Literal("none")], {
|
|
27
46
|
description: "Sort key. Default: name.",
|
|
@@ -115,6 +134,11 @@ async function readEntries(full: string, input: Input): Promise<Entry[]> {
|
|
|
115
134
|
}
|
|
116
135
|
if (input.all === true) names = [".", "..", ...names];
|
|
117
136
|
else if (input.almostAll !== true) names = names.filter((name) => !name.startsWith("."));
|
|
137
|
+
const hidden = input.hide?.map((pattern) => picomatch(pattern, { dot: true }));
|
|
138
|
+
const ignored = input.ignore?.map((pattern) => picomatch(pattern, { dot: true }));
|
|
139
|
+
names = names.filter((name) =>
|
|
140
|
+
hidden?.some((match) => match(name)) !== true &&
|
|
141
|
+
ignored?.some((match) => match(name)) !== true);
|
|
118
142
|
const entries: Entry[] = [];
|
|
119
143
|
for (const name of names) {
|
|
120
144
|
const target = path.join(full, name);
|
|
@@ -134,35 +158,106 @@ async function readEntries(full: string, input: Input): Promise<Entry[]> {
|
|
|
134
158
|
|
|
135
159
|
function sortEntries(entries: Entry[], input: Input): Entry[] {
|
|
136
160
|
const sortBy = input.sortBy ?? "name";
|
|
137
|
-
if (sortBy !== "none") {
|
|
161
|
+
if (sortBy !== "none" || input.versionSort === true || input.extensionSort === true) {
|
|
138
162
|
entries.sort((a, b) => {
|
|
139
|
-
if (
|
|
140
|
-
|
|
163
|
+
if (input.extensionSort === true) {
|
|
164
|
+
const extension = path.extname(a.name).localeCompare(path.extname(b.name));
|
|
165
|
+
if (extension !== 0) return extension;
|
|
166
|
+
} else if (input.versionSort === true) {
|
|
167
|
+
return versionCompare(a.name, b.name);
|
|
168
|
+
} else if (sortBy === "size") {
|
|
169
|
+
return num(a.stats.size) - num(b.stats.size);
|
|
170
|
+
} else if (sortBy === "time") {
|
|
171
|
+
return num(a.stats.mtimeMs) - num(b.stats.mtimeMs);
|
|
172
|
+
}
|
|
141
173
|
return a.name.localeCompare(b.name);
|
|
142
174
|
});
|
|
143
175
|
}
|
|
144
176
|
if (input.reverse === true) entries.reverse();
|
|
177
|
+
if (input.groupDirectoriesFirst === true) {
|
|
178
|
+
entries.sort((a, b) => Number(b.stats.isDirectory()) - Number(a.stats.isDirectory()));
|
|
179
|
+
}
|
|
145
180
|
return entries;
|
|
146
181
|
}
|
|
147
182
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
183
|
+
function versionCompare(left: string, right: string): number {
|
|
184
|
+
/* v8 ignore next -- ls entry names are never empty */
|
|
185
|
+
const leftParts = left.match(/\d+|\D+/g) ?? [];
|
|
186
|
+
/* v8 ignore next -- ls entry names are never empty */
|
|
187
|
+
const rightParts = right.match(/\d+|\D+/g) ?? [];
|
|
188
|
+
const length = Math.max(leftParts.length, rightParts.length);
|
|
189
|
+
for (let index = 0; index < length; index++) {
|
|
190
|
+
const a = leftParts[index];
|
|
191
|
+
const b = rightParts[index];
|
|
192
|
+
/* v8 ignore next */
|
|
193
|
+
if (a === undefined) return -1;
|
|
194
|
+
/* v8 ignore next */
|
|
195
|
+
if (b === undefined) return 1;
|
|
196
|
+
if (/^\d+$/.test(a) && /^\d+$/.test(b)) {
|
|
197
|
+
const difference = Number(a) - Number(b);
|
|
198
|
+
if (difference !== 0) return difference;
|
|
199
|
+
} else {
|
|
200
|
+
const result = a.localeCompare(b);
|
|
201
|
+
if (result !== 0) return result;
|
|
202
|
+
}
|
|
151
203
|
}
|
|
152
|
-
|
|
204
|
+
/* v8 ignore next -- distinct entry names cannot compare fully equal */
|
|
205
|
+
return 0;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function formatEntries(entries: Entry[], input: Input): Promise<string[]> {
|
|
209
|
+
return Promise.all(entries.map((entry) => formatEntry(entry, input)));
|
|
153
210
|
}
|
|
154
211
|
|
|
155
212
|
async function formatEntry(entry: Entry, input: Input): Promise<string> {
|
|
156
|
-
const name =
|
|
213
|
+
const name = displayName(entry.name, entry.stats, input);
|
|
214
|
+
const long = input.long === true || input.numericIds === true || input.noOwner === true || input.noGroup === true;
|
|
157
215
|
/* v8 ignore next */
|
|
158
|
-
if (
|
|
159
|
-
|
|
160
|
-
|
|
216
|
+
if (!long) {
|
|
217
|
+
const inode = input.inode === true ? `${num(entry.stats.ino)} ` : "";
|
|
218
|
+
const blocks = input.size === true ? `${blockSize(entry.stats, input)} ` : "";
|
|
219
|
+
return `${inode}${blocks}${name}`;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const user = input.numericIds === true ? String(num(entry.stats.uid)) : await lookupUser(num(entry.stats.uid));
|
|
223
|
+
const group = input.numericIds === true ? String(num(entry.stats.gid)) : await lookupGroup(num(entry.stats.gid));
|
|
161
224
|
const size = input.human === true ? humanSize(num(entry.stats.size)) : String(num(entry.stats.size));
|
|
162
225
|
const link = entry.link === undefined ? "" : ` -> ${entry.link}`;
|
|
226
|
+
const parts: string[] = [];
|
|
227
|
+
if (input.size === true) parts.push(blockSize(entry.stats, input));
|
|
163
228
|
/* v8 ignore next */
|
|
164
|
-
|
|
165
|
-
|
|
229
|
+
if (input.inode === true) parts.push(String(num(entry.stats.ino)));
|
|
230
|
+
parts.push(modeString(entry.stats), String(num(entry.stats.nlink)).padStart(2));
|
|
231
|
+
if (input.noOwner !== true) parts.push(user);
|
|
232
|
+
if (input.noGroup !== true) parts.push(group);
|
|
233
|
+
parts.push(size.padStart(8), formatTime(entry.stats.mtime, input));
|
|
234
|
+
return `${parts.join(" ")} ${name}${link}`;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function blockSize(stats: Awaited<ReturnType<typeof fs.lstat>>, input: Input): string {
|
|
238
|
+
return input.human === true
|
|
239
|
+
? humanSize(num(stats.blocks) * 512)
|
|
240
|
+
: String(Math.ceil(num(stats.blocks) / 2));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function formatTime(date: Date, input: Input): string {
|
|
244
|
+
if (input.fullTime === true || input.timeStyle === "full-iso") {
|
|
245
|
+
const iso = date.toISOString();
|
|
246
|
+
return `${iso.slice(0, 10)} ${iso.slice(11, 23)}000000 +0000`;
|
|
247
|
+
}
|
|
248
|
+
if (input.timeStyle === "long-iso") return date.toISOString().slice(0, 16).replace("T", " ");
|
|
249
|
+
if (input.timeStyle === "iso") {
|
|
250
|
+
const iso = date.toISOString();
|
|
251
|
+
return `${iso.slice(5, 10)} ${iso.slice(11, 16)}`;
|
|
252
|
+
}
|
|
253
|
+
return formatDate(date);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function displayName(name: string, stats: Awaited<ReturnType<typeof fs.lstat>>, input: Input): string {
|
|
257
|
+
const quoted = input.quote === true ? JSON.stringify(name) : name;
|
|
258
|
+
const classified = classify(quoted, stats, input);
|
|
259
|
+
if (input.slash === true && stats.isDirectory() && !classified.endsWith("/")) return `${classified}/`;
|
|
260
|
+
return classified;
|
|
166
261
|
}
|
|
167
262
|
|
|
168
263
|
function classify(name: string, stats: Awaited<ReturnType<typeof fs.lstat>>, input: Input): string {
|
package/src/tools/pipe.ts
CHANGED
|
@@ -17,10 +17,12 @@ import { headTool } from "./head.js";
|
|
|
17
17
|
import { sedTool } from "./sed.js";
|
|
18
18
|
import { sortTool } from "./sort.js";
|
|
19
19
|
import { tailTool } from "./tail.js";
|
|
20
|
+
import { tarTool } from "./tar.js";
|
|
20
21
|
import { teeTool } from "./tee.js";
|
|
21
22
|
import { trTool } from "./tr.js";
|
|
22
23
|
import { uniqTool } from "./uniq.js";
|
|
23
24
|
import { wcTool } from "./wc.js";
|
|
25
|
+
import { zipTool } from "./zip.js";
|
|
24
26
|
|
|
25
27
|
const Stage = Type.Object(
|
|
26
28
|
{
|
|
@@ -44,9 +46,10 @@ type Input = Static<typeof Schema>;
|
|
|
44
46
|
type AnyTool = ToolSpec<any>;
|
|
45
47
|
|
|
46
48
|
const REGISTRY: ReadonlyMap<string, AnyTool> = new Map(
|
|
47
|
-
[
|
|
48
|
-
|
|
49
|
-
|
|
49
|
+
[
|
|
50
|
+
catTool, headTool, tailTool, grepTool, sedTool, sortTool, uniqTool, cutTool,
|
|
51
|
+
trTool, wcTool, teeTool, hashTool, gzipTool, gunzipTool, tarTool, zipTool,
|
|
52
|
+
].map((tool) => [tool.name, tool]),
|
|
50
53
|
);
|
|
51
54
|
|
|
52
55
|
export const pipeTool: ToolSpec<Input> = {
|