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/rm.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
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 { FsError, fromErrno, isMissing } from "../core/errors.js";
|
|
9
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
10
|
+
|
|
11
|
+
const Schema = Type.Object(
|
|
12
|
+
{
|
|
13
|
+
paths: Type.Array(Type.String({ minLength: 1 }), {
|
|
14
|
+
minItems: 1,
|
|
15
|
+
description: "Files, symlinks or directories to remove, like `rm FILE...`.",
|
|
16
|
+
}),
|
|
17
|
+
recursive: Type.Optional(
|
|
18
|
+
Type.Boolean({ description: "Remove directories and their contents recursively (`-r`, `-R`)." }),
|
|
19
|
+
),
|
|
20
|
+
force: Type.Optional(Type.Boolean({ description: "Ignore missing files and never prompt (`-f`)." })),
|
|
21
|
+
dir: Type.Optional(Type.Boolean({ description: "Remove empty directories like `rm -d`." })),
|
|
22
|
+
verbose: Type.Optional(Type.Boolean({ description: "Report each removed path like `rm -v`." })),
|
|
23
|
+
},
|
|
24
|
+
{ additionalProperties: false },
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
type Input = Static<typeof Schema>;
|
|
28
|
+
|
|
29
|
+
export const rmTool: ToolSpec<Input> = {
|
|
30
|
+
name: "rm",
|
|
31
|
+
description:
|
|
32
|
+
"Remove files, symlinks or directories with Linux `rm` semantics (`-r`, `-f`, `-d`, `-v`). " +
|
|
33
|
+
"Symlinks are removed as links; their targets are never touched. The project root is a hard stop.",
|
|
34
|
+
schema: Schema,
|
|
35
|
+
pipeable: false,
|
|
36
|
+
mutates: true,
|
|
37
|
+
async run(ctx, input) {
|
|
38
|
+
const removed: string[] = [];
|
|
39
|
+
const warnings: string[] = [];
|
|
40
|
+
|
|
41
|
+
for (const requested of input.paths) {
|
|
42
|
+
let target;
|
|
43
|
+
try {
|
|
44
|
+
target = await ctx.sandbox.resolveExisting(requested);
|
|
45
|
+
} catch (error) {
|
|
46
|
+
if (input.force === true && error instanceof FsError && error.code === "not-found") {
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
ctx.sandbox.assertSafeToDelete(target.full);
|
|
52
|
+
|
|
53
|
+
const stats = await ctx.sandbox.lstat(target.full, requested);
|
|
54
|
+
const boundary = stats.isDirectory() && !stats.isSymbolicLink() ? target.full : ctx.sandbox.boundaryFor(target.full, "file");
|
|
55
|
+
await ctx.permission.assert([
|
|
56
|
+
{ target, boundary, resource: ctx.sandbox.resource(target.full) },
|
|
57
|
+
]);
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
if (stats.isSymbolicLink()) {
|
|
61
|
+
await fs.unlink(target.full);
|
|
62
|
+
} else if (stats.isDirectory()) {
|
|
63
|
+
if (input.recursive === true) {
|
|
64
|
+
await fs.rm(target.full, { recursive: true, force: false });
|
|
65
|
+
} else if (input.dir === true) {
|
|
66
|
+
await fs.rmdir(target.full);
|
|
67
|
+
} else {
|
|
68
|
+
throw new FsError(
|
|
69
|
+
`"${requested}" is a directory; use recursive: true or dir: true.`,
|
|
70
|
+
"not-file",
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
} else {
|
|
74
|
+
await fs.unlink(target.full);
|
|
75
|
+
}
|
|
76
|
+
} catch (error) {
|
|
77
|
+
/* v8 ignore next */
|
|
78
|
+
if (input.force === true && isMissing(error)) continue;
|
|
79
|
+
/* v8 ignore next 2 */
|
|
80
|
+
if (error instanceof FsError) throw error;
|
|
81
|
+
/* v8 ignore next */
|
|
82
|
+
throw fromErrno(error);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
removed.push(requested);
|
|
86
|
+
if (input.verbose === true) warnings.push(`removed '${requested}'`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return textResult(warnings.join("\n"), { removed });
|
|
90
|
+
},
|
|
91
|
+
};
|
|
@@ -0,0 +1,117 @@
|
|
|
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 { Type, type Static } from "@sinclair/typebox";
|
|
9
|
+
import { FsError, fromErrno, isMissing } from "../core/errors.js";
|
|
10
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
11
|
+
|
|
12
|
+
const Schema = Type.Object(
|
|
13
|
+
{
|
|
14
|
+
paths: Type.Array(Type.String({ minLength: 1 }), {
|
|
15
|
+
minItems: 1,
|
|
16
|
+
description: "Empty directories to remove, like `rmdir DIR...`.",
|
|
17
|
+
}),
|
|
18
|
+
parents: Type.Optional(
|
|
19
|
+
Type.Boolean({ description: "Remove now-empty parent directories like `rmdir -p`." }),
|
|
20
|
+
),
|
|
21
|
+
ignoreNonEmpty: Type.Optional(
|
|
22
|
+
Type.Boolean({ description: "Ignore non-empty directories like `--ignore-fail-on-non-empty`." }),
|
|
23
|
+
),
|
|
24
|
+
verbose: Type.Optional(Type.Boolean({ description: "Report each removed directory like `rmdir -v`." })),
|
|
25
|
+
},
|
|
26
|
+
{ additionalProperties: false },
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
type Input = Static<typeof Schema>;
|
|
30
|
+
|
|
31
|
+
export const rmdirTool: ToolSpec<Input> = {
|
|
32
|
+
name: "rmdir",
|
|
33
|
+
description:
|
|
34
|
+
"Remove one or more empty directories with Linux `rmdir` semantics (`-p`, `-v`, " +
|
|
35
|
+
"`--ignore-fail-on-non-empty`). Symlinks and non-empty directories are refused.",
|
|
36
|
+
schema: Schema,
|
|
37
|
+
pipeable: false,
|
|
38
|
+
mutates: true,
|
|
39
|
+
async run(ctx, input) {
|
|
40
|
+
const removed: string[] = [];
|
|
41
|
+
const warnings: string[] = [];
|
|
42
|
+
|
|
43
|
+
for (const requested of input.paths) {
|
|
44
|
+
const target = await ctx.sandbox.resolveExisting(requested);
|
|
45
|
+
ctx.sandbox.assertSafeToDelete(target.full);
|
|
46
|
+
await ctx.permission.assert([
|
|
47
|
+
{ target, boundary: target.full, resource: ctx.sandbox.resource(target.full) },
|
|
48
|
+
]);
|
|
49
|
+
|
|
50
|
+
const stats = await ctx.sandbox.lstat(target.full, requested);
|
|
51
|
+
if (stats.isSymbolicLink()) {
|
|
52
|
+
throw new FsError(`"${requested}" is a symlink; use rm to remove the link.`, "not-directory");
|
|
53
|
+
}
|
|
54
|
+
if (!stats.isDirectory()) {
|
|
55
|
+
throw new FsError(`"${requested}" is not a directory.`, "not-directory");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
await fs.rmdir(target.full);
|
|
60
|
+
removed.push(requested);
|
|
61
|
+
if (input.verbose === true) warnings.push(`rmdir: removing directory, '${requested}'`);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (isNonEmpty(error) && input.ignoreNonEmpty === true) {
|
|
64
|
+
warnings.push(`rmdir: ignoring non-empty directory '${requested}'`);
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
throw fromErrno(error);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (input.parents === true) {
|
|
71
|
+
await removeParents(ctx, target.full, removed, warnings, input.verbose === true);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return textResult(
|
|
76
|
+
[...warnings, ...(input.verbose === true ? removed.map((item) => `Directory removed: ${item}`) : [])].join(
|
|
77
|
+
"\n",
|
|
78
|
+
),
|
|
79
|
+
{ removed },
|
|
80
|
+
);
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
async function removeParents(
|
|
85
|
+
ctx: Parameters<ToolSpec<Input>["run"]>[0],
|
|
86
|
+
start: string,
|
|
87
|
+
removed: string[],
|
|
88
|
+
warnings: string[],
|
|
89
|
+
verbose: boolean,
|
|
90
|
+
): Promise<void> {
|
|
91
|
+
let current = path.dirname(start);
|
|
92
|
+
while (ctx.sandbox.isWithin(current) && current !== ctx.sandbox.root) {
|
|
93
|
+
const target = await ctx.sandbox.resolveExisting(current);
|
|
94
|
+
await ctx.permission.assert([
|
|
95
|
+
{ target, boundary: target.full, resource: ctx.sandbox.resource(target.full) },
|
|
96
|
+
]);
|
|
97
|
+
try {
|
|
98
|
+
await fs.rmdir(current);
|
|
99
|
+
const label = ctx.sandbox.resource(current);
|
|
100
|
+
removed.push(label);
|
|
101
|
+
/* v8 ignore next */
|
|
102
|
+
if (verbose) warnings.push(`rmdir: removing directory, '${label}'`);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
/* v8 ignore next 3 */
|
|
105
|
+
if (isMissing(error) || isNonEmpty(error)) return;
|
|
106
|
+
/* v8 ignore next */
|
|
107
|
+
throw fromErrno(error);
|
|
108
|
+
}
|
|
109
|
+
current = path.dirname(current);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function isNonEmpty(error: unknown): boolean {
|
|
114
|
+
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
|
115
|
+
/* v8 ignore next */
|
|
116
|
+
return code === "ENOTEMPTY" || code === "ENOTDIR" || code === "EEXIST";
|
|
117
|
+
}
|
package/src/tools/sed.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
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 { randomBytes } from "node:crypto";
|
|
9
|
+
import { Type, type Static } from "@sinclair/typebox";
|
|
10
|
+
import { FsError, fromErrno } from "../core/errors.js";
|
|
11
|
+
import { inputStream, writeAll } from "../core/stream.js";
|
|
12
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
13
|
+
|
|
14
|
+
const Schema = Type.Object(
|
|
15
|
+
{
|
|
16
|
+
script: Type.String({ description: "sed substitution, e.g. s/old/new/g." }),
|
|
17
|
+
expressions: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Additional -e expressions." })),
|
|
18
|
+
paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to process. Omit to read stdin." })),
|
|
19
|
+
inPlace: Type.Optional(Type.Boolean({ description: "Edit files in place (`-i`)." })),
|
|
20
|
+
extendedRegexp: Type.Optional(Type.Boolean({ description: "Use extended regular expressions (`-E`)." })),
|
|
21
|
+
quiet: Type.Optional(Type.Boolean({ description: "Suppress automatic output (`-n`)." })),
|
|
22
|
+
},
|
|
23
|
+
{ additionalProperties: false },
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
type Input = Static<typeof Schema>;
|
|
27
|
+
|
|
28
|
+
interface Substitution {
|
|
29
|
+
pattern: RegExp;
|
|
30
|
+
replacement: string;
|
|
31
|
+
global: boolean;
|
|
32
|
+
print: boolean;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const sedTool: ToolSpec<Input> = {
|
|
36
|
+
name: "sed",
|
|
37
|
+
description:
|
|
38
|
+
"Apply `s/pattern/replacement/flags` substitutions with Linux `sed` semantics for the common " +
|
|
39
|
+
"substitution form (`-e`, `-i`, `-E`, `-n`). Full sed command language is not supported.",
|
|
40
|
+
schema: Schema,
|
|
41
|
+
pipeable: "filter",
|
|
42
|
+
mutates: false,
|
|
43
|
+
async run(ctx, input, io) {
|
|
44
|
+
const scripts = [input.script, ...(input.expressions ?? [])];
|
|
45
|
+
const substitutions = scripts.map((script) => parseSubstitution(script, input.extendedRegexp === true));
|
|
46
|
+
const paths = input.paths ?? [];
|
|
47
|
+
if (input.inPlace === true && paths.length === 0) {
|
|
48
|
+
throw new FsError("in-place editing requires paths.", "invalid");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const targets = [];
|
|
52
|
+
for (const requested of paths) {
|
|
53
|
+
const target = await ctx.sandbox.resolveFollow(requested);
|
|
54
|
+
targets.push({ requested, full: target.full, target });
|
|
55
|
+
}
|
|
56
|
+
if (targets.length > 0) {
|
|
57
|
+
await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (input.inPlace === true) {
|
|
61
|
+
for (const target of targets) {
|
|
62
|
+
/* v8 ignore next */
|
|
63
|
+
const data = await fs.readFile(target.full).catch((error) => {
|
|
64
|
+
throw fromErrno(error);
|
|
65
|
+
});
|
|
66
|
+
const transformed = transform(data.toString("utf8"), substitutions, input.quiet === true);
|
|
67
|
+
const temp = path.join(path.dirname(target.full), `.opencode-sed-${randomBytes(6).toString("hex")}`);
|
|
68
|
+
await writeAll(temp, Buffer.from(transformed, "utf8"));
|
|
69
|
+
const stats = await fs.stat(target.full);
|
|
70
|
+
/* v8 ignore next */
|
|
71
|
+
await fs.chmod(temp, stats.mode & 0o7777).catch(() => undefined);
|
|
72
|
+
/* v8 ignore next */
|
|
73
|
+
await fs.rename(temp, target.full).catch((error) => {
|
|
74
|
+
throw fromErrno(error);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
return textResult("", { files: paths });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/* v8 ignore next */
|
|
81
|
+
const stream = inputStream(targets.map((target) => target.full), io.stdin);
|
|
82
|
+
const source = await collectText(stream);
|
|
83
|
+
return textResult(transform(source, substitutions, input.quiet === true), { lines: source.split("\n").length });
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
export function parseSubstitution(script: string, extended: boolean): Substitution {
|
|
88
|
+
if (!script.startsWith("s") || script.length < 4) {
|
|
89
|
+
throw new FsError(`Unsupported sed expression: ${script}`, "unsupported");
|
|
90
|
+
}
|
|
91
|
+
const delimiter = script[1] as string;
|
|
92
|
+
const parts: string[] = [];
|
|
93
|
+
let current = "";
|
|
94
|
+
for (let index = 2; index < script.length; index++) {
|
|
95
|
+
const char = script[index] as string;
|
|
96
|
+
/* v8 ignore next */
|
|
97
|
+
if (char === "\\") {
|
|
98
|
+
/* v8 ignore next */
|
|
99
|
+
current += char + (script[++index] ?? "");
|
|
100
|
+
} else if (char === delimiter) {
|
|
101
|
+
parts.push(current);
|
|
102
|
+
current = "";
|
|
103
|
+
} else {
|
|
104
|
+
current += char;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
parts.push(current);
|
|
108
|
+
/* v8 ignore next */
|
|
109
|
+
if (parts.length < 2) throw new FsError(`Invalid sed expression: ${script}`, "invalid");
|
|
110
|
+
const flags = parts[2] ?? "";
|
|
111
|
+
return {
|
|
112
|
+
/* v8 ignore next */
|
|
113
|
+
pattern: new RegExp(parts[0] as string, `${extended ? "" : ""}${flags.includes("i") ? "i" : ""}g`),
|
|
114
|
+
replacement: toJsReplacement(parts[1] as string),
|
|
115
|
+
global: flags.includes("g"),
|
|
116
|
+
print: flags.includes("p"),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function toJsReplacement(value: string): string {
|
|
121
|
+
return value.replaceAll("&", "$&").replace(/\\(\d)/g, "$$$1");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function transform(text: string, substitutions: Substitution[], quiet: boolean): string {
|
|
125
|
+
const trailing = text.endsWith("\n");
|
|
126
|
+
const rows = text.split("\n");
|
|
127
|
+
/* v8 ignore next */
|
|
128
|
+
if (trailing) rows.pop();
|
|
129
|
+
const output: string[] = [];
|
|
130
|
+
for (const row of rows) {
|
|
131
|
+
let line = row;
|
|
132
|
+
for (const substitution of substitutions) {
|
|
133
|
+
const before = line;
|
|
134
|
+
line = substitution.global
|
|
135
|
+
? line.replace(substitution.pattern, substitution.replacement)
|
|
136
|
+
: line.replace(new RegExp(substitution.pattern.source, substitution.pattern.flags.replace("g", "")), substitution.replacement);
|
|
137
|
+
if (substitution.print && line !== before) output.push(line);
|
|
138
|
+
}
|
|
139
|
+
if (quiet !== true) output.push(line);
|
|
140
|
+
}
|
|
141
|
+
/* v8 ignore next */
|
|
142
|
+
return output.join("\n") + (trailing ? "\n" : "");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function collectText(stream: AsyncIterable<Buffer>): Promise<string> {
|
|
146
|
+
let text = "";
|
|
147
|
+
for await (const chunk of stream) text += chunk.toString("utf8");
|
|
148
|
+
return text;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { Type, type Static } from "@sinclair/typebox";
|
|
7
|
+
import { collect, inputStream, lines } from "../core/stream.js";
|
|
8
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
9
|
+
|
|
10
|
+
const Schema = Type.Object(
|
|
11
|
+
{
|
|
12
|
+
paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to sort. Omit to read stdin." })),
|
|
13
|
+
numeric: Type.Optional(Type.Boolean({ description: "Compare numerically (`-n`)." })),
|
|
14
|
+
reverse: Type.Optional(Type.Boolean({ description: "Reverse the result (`-r`)." })),
|
|
15
|
+
unique: Type.Optional(Type.Boolean({ description: "Remove duplicate lines (`-u`)." })),
|
|
16
|
+
ignoreCase: Type.Optional(Type.Boolean({ description: "Fold case (`-f`)." })),
|
|
17
|
+
ignoreLeadingBlanks: Type.Optional(Type.Boolean({ description: "Ignore leading blanks (`-b`)." })),
|
|
18
|
+
field: Type.Optional(Type.Integer({ minimum: 1, description: "Sort by this 1-based field (`-k`)." })),
|
|
19
|
+
separator: Type.Optional(Type.String({ description: "Field separator (`-t`). Default: whitespace." })),
|
|
20
|
+
},
|
|
21
|
+
{ additionalProperties: false },
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
type Input = Static<typeof Schema>;
|
|
25
|
+
|
|
26
|
+
export const sortTool: ToolSpec<Input> = {
|
|
27
|
+
name: "sort",
|
|
28
|
+
description:
|
|
29
|
+
"Sort lines with common Linux `sort` semantics (`-n`, `-r`, `-u`, `-f`, `-b`, `-k`, `-t`).",
|
|
30
|
+
schema: Schema,
|
|
31
|
+
pipeable: "filter",
|
|
32
|
+
mutates: false,
|
|
33
|
+
async run(ctx, input, io) {
|
|
34
|
+
const paths = input.paths ?? [];
|
|
35
|
+
const targets = [];
|
|
36
|
+
for (const requested of paths) {
|
|
37
|
+
const target = await ctx.sandbox.resolveFollow(requested);
|
|
38
|
+
targets.push({ requested, full: target.full, target });
|
|
39
|
+
}
|
|
40
|
+
if (targets.length > 0) {
|
|
41
|
+
await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
|
|
42
|
+
}
|
|
43
|
+
const stream = inputStream(targets.map((target) => target.full), io.stdin);
|
|
44
|
+
const rows: string[] = [];
|
|
45
|
+
for await (const line of lines(stream)) rows.push(line.text);
|
|
46
|
+
rows.sort((a, b) => compare(a, b, input));
|
|
47
|
+
const result = input.unique === true ? [...new Set(rows)] : rows;
|
|
48
|
+
return textResult(result.map((line) => `${line}\n`).join(""), { lines: result.length });
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
function compare(a: string, b: string, input: Input): number {
|
|
53
|
+
const left = key(a, input);
|
|
54
|
+
const right = key(b, input);
|
|
55
|
+
let result: number;
|
|
56
|
+
if (input.numeric === true) {
|
|
57
|
+
result = Number.parseFloat(left) - Number.parseFloat(right);
|
|
58
|
+
if (Number.isNaN(result)) result = left.localeCompare(right);
|
|
59
|
+
} else {
|
|
60
|
+
result = input.ignoreCase === true ? left.toLowerCase().localeCompare(right.toLowerCase()) : left.localeCompare(right);
|
|
61
|
+
}
|
|
62
|
+
return input.reverse === true ? -result : result;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function key(value: string, input: Input): string {
|
|
66
|
+
let text = input.ignoreLeadingBlanks === true ? value.trimStart() : value;
|
|
67
|
+
if (input.field !== undefined) {
|
|
68
|
+
const fields = input.separator === undefined ? text.split(/\s+/) : text.split(input.separator);
|
|
69
|
+
/* v8 ignore next */
|
|
70
|
+
text = fields[input.field - 1] ?? "";
|
|
71
|
+
}
|
|
72
|
+
return text;
|
|
73
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
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 { lookupGroup, lookupUser, modeString, num, typeName } from "../core/fsutil.js";
|
|
10
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
11
|
+
|
|
12
|
+
const Schema = Type.Object(
|
|
13
|
+
{
|
|
14
|
+
paths: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
|
|
15
|
+
follow: Type.Optional(Type.Boolean({ description: "Follow symlinks (`-L`)." })),
|
|
16
|
+
format: Type.Optional(Type.String({ description: "printf-style format string (`-c`, `--printf`)." })),
|
|
17
|
+
filesystem: Type.Optional(Type.Boolean({ description: "Show filesystem status (`-f`)." })),
|
|
18
|
+
},
|
|
19
|
+
{ additionalProperties: false },
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
type Input = Static<typeof Schema>;
|
|
23
|
+
|
|
24
|
+
export const statTool: ToolSpec<Input> = {
|
|
25
|
+
name: "stat",
|
|
26
|
+
description:
|
|
27
|
+
"Display file or filesystem status with Linux `stat` semantics (`-L`, `-c`, `-f`). " +
|
|
28
|
+
"Supports the common percent tokens for path, size, type, mode, owner, times, device and inode.",
|
|
29
|
+
schema: Schema,
|
|
30
|
+
pipeable: false,
|
|
31
|
+
mutates: false,
|
|
32
|
+
async run(ctx, input) {
|
|
33
|
+
const blocks: string[] = [];
|
|
34
|
+
for (const requested of input.paths) {
|
|
35
|
+
const target = input.follow === true
|
|
36
|
+
? await ctx.sandbox.resolveFollow(requested)
|
|
37
|
+
: await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
|
|
38
|
+
await ctx.permission.assert([{ target, boundary: target.full }]);
|
|
39
|
+
if (input.filesystem === true) {
|
|
40
|
+
blocks.push(await formatFilesystem(requested, target.full));
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
const stats = input.follow === true
|
|
44
|
+
? await ctx.sandbox.stat(target.full, requested)
|
|
45
|
+
: await ctx.sandbox.lstat(target.full, requested);
|
|
46
|
+
/* v8 ignore next */
|
|
47
|
+
const link = stats.isSymbolicLink() ? await fs.readlink(target.full).catch(() => undefined) : undefined;
|
|
48
|
+
blocks.push(
|
|
49
|
+
input.format === undefined
|
|
50
|
+
? await defaultFormat(requested, target.full, stats, link)
|
|
51
|
+
: await customFormat(input.format, requested, target.full, stats, link),
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
return textResult(blocks.join("\n"), { paths: input.paths });
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
async function defaultFormat(
|
|
59
|
+
requested: string,
|
|
60
|
+
full: string,
|
|
61
|
+
stats: Awaited<ReturnType<typeof fs.lstat>>,
|
|
62
|
+
link: string | undefined,
|
|
63
|
+
): Promise<string> {
|
|
64
|
+
const user = await lookupUser(num(stats.uid));
|
|
65
|
+
const group = await lookupGroup(num(stats.gid));
|
|
66
|
+
/* v8 ignore next */
|
|
67
|
+
const name = link === undefined ? `'${requested}'` : `'${requested}' -> '${link}'`;
|
|
68
|
+
/* v8 ignore next */
|
|
69
|
+
const birth = stats.birthtimeMs === 0 ? "-" : stats.birthtime.toISOString();
|
|
70
|
+
const lines = [
|
|
71
|
+
` File: ${name}`,
|
|
72
|
+
` Size: ${num(stats.size)}\tBlocks: ${num(stats.blocks)}\tIO Block: ${num(stats.blksize)} ${typeName(stats)}`,
|
|
73
|
+
`Device: ${num(stats.dev)}\tInode: ${num(stats.ino)}\tLinks: ${num(stats.nlink)}`,
|
|
74
|
+
`Access: (${(num(stats.mode) & 0o7777).toString(8).padStart(4, "0")}/${modeString(stats)}) Uid: (${num(stats.uid)}/${user}) Gid: (${num(stats.gid)}/${group})`,
|
|
75
|
+
`Access: ${stats.atime.toISOString()}`,
|
|
76
|
+
`Modify: ${stats.mtime.toISOString()}`,
|
|
77
|
+
`Change: ${stats.ctime.toISOString()}`,
|
|
78
|
+
` Birth: ${birth}`,
|
|
79
|
+
];
|
|
80
|
+
return lines.join("\n");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function customFormat(
|
|
84
|
+
format: string,
|
|
85
|
+
requested: string,
|
|
86
|
+
full: string,
|
|
87
|
+
stats: Awaited<ReturnType<typeof fs.lstat>>,
|
|
88
|
+
link: string | undefined,
|
|
89
|
+
): Promise<string> {
|
|
90
|
+
const values: Record<string, string> = {
|
|
91
|
+
n: requested,
|
|
92
|
+
/* v8 ignore next */
|
|
93
|
+
N: link === undefined ? `'${requested}'` : `'${requested}' -> '${link}'`,
|
|
94
|
+
s: String(num(stats.size)),
|
|
95
|
+
F: typeName(stats),
|
|
96
|
+
a: (num(stats.mode) & 0o7777).toString(8),
|
|
97
|
+
A: modeString(stats),
|
|
98
|
+
u: String(num(stats.uid)),
|
|
99
|
+
U: await lookupUser(num(stats.uid)),
|
|
100
|
+
g: String(num(stats.gid)),
|
|
101
|
+
G: await lookupGroup(num(stats.gid)),
|
|
102
|
+
d: String(num(stats.dev)),
|
|
103
|
+
i: String(num(stats.ino)),
|
|
104
|
+
h: String(num(stats.nlink)),
|
|
105
|
+
b: String(num(stats.blocks)),
|
|
106
|
+
B: String(num(stats.blksize)),
|
|
107
|
+
o: String(num(stats.blksize)),
|
|
108
|
+
x: stats.atime.toISOString(),
|
|
109
|
+
X: String(Math.floor(num(stats.atimeMs) / 1000)),
|
|
110
|
+
y: stats.mtime.toISOString(),
|
|
111
|
+
Y: String(Math.floor(num(stats.mtimeMs) / 1000)),
|
|
112
|
+
z: stats.ctime.toISOString(),
|
|
113
|
+
Z: String(Math.floor(num(stats.ctimeMs) / 1000)),
|
|
114
|
+
t: Math.floor(num(stats.rdev) / 256).toString(16),
|
|
115
|
+
T: (num(stats.rdev) % 256).toString(16),
|
|
116
|
+
L: full,
|
|
117
|
+
};
|
|
118
|
+
let output = "";
|
|
119
|
+
for (let index = 0; index < format.length; index++) {
|
|
120
|
+
const char = format[index] as string;
|
|
121
|
+
if (char === "\\") {
|
|
122
|
+
const escaped = format[++index] as string | undefined;
|
|
123
|
+
/* v8 ignore next */
|
|
124
|
+
output += escaped === "n" ? "\n" : escaped === "t" ? "\t" : escaped === "\\" ? "\\" : `\\${escaped ?? ""}`;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (char !== "%") {
|
|
128
|
+
output += char;
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const next = format[++index] as string | undefined;
|
|
132
|
+
if (next === undefined) {
|
|
133
|
+
output += "%";
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
if (next === "%") output += "%";
|
|
137
|
+
else output += values[next] ?? `%${next}`;
|
|
138
|
+
}
|
|
139
|
+
return output;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function formatFilesystem(requested: string, full: string): Promise<string> {
|
|
143
|
+
let stats;
|
|
144
|
+
try {
|
|
145
|
+
stats = await fs.statfs(full);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
/* v8 ignore next */
|
|
148
|
+
throw fromErrno(error, "access");
|
|
149
|
+
}
|
|
150
|
+
return [
|
|
151
|
+
` File: "${requested}"`,
|
|
152
|
+
` ID: ${num(stats.type).toString(16)} Namelen: 255 Type: ${num(stats.type).toString(16)}`,
|
|
153
|
+
`Block size: ${num(stats.bsize)} Fundamental block size: ${num(stats.bsize)}`,
|
|
154
|
+
`Blocks: Total: ${num(stats.blocks)} Free: ${num(stats.bfree)} Available: ${num(stats.bavail)}`,
|
|
155
|
+
`Inodes: Total: ${num(stats.files)} Free: ${num(stats.ffree)}`,
|
|
156
|
+
].join("\n");
|
|
157
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { Type, type Static } from "@sinclair/typebox";
|
|
7
|
+
import { collect, inputStream, readFiles } from "../core/stream.js";
|
|
8
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
9
|
+
import { FsError } from "../core/errors.js";
|
|
10
|
+
|
|
11
|
+
const Schema = Type.Object(
|
|
12
|
+
{
|
|
13
|
+
paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to read. Omit to read stdin." })),
|
|
14
|
+
lines: Type.Optional(Type.Integer({ minimum: 1, description: "Number of lines. Default: 10 (`-n`)." })),
|
|
15
|
+
bytes: Type.Optional(Type.Integer({ minimum: 1, description: "Number of bytes from the end (`-c`)." })),
|
|
16
|
+
fromStart: Type.Optional(Type.Boolean({ description: "Treat lines as a 1-based starting line (`-n +N`)." })),
|
|
17
|
+
quiet: Type.Optional(Type.Boolean({ description: "Never print file headers (`-q`)." })),
|
|
18
|
+
verbose: Type.Optional(Type.Boolean({ description: "Always print file headers (`-v`)." })),
|
|
19
|
+
},
|
|
20
|
+
{ additionalProperties: false },
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
type Input = Static<typeof Schema>;
|
|
24
|
+
|
|
25
|
+
export const tailTool: ToolSpec<Input> = {
|
|
26
|
+
name: "tail",
|
|
27
|
+
description:
|
|
28
|
+
"Output the last part of files or stdin with Linux `tail` semantics (`-n`, `-n +N`, `-c`, `-q`, `-v`). " +
|
|
29
|
+
"Follow mode (`-f`) is not supported.",
|
|
30
|
+
schema: Schema,
|
|
31
|
+
pipeable: "filter",
|
|
32
|
+
mutates: false,
|
|
33
|
+
async run(ctx, input, io) {
|
|
34
|
+
if (input.lines !== undefined && input.bytes !== undefined) {
|
|
35
|
+
throw new FsError("tail accepts either lines or bytes, not both.", "invalid");
|
|
36
|
+
}
|
|
37
|
+
const count = input.bytes ?? input.lines ?? 10;
|
|
38
|
+
const paths = input.paths ?? [];
|
|
39
|
+
const targets = [];
|
|
40
|
+
for (const requested of paths) {
|
|
41
|
+
const target = await ctx.sandbox.resolveFollow(requested);
|
|
42
|
+
targets.push({ requested, full: target.full, target });
|
|
43
|
+
}
|
|
44
|
+
if (targets.length > 0) {
|
|
45
|
+
await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const output: Buffer[] = [];
|
|
49
|
+
if (targets.length === 0) {
|
|
50
|
+
const data = await collect(await inputStream([], io.stdin));
|
|
51
|
+
output.push(tailBuffer(data, count, input));
|
|
52
|
+
} else {
|
|
53
|
+
for (const target of targets) {
|
|
54
|
+
if (input.quiet !== true && (targets.length > 1 || input.verbose === true)) {
|
|
55
|
+
output.push(Buffer.from(`==> ${target.requested} <==\n`));
|
|
56
|
+
}
|
|
57
|
+
const data = await collect(readFiles([target.full]));
|
|
58
|
+
output.push(tailBuffer(data, count, input));
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return textResult(Buffer.concat(output).toString("utf8"), { paths });
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
function tailBuffer(data: Buffer, count: number, input: Input): Buffer {
|
|
66
|
+
if (input.bytes !== undefined) return data.subarray(Math.max(0, data.length - count));
|
|
67
|
+
const text = data.toString("utf8");
|
|
68
|
+
const trailing = text.endsWith("\n");
|
|
69
|
+
const parts = text.split("\n");
|
|
70
|
+
if (trailing) parts.pop();
|
|
71
|
+
/* v8 ignore next */
|
|
72
|
+
if (input.fromStart === true) return Buffer.from(parts.slice(count - 1).join("\n") + (trailing ? "\n" : ""), "utf8");
|
|
73
|
+
return Buffer.from(parts.slice(Math.max(0, parts.length - count)).join("\n") + (trailing ? "\n" : ""), "utf8");
|
|
74
|
+
}
|