opencode-fs-plugin 0.0.0-stage → 1.0.2
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 +186 -0
- package/LICENSE +225 -0
- package/README.md +266 -2
- package/SPEC.md +45 -0
- package/package.json +63 -4
- package/skills/filesystem/SKILL.md +153 -0
- package/src/core/errors.ts +81 -0
- package/src/core/format.ts +100 -0
- package/src/core/fsutil.ts +228 -0
- package/src/core/mode.ts +107 -0
- package/src/core/parallel.ts +76 -0
- package/src/core/permissions.ts +134 -0
- package/src/core/sandbox.ts +270 -0
- package/src/core/schema.ts +16 -0
- package/src/core/stream.ts +84 -0
- package/src/core/types.ts +51 -0
- package/src/index.ts +172 -0
- package/src/tools/cat.ts +90 -0
- package/src/tools/chmod.ts +93 -0
- package/src/tools/cp.ts +136 -0
- package/src/tools/cut.ts +93 -0
- package/src/tools/df.ts +78 -0
- package/src/tools/diff.ts +136 -0
- package/src/tools/du.ts +102 -0
- package/src/tools/find.ts +181 -0
- package/src/tools/grep.ts +205 -0
- package/src/tools/gzip.ts +164 -0
- package/src/tools/hash.ts +84 -0
- package/src/tools/head.ts +78 -0
- package/src/tools/ln.ts +98 -0
- package/src/tools/ls.ts +178 -0
- package/src/tools/mkdir.ts +70 -0
- package/src/tools/mktemp.ts +83 -0
- package/src/tools/mv.ts +135 -0
- package/src/tools/pipe.ts +107 -0
- package/src/tools/readlink.ts +90 -0
- package/src/tools/rm.ts +91 -0
- package/src/tools/rmdir.ts +117 -0
- package/src/tools/sed.ts +151 -0
- package/src/tools/sort.ts +73 -0
- package/src/tools/stat.ts +157 -0
- package/src/tools/tail.ts +74 -0
- package/src/tools/tar.ts +195 -0
- package/src/tools/tee.ts +51 -0
- package/src/tools/touch.ts +130 -0
- package/src/tools/tr.ts +123 -0
- package/src/tools/trash.ts +86 -0
- package/src/tools/truncate.ts +96 -0
- package/src/tools/uniq.ts +76 -0
- package/src/tools/wc.ts +97 -0
- package/src/tools/zip.ts +231 -0
package/src/tools/df.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as fs from "node:fs/promises";
|
|
7
|
+
import { Type, type Static } from "@sinclair/typebox";
|
|
8
|
+
import { fromErrno } from "../core/errors.js";
|
|
9
|
+
import { humanSize } from "../core/format.js";
|
|
10
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
11
|
+
|
|
12
|
+
const Schema = Type.Object(
|
|
13
|
+
{
|
|
14
|
+
paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Filesystems to report. Default: ['.']." })),
|
|
15
|
+
human: Type.Optional(Type.Boolean({ description: "Human-readable sizes (`-h`)." })),
|
|
16
|
+
inodes: Type.Optional(Type.Boolean({ description: "Report inode usage (`-i`)." })),
|
|
17
|
+
printType: Type.Optional(Type.Boolean({ description: "Print the filesystem type (`-T`)." })),
|
|
18
|
+
all: Type.Optional(Type.Boolean({ description: "Include pseudo filesystems (`-a`)." })),
|
|
19
|
+
},
|
|
20
|
+
{ additionalProperties: false },
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
type Input = Static<typeof Schema>;
|
|
24
|
+
|
|
25
|
+
export const dfTool: ToolSpec<Input> = {
|
|
26
|
+
name: "df",
|
|
27
|
+
description:
|
|
28
|
+
"Report filesystem space usage with Linux `df` semantics (`-h`, `-i`, `-T`, `-a`).",
|
|
29
|
+
schema: Schema,
|
|
30
|
+
pipeable: false,
|
|
31
|
+
mutates: false,
|
|
32
|
+
async run(ctx, input) {
|
|
33
|
+
const paths = input.paths ?? ["."];
|
|
34
|
+
const rows: string[] = [];
|
|
35
|
+
const typeHeader = input.printType === true ? "Type " : "";
|
|
36
|
+
rows.push(
|
|
37
|
+
input.inodes === true
|
|
38
|
+
? `${typeHeader}Filesystem Inodes IUsed IFree IUse% Mounted on`
|
|
39
|
+
: `${typeHeader}Filesystem Size Used Avail Use% Mounted on`,
|
|
40
|
+
);
|
|
41
|
+
for (const requested of paths) {
|
|
42
|
+
const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
|
|
43
|
+
await ctx.permission.assert([{ target, boundary: target.full }]);
|
|
44
|
+
let stats;
|
|
45
|
+
try {
|
|
46
|
+
stats = await fs.statfs(target.full);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
/* v8 ignore next */
|
|
49
|
+
throw fromErrno(error, "access");
|
|
50
|
+
}
|
|
51
|
+
const type = input.printType === true ? `${Number(stats.type).toString(16)} ` : "";
|
|
52
|
+
if (input.inodes === true) {
|
|
53
|
+
const used = stats.files - stats.ffree;
|
|
54
|
+
/* v8 ignore next */
|
|
55
|
+
const percent = stats.files === 0 ? 0 : Math.ceil((used / stats.files) * 100);
|
|
56
|
+
rows.push(`${type}${requested} ${stats.files} ${used} ${stats.ffree} ${percent}% ${requested}`);
|
|
57
|
+
} else {
|
|
58
|
+
const total = stats.blocks * stats.bsize;
|
|
59
|
+
const free = stats.bfree * stats.bsize;
|
|
60
|
+
const available = stats.bavail * stats.bsize;
|
|
61
|
+
const used = total - free;
|
|
62
|
+
/* v8 ignore next */
|
|
63
|
+
const percent = total === 0 ? 0 : Math.ceil((used / total) * 100);
|
|
64
|
+
rows.push(
|
|
65
|
+
`${type}${requested} ${size(total, input.human === true)} ${size(used, input.human === true)} ${size(available, input.human === true)} ${percent}% ${requested}`,
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return textResult(rows.join("\n") + "\n", { paths });
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
function size(bytes: number, human: boolean): string {
|
|
74
|
+
if (human) return humanSize(bytes);
|
|
75
|
+
return String(Math.ceil(bytes / 1024));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as fs from "node:fs/promises";
|
|
7
|
+
import * as path from "node:path";
|
|
8
|
+
import { createTwoFilesPatch } from "diff";
|
|
9
|
+
import { Type, type Static } from "@sinclair/typebox";
|
|
10
|
+
import { fromErrno } from "../core/errors.js";
|
|
11
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
12
|
+
|
|
13
|
+
const Schema = Type.Object(
|
|
14
|
+
{
|
|
15
|
+
left: Type.String({ minLength: 1 }),
|
|
16
|
+
right: Type.String({ minLength: 1 }),
|
|
17
|
+
unified: Type.Optional(Type.Integer({ minimum: 0, description: "Context lines (`-U`). Default: 3." })),
|
|
18
|
+
brief: Type.Optional(Type.Boolean({ description: "Only report whether files differ (`-q`)." })),
|
|
19
|
+
recursive: Type.Optional(Type.Boolean({ description: "Compare directories recursively (`-r`)." })),
|
|
20
|
+
ignoreWhitespace: Type.Optional(Type.Boolean({ description: "Ignore whitespace changes (`-w`)." })),
|
|
21
|
+
ignoreCase: Type.Optional(Type.Boolean({ description: "Ignore case (`-i`)." })),
|
|
22
|
+
exclude: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Exclude globs for directories." })),
|
|
23
|
+
},
|
|
24
|
+
{ additionalProperties: false },
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
type Input = Static<typeof Schema>;
|
|
28
|
+
|
|
29
|
+
export const diffTool: ToolSpec<Input> = {
|
|
30
|
+
name: "diff",
|
|
31
|
+
description:
|
|
32
|
+
"Compare files or directories with common `diff` semantics (`-u`, `-q`, `-r`, `-w`, `-i`, " +
|
|
33
|
+
"`-U`, `--exclude`). Differences return exit code 1.",
|
|
34
|
+
schema: Schema,
|
|
35
|
+
pipeable: false,
|
|
36
|
+
mutates: false,
|
|
37
|
+
async run(ctx, input) {
|
|
38
|
+
const left = await ctx.sandbox.resolveExisting(input.left, { allowRoot: true });
|
|
39
|
+
const right = await ctx.sandbox.resolveExisting(input.right, { allowRoot: true });
|
|
40
|
+
await ctx.permission.assert([
|
|
41
|
+
{ target: left, boundary: left.full },
|
|
42
|
+
{ target: right, boundary: right.full },
|
|
43
|
+
]);
|
|
44
|
+
const leftStats = await ctx.sandbox.lstat(left.full, input.left);
|
|
45
|
+
const rightStats = await ctx.sandbox.lstat(right.full, input.right);
|
|
46
|
+
if (leftStats.isDirectory() || rightStats.isDirectory()) {
|
|
47
|
+
if (leftStats.isDirectory() !== rightStats.isDirectory()) {
|
|
48
|
+
return textResult(`File ${input.left} is a directory while file ${input.right} is not\n`, {}, 1);
|
|
49
|
+
}
|
|
50
|
+
if (input.recursive !== true) {
|
|
51
|
+
return textResult(`Common subdirectories: ${input.left} and ${input.right}\n`, {}, 1);
|
|
52
|
+
}
|
|
53
|
+
const lines = await diffDirs(left.full, right.full, input);
|
|
54
|
+
return textResult(lines.join(""), { differences: lines.length > 0 }, lines.length > 0 ? 1 : 0);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/* v8 ignore next */
|
|
58
|
+
const leftData = await fs.readFile(left.full).catch((error) => {
|
|
59
|
+
throw fromErrno(error);
|
|
60
|
+
});
|
|
61
|
+
/* v8 ignore next */
|
|
62
|
+
const rightData = await fs.readFile(right.full).catch((error) => {
|
|
63
|
+
throw fromErrno(error);
|
|
64
|
+
});
|
|
65
|
+
if (leftData.equals(rightData)) return textResult("", { differences: false }, 0);
|
|
66
|
+
if (leftData.includes(0) || rightData.includes(0)) {
|
|
67
|
+
return textResult(`Binary files ${input.left} and ${input.right} differ\n`, { differences: true }, 1);
|
|
68
|
+
}
|
|
69
|
+
if (input.brief === true) {
|
|
70
|
+
return textResult(`Files ${input.left} and ${input.right} differ\n`, { differences: true }, 1);
|
|
71
|
+
}
|
|
72
|
+
let oldText = leftData.toString("utf8");
|
|
73
|
+
let newText = rightData.toString("utf8");
|
|
74
|
+
if (input.ignoreCase === true) {
|
|
75
|
+
oldText = oldText.toLowerCase();
|
|
76
|
+
newText = newText.toLowerCase();
|
|
77
|
+
}
|
|
78
|
+
if (input.ignoreWhitespace === true) {
|
|
79
|
+
oldText = oldText.replace(/\s+/g, "");
|
|
80
|
+
newText = newText.replace(/\s+/g, "");
|
|
81
|
+
}
|
|
82
|
+
if (oldText === newText) return textResult("", { differences: false }, 0);
|
|
83
|
+
const patch = createTwoFilesPatch(input.left, input.right, oldText, newText, "", "", {
|
|
84
|
+
context: input.unified ?? 3,
|
|
85
|
+
});
|
|
86
|
+
return textResult(patch, { differences: true }, 1);
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
async function diffDirs(left: string, right: string, input: Input): Promise<string[]> {
|
|
91
|
+
const names = new Set<string>();
|
|
92
|
+
for (const dir of [left, right]) {
|
|
93
|
+
for (const name of await fs.readdir(dir)) {
|
|
94
|
+
if (input.exclude?.some((pattern) => name.includes(pattern.replaceAll("*", ""))) === true) continue;
|
|
95
|
+
names.add(name);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const output: string[] = [];
|
|
99
|
+
for (const name of [...names].sort()) {
|
|
100
|
+
const leftPath = path.join(left, name);
|
|
101
|
+
const rightPath = path.join(right, name);
|
|
102
|
+
const leftExists = await exists(leftPath);
|
|
103
|
+
const rightExists = await exists(rightPath);
|
|
104
|
+
if (!leftExists || !rightExists) {
|
|
105
|
+
/* v8 ignore next */
|
|
106
|
+
output.push(`Only in ${leftExists ? left : right}: ${name}\n`);
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
const leftStats = await fs.lstat(leftPath);
|
|
110
|
+
const rightStats = await fs.lstat(rightPath);
|
|
111
|
+
if (leftStats.isDirectory() && rightStats.isDirectory()) {
|
|
112
|
+
output.push(...(await diffDirs(leftPath, rightPath, input)));
|
|
113
|
+
/* v8 ignore next 4 */
|
|
114
|
+
} else if (leftStats.isDirectory() !== rightStats.isDirectory()) {
|
|
115
|
+
/* v8 ignore next */
|
|
116
|
+
output.push(`File ${leftPath} is a directory while file ${rightPath} is not\n`);
|
|
117
|
+
} else {
|
|
118
|
+
const leftData = await fs.readFile(leftPath);
|
|
119
|
+
const rightData = await fs.readFile(rightPath);
|
|
120
|
+
/* v8 ignore next */
|
|
121
|
+
if (!leftData.equals(rightData)) {
|
|
122
|
+
output.push(createTwoFilesPatch(leftPath, rightPath, leftData.toString("utf8"), rightData.toString("utf8"), "", "", { context: input.unified ?? 3 }));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return output;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function exists(target: string): Promise<boolean> {
|
|
130
|
+
try {
|
|
131
|
+
await fs.lstat(target);
|
|
132
|
+
return true;
|
|
133
|
+
} catch {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
}
|
package/src/tools/du.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as fs from "node:fs/promises";
|
|
7
|
+
import { Type, type Static } from "@sinclair/typebox";
|
|
8
|
+
import { num, walk } from "../core/fsutil.js";
|
|
9
|
+
import { humanSize } from "../core/format.js";
|
|
10
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
11
|
+
|
|
12
|
+
const Schema = Type.Object(
|
|
13
|
+
{
|
|
14
|
+
paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Paths to measure. Default: ['.']." })),
|
|
15
|
+
summarize: Type.Optional(Type.Boolean({ description: "Only print a total per argument (`-s`)." })),
|
|
16
|
+
all: Type.Optional(Type.Boolean({ description: "Print every file, not just directories (`-a`)." })),
|
|
17
|
+
human: Type.Optional(Type.Boolean({ description: "Human-readable sizes (`-h`)." })),
|
|
18
|
+
total: Type.Optional(Type.Boolean({ description: "Print a grand total (`-c`)." })),
|
|
19
|
+
maxDepth: Type.Optional(Type.Integer({ minimum: 0, description: "Maximum recursion depth (`-d`)." })),
|
|
20
|
+
follow: Type.Optional(Type.Boolean({ description: "Follow symlinks (`-L`)." })),
|
|
21
|
+
oneFileSystem: Type.Optional(Type.Boolean({ description: "Stay on the starting filesystem (`-x`)." })),
|
|
22
|
+
},
|
|
23
|
+
{ additionalProperties: false },
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
type Input = Static<typeof Schema>;
|
|
27
|
+
|
|
28
|
+
interface Row {
|
|
29
|
+
path: string;
|
|
30
|
+
bytes: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export const duTool: ToolSpec<Input> = {
|
|
34
|
+
name: "du",
|
|
35
|
+
description:
|
|
36
|
+
"Estimate file and directory space usage with Linux `du` semantics (`-s`, `-a`, `-h`, `-c`, " +
|
|
37
|
+
"`-d`, `-L`, `-x`). Hard links are counted once.",
|
|
38
|
+
schema: Schema,
|
|
39
|
+
pipeable: false,
|
|
40
|
+
mutates: false,
|
|
41
|
+
async run(ctx, input) {
|
|
42
|
+
const paths = input.paths ?? ["."];
|
|
43
|
+
const rows: Row[] = [];
|
|
44
|
+
let grand = 0;
|
|
45
|
+
for (const requested of paths) {
|
|
46
|
+
const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
|
|
47
|
+
await ctx.permission.assert([{ target, boundary: target.full }]);
|
|
48
|
+
const rootStats = input.follow === true
|
|
49
|
+
? await ctx.sandbox.stat(target.full, requested)
|
|
50
|
+
: await ctx.sandbox.lstat(target.full, requested);
|
|
51
|
+
const rootDev = num(rootStats.dev);
|
|
52
|
+
const seen = new Set<string>();
|
|
53
|
+
let total = usage(target.full, rootStats, seen);
|
|
54
|
+
const local: Row[] = [];
|
|
55
|
+
if (input.all === true && !rootStats.isDirectory()) {
|
|
56
|
+
local.push({ path: requested, bytes: total });
|
|
57
|
+
}
|
|
58
|
+
if (rootStats.isDirectory()) {
|
|
59
|
+
for await (const entry of walk(target.full, {
|
|
60
|
+
recursive: true,
|
|
61
|
+
followSymlinks: input.follow === true,
|
|
62
|
+
...(input.maxDepth === undefined ? {} : { maxDepth: input.maxDepth }),
|
|
63
|
+
includeHidden: true,
|
|
64
|
+
signal: ctx.signal,
|
|
65
|
+
})) {
|
|
66
|
+
/* v8 ignore next */
|
|
67
|
+
if (input.oneFileSystem === true && num(entry.stats.dev) !== rootDev) continue;
|
|
68
|
+
const bytes = usage(entry.path, entry.stats, seen);
|
|
69
|
+
total += bytes;
|
|
70
|
+
if (input.all === true || entry.stats.isDirectory()) {
|
|
71
|
+
local.push({ path: entry.path, bytes });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (!rootStats.isDirectory()) {
|
|
76
|
+
rows.push({ path: requested, bytes: total });
|
|
77
|
+
} else if (input.summarize === true) {
|
|
78
|
+
rows.push({ path: requested, bytes: total });
|
|
79
|
+
} else {
|
|
80
|
+
rows.push(...local, { path: requested, bytes: total });
|
|
81
|
+
}
|
|
82
|
+
grand += total;
|
|
83
|
+
}
|
|
84
|
+
if (input.total === true) rows.push({ path: "total", bytes: grand });
|
|
85
|
+
const text = rows
|
|
86
|
+
.map((row) => `${input.human === true ? humanSize(row.bytes) : String(Math.ceil(row.bytes / 1024))}\t${row.path}`)
|
|
87
|
+
.join("\n");
|
|
88
|
+
return textResult(text.length > 0 ? `${text}\n` : "", { total: grand });
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
function usage(path: string, stats: Awaited<ReturnType<typeof fs.lstat>>, seen: Set<string>): number {
|
|
93
|
+
/* v8 ignore next */
|
|
94
|
+
if (!stats.isFile()) return stats.isDirectory() ? num(stats.blocks) * 512 : 0;
|
|
95
|
+
if (num(stats.nlink) > 1) {
|
|
96
|
+
const key = `${num(stats.dev)}:${num(stats.ino)}`;
|
|
97
|
+
/* v8 ignore next */
|
|
98
|
+
if (seen.has(key)) return 0;
|
|
99
|
+
seen.add(key);
|
|
100
|
+
}
|
|
101
|
+
return num(stats.size);
|
|
102
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as fs from "node:fs/promises";
|
|
7
|
+
import * as path from "node:path";
|
|
8
|
+
import picomatch from "picomatch";
|
|
9
|
+
import { Type, type Static } from "@sinclair/typebox";
|
|
10
|
+
import { num, walk } from "../core/fsutil.js";
|
|
11
|
+
import { parseSize } from "../core/format.js";
|
|
12
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
13
|
+
|
|
14
|
+
const Schema = Type.Object(
|
|
15
|
+
{
|
|
16
|
+
paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Starting paths. Default: ['.']." })),
|
|
17
|
+
name: Type.Optional(Type.String({ description: "Filename glob (`-name`)." })),
|
|
18
|
+
iname: Type.Optional(Type.String({ description: "Case-insensitive filename glob (`-iname`)." })),
|
|
19
|
+
pathPattern: Type.Optional(Type.String({ description: "Path glob (`-path`)." })),
|
|
20
|
+
type: Type.Optional(
|
|
21
|
+
Type.Union([Type.Literal("f"), Type.Literal("d"), Type.Literal("l"), Type.Literal("p"), Type.Literal("s")], {
|
|
22
|
+
description: "Entry type (`-type`).",
|
|
23
|
+
}),
|
|
24
|
+
),
|
|
25
|
+
size: Type.Optional(Type.String({ description: "Size expression, e.g. +10k or -1M (`-size`)." })),
|
|
26
|
+
mtime: Type.Optional(Type.String({ description: "Modification age in days, e.g. +7 (`-mtime`)." })),
|
|
27
|
+
mmin: Type.Optional(Type.String({ description: "Modification age in minutes (`-mmin`)." })),
|
|
28
|
+
maxDepth: Type.Optional(Type.Integer({ minimum: 0, description: "Maximum depth (`-maxdepth`)." })),
|
|
29
|
+
minDepth: Type.Optional(Type.Integer({ minimum: 0, description: "Minimum depth (`-mindepth`)." })),
|
|
30
|
+
empty: Type.Optional(Type.Boolean({ description: "Empty files or directories (`-empty`)." })),
|
|
31
|
+
perm: Type.Optional(Type.String({ description: "Octal permission mode (`-perm`)." })),
|
|
32
|
+
newer: Type.Optional(Type.String({ description: "Only entries newer than this file (`-newer`)." })),
|
|
33
|
+
follow: Type.Optional(Type.Boolean({ description: "Follow symlinks (`-L`)." })),
|
|
34
|
+
print0: Type.Optional(Type.Boolean({ description: "NUL-separated output (`-print0`)." })),
|
|
35
|
+
sort: Type.Optional(Type.Boolean({ description: "Sort results lexically. Default: true." })),
|
|
36
|
+
},
|
|
37
|
+
{ additionalProperties: false },
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
type Input = Static<typeof Schema>;
|
|
41
|
+
|
|
42
|
+
export const findTool: ToolSpec<Input> = {
|
|
43
|
+
name: "find",
|
|
44
|
+
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`.",
|
|
47
|
+
schema: Schema,
|
|
48
|
+
pipeable: false,
|
|
49
|
+
mutates: false,
|
|
50
|
+
async run(ctx, input) {
|
|
51
|
+
/* v8 ignore next */
|
|
52
|
+
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[] = [];
|
|
68
|
+
|
|
69
|
+
for (const requested of paths) {
|
|
70
|
+
const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
|
|
71
|
+
await ctx.permission.assert([{ target, boundary: target.full }]);
|
|
72
|
+
/* v8 ignore next 3 */
|
|
73
|
+
const rootStats = input.follow === true
|
|
74
|
+
? await ctx.sandbox.stat(target.full, requested)
|
|
75
|
+
: await ctx.sandbox.lstat(target.full, requested);
|
|
76
|
+
/* v8 ignore next */
|
|
77
|
+
if (!rootStats.isDirectory()) {
|
|
78
|
+
/* v8 ignore next */
|
|
79
|
+
if (await matches(target.full, rootStats, input, { nameMatch, inameMatch, pathMatch, newer })) {
|
|
80
|
+
results.push(requested);
|
|
81
|
+
}
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
/* v8 ignore next */
|
|
85
|
+
if (input.maxDepth === 0) {
|
|
86
|
+
/* v8 ignore next */
|
|
87
|
+
if (await matches(target.full, rootStats, input, { nameMatch, inameMatch, pathMatch, newer })) {
|
|
88
|
+
results.push(requested);
|
|
89
|
+
}
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
for await (const entry of walk(target.full, {
|
|
93
|
+
recursive: true,
|
|
94
|
+
followSymlinks: input.follow === true,
|
|
95
|
+
...(input.maxDepth === undefined ? {} : { maxDepth: input.maxDepth }),
|
|
96
|
+
includeHidden: true,
|
|
97
|
+
signal: ctx.signal,
|
|
98
|
+
})) {
|
|
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);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (input.sort !== false) results.sort((a, b) => a.localeCompare(b));
|
|
107
|
+
const separator = input.print0 === true ? "\0" : "\n";
|
|
108
|
+
/* v8 ignore next */
|
|
109
|
+
const text = results.length === 0 ? "" : results.join(separator) + separator;
|
|
110
|
+
return textResult(text, { found: results.length });
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
async function matches(
|
|
115
|
+
full: string,
|
|
116
|
+
stats: Awaited<ReturnType<typeof fs.lstat>>,
|
|
117
|
+
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
|
+
},
|
|
124
|
+
): Promise<boolean> {
|
|
125
|
+
const base = path.basename(full);
|
|
126
|
+
if (patterns.nameMatch !== undefined && !patterns.nameMatch(base)) return false;
|
|
127
|
+
/* v8 ignore next */
|
|
128
|
+
if (patterns.inameMatch !== undefined && !patterns.inameMatch(base)) return false;
|
|
129
|
+
/* v8 ignore next */
|
|
130
|
+
if (patterns.pathMatch !== undefined && !patterns.pathMatch(full)) return false;
|
|
131
|
+
if (input.type !== undefined && typeOf(stats) !== input.type) return false;
|
|
132
|
+
if (input.size !== undefined) {
|
|
133
|
+
/* v8 ignore next 3 */
|
|
134
|
+
const sign = input.size.startsWith("+") ? 1 : input.size.startsWith("-") ? -1 : 0;
|
|
135
|
+
const body = sign === 0 ? input.size : input.size.slice(1);
|
|
136
|
+
const size = parseSize(body);
|
|
137
|
+
/* v8 ignore next */
|
|
138
|
+
if (sign === 1 && stats.size <= size) return false;
|
|
139
|
+
/* v8 ignore next */
|
|
140
|
+
if (sign === -1 && stats.size >= size) return false;
|
|
141
|
+
/* v8 ignore next */
|
|
142
|
+
if (sign === 0 && stats.size !== size) return false;
|
|
143
|
+
}
|
|
144
|
+
if (input.mtime !== undefined) {
|
|
145
|
+
const age = (Date.now() - num(stats.mtimeMs)) / 86_400_000;
|
|
146
|
+
if (!ageMatches(age, input.mtime)) return false;
|
|
147
|
+
}
|
|
148
|
+
/* v8 ignore next 4 */
|
|
149
|
+
if (input.mmin !== undefined) {
|
|
150
|
+
const age = (Date.now() - num(stats.mtimeMs)) / 60_000;
|
|
151
|
+
if (!ageMatches(age, input.mmin)) return false;
|
|
152
|
+
}
|
|
153
|
+
/* v8 ignore next 6 */
|
|
154
|
+
if (input.empty === true) {
|
|
155
|
+
if (stats.isDirectory()) {
|
|
156
|
+
if ((await fs.readdir(full)).length > 0) return false;
|
|
157
|
+
} else if (num(stats.size) !== 0) return false;
|
|
158
|
+
}
|
|
159
|
+
if (input.perm !== undefined && (num(stats.mode) & 0o7777) !== Number.parseInt(input.perm, 8)) return false;
|
|
160
|
+
if (patterns.newer !== undefined && num(stats.mtimeMs) <= patterns.newer) return false;
|
|
161
|
+
return true;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function ageMatches(age: number, expression: string): boolean {
|
|
165
|
+
if (expression.startsWith("+")) return age > Number(expression.slice(1));
|
|
166
|
+
if (expression.startsWith("-")) return age < Number(expression.slice(1));
|
|
167
|
+
return Math.floor(age) === Number(expression);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function typeOf(stats: Awaited<ReturnType<typeof fs.lstat>>): string {
|
|
171
|
+
if (stats.isDirectory()) return "d";
|
|
172
|
+
/* v8 ignore next */
|
|
173
|
+
if (stats.isSymbolicLink()) return "l";
|
|
174
|
+
/* v8 ignore next */
|
|
175
|
+
if (stats.isFIFO()) return "p";
|
|
176
|
+
/* v8 ignore next */
|
|
177
|
+
if (stats.isSocket()) return "s";
|
|
178
|
+
return "f";
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
|