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