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
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { TSchema } from "@sinclair/typebox";
|
|
7
|
+
import type { Sandbox } from "./sandbox.js";
|
|
8
|
+
import type { PermissionGate } from "./permissions.js";
|
|
9
|
+
|
|
10
|
+
export type PipeMode = "source" | "filter" | "sink" | false;
|
|
11
|
+
|
|
12
|
+
export interface IO {
|
|
13
|
+
/** Piped input when the tool is used as a pipe stage. */
|
|
14
|
+
readonly stdin?: AsyncIterable<Buffer>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ToolResult {
|
|
18
|
+
readonly stdout: Buffer;
|
|
19
|
+
readonly stderr?: string;
|
|
20
|
+
readonly exitCode?: 0 | 1 | 2;
|
|
21
|
+
readonly metadata?: Record<string, unknown>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface RunContext {
|
|
25
|
+
readonly sandbox: Sandbox;
|
|
26
|
+
readonly permission: PermissionGate;
|
|
27
|
+
readonly permissionFor: (action: string) => PermissionGate;
|
|
28
|
+
readonly concurrency: number;
|
|
29
|
+
readonly signal: AbortSignal;
|
|
30
|
+
readonly tmpdir: string;
|
|
31
|
+
readonly maxOutputBytes: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ToolSpec<I> {
|
|
35
|
+
readonly name: string;
|
|
36
|
+
readonly description: string;
|
|
37
|
+
readonly schema: TSchema;
|
|
38
|
+
readonly pipeable: PipeMode;
|
|
39
|
+
readonly mutates: boolean;
|
|
40
|
+
readonly run: (ctx: RunContext, input: I, io: IO) => Promise<ToolResult>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function textResult(
|
|
44
|
+
text: string,
|
|
45
|
+
metadata: Record<string, unknown> = {},
|
|
46
|
+
exitCode: 0 | 1 | 2 = 0,
|
|
47
|
+
): ToolResult {
|
|
48
|
+
return { stdout: Buffer.from(text, "utf8"), exitCode, metadata };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as os from "node:os";
|
|
7
|
+
import { Plugin } from "@opencode/plugin";
|
|
8
|
+
import { FsError } from "./core/errors.js";
|
|
9
|
+
import { renderError, renderResult } from "./core/format.js";
|
|
10
|
+
import { PermissionGate, type PermissionAssert } from "./core/permissions.js";
|
|
11
|
+
import { clampConcurrency } from "./core/parallel.js";
|
|
12
|
+
import { Sandbox } from "./core/sandbox.js";
|
|
13
|
+
import { parseSchema } from "./core/schema.js";
|
|
14
|
+
import type { ToolSpec } from "./core/types.js";
|
|
15
|
+
import { catTool } from "./tools/cat.js";
|
|
16
|
+
import { chmodTool } from "./tools/chmod.js";
|
|
17
|
+
import { cpTool } from "./tools/cp.js";
|
|
18
|
+
import { cutTool } from "./tools/cut.js";
|
|
19
|
+
import { dfTool } from "./tools/df.js";
|
|
20
|
+
import { diffTool } from "./tools/diff.js";
|
|
21
|
+
import { duTool } from "./tools/du.js";
|
|
22
|
+
import { findTool } from "./tools/find.js";
|
|
23
|
+
import { grepTool } from "./tools/grep.js";
|
|
24
|
+
import { gunzipTool, gzipTool } from "./tools/gzip.js";
|
|
25
|
+
import { hashTool } from "./tools/hash.js";
|
|
26
|
+
import { headTool } from "./tools/head.js";
|
|
27
|
+
import { lnTool } from "./tools/ln.js";
|
|
28
|
+
import { lsTool } from "./tools/ls.js";
|
|
29
|
+
import { mkdirTool } from "./tools/mkdir.js";
|
|
30
|
+
import { mktempTool } from "./tools/mktemp.js";
|
|
31
|
+
import { mvTool } from "./tools/mv.js";
|
|
32
|
+
import { pipeTool } from "./tools/pipe.js";
|
|
33
|
+
import { readlinkTool } from "./tools/readlink.js";
|
|
34
|
+
import { rmTool } from "./tools/rm.js";
|
|
35
|
+
import { rmdirTool } from "./tools/rmdir.js";
|
|
36
|
+
import { sedTool } from "./tools/sed.js";
|
|
37
|
+
import { sortTool } from "./tools/sort.js";
|
|
38
|
+
import { statTool } from "./tools/stat.js";
|
|
39
|
+
import { tailTool } from "./tools/tail.js";
|
|
40
|
+
import { tarTool } from "./tools/tar.js";
|
|
41
|
+
import { teeTool } from "./tools/tee.js";
|
|
42
|
+
import { touchTool } from "./tools/touch.js";
|
|
43
|
+
import { trTool } from "./tools/tr.js";
|
|
44
|
+
import { trashTool } from "./tools/trash.js";
|
|
45
|
+
import { truncateTool } from "./tools/truncate.js";
|
|
46
|
+
import { uniqTool } from "./tools/uniq.js";
|
|
47
|
+
import { wcTool } from "./tools/wc.js";
|
|
48
|
+
import { unzipTool, zipTool } from "./tools/zip.js";
|
|
49
|
+
|
|
50
|
+
type AnyTool = ToolSpec<any>;
|
|
51
|
+
|
|
52
|
+
const TOOLS: readonly AnyTool[] = [
|
|
53
|
+
mkdirTool,
|
|
54
|
+
rmdirTool,
|
|
55
|
+
rmTool,
|
|
56
|
+
cpTool,
|
|
57
|
+
mvTool,
|
|
58
|
+
lsTool,
|
|
59
|
+
statTool,
|
|
60
|
+
touchTool,
|
|
61
|
+
truncateTool,
|
|
62
|
+
lnTool,
|
|
63
|
+
readlinkTool,
|
|
64
|
+
chmodTool,
|
|
65
|
+
hashTool,
|
|
66
|
+
duTool,
|
|
67
|
+
dfTool,
|
|
68
|
+
findTool,
|
|
69
|
+
mktempTool,
|
|
70
|
+
trashTool,
|
|
71
|
+
gzipTool,
|
|
72
|
+
gunzipTool,
|
|
73
|
+
tarTool,
|
|
74
|
+
zipTool,
|
|
75
|
+
unzipTool,
|
|
76
|
+
diffTool,
|
|
77
|
+
catTool,
|
|
78
|
+
headTool,
|
|
79
|
+
tailTool,
|
|
80
|
+
teeTool,
|
|
81
|
+
wcTool,
|
|
82
|
+
sortTool,
|
|
83
|
+
uniqTool,
|
|
84
|
+
cutTool,
|
|
85
|
+
trTool,
|
|
86
|
+
sedTool,
|
|
87
|
+
grepTool,
|
|
88
|
+
pipeTool,
|
|
89
|
+
];
|
|
90
|
+
|
|
91
|
+
const DEFAULT_MAX_OUTPUT = 1024 * 1024;
|
|
92
|
+
|
|
93
|
+
export default Plugin.define({
|
|
94
|
+
id: "opencode-fs-plugin",
|
|
95
|
+
async setup(ctx) {
|
|
96
|
+
const rawRoot =
|
|
97
|
+
(typeof ctx.options?.root === "string" && ctx.options.root) ||
|
|
98
|
+
ctx.location?.project?.canonical ||
|
|
99
|
+
ctx.location?.directory ||
|
|
100
|
+
"";
|
|
101
|
+
if (!rawRoot) {
|
|
102
|
+
throw new Error("opencode-fs-plugin: could not determine a sandbox root.");
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const sandbox = await Sandbox.create(rawRoot);
|
|
106
|
+
const concurrency = clampConcurrency(
|
|
107
|
+
typeof ctx.options?.concurrency === "number" ? ctx.options.concurrency : undefined,
|
|
108
|
+
);
|
|
109
|
+
const maxOutputBytes =
|
|
110
|
+
typeof ctx.options?.maxOutputBytes === "number" && ctx.options.maxOutputBytes > 0
|
|
111
|
+
? Math.trunc(ctx.options.maxOutputBytes)
|
|
112
|
+
: DEFAULT_MAX_OUTPUT;
|
|
113
|
+
|
|
114
|
+
await ctx.tool.transform((editor) => {
|
|
115
|
+
editor.namespace({
|
|
116
|
+
name: "fs",
|
|
117
|
+
description: "Linux-style filesystem and text tools with native command semantics.",
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
for (const spec of TOOLS) {
|
|
121
|
+
editor.add({
|
|
122
|
+
name: spec.name,
|
|
123
|
+
description: spec.description,
|
|
124
|
+
input: spec.schema,
|
|
125
|
+
options: { namespace: "fs", permission: `fs_${spec.name}` },
|
|
126
|
+
execute: async (input, context) => {
|
|
127
|
+
try {
|
|
128
|
+
const parsed = parseSchema<unknown>(spec.schema, input, `${spec.name} input`);
|
|
129
|
+
const assertPermission: PermissionAssert = async (request) => {
|
|
130
|
+
await ctx.permission.assert(
|
|
131
|
+
request as unknown as Parameters<typeof ctx.permission.assert>[0],
|
|
132
|
+
);
|
|
133
|
+
};
|
|
134
|
+
const permissionFor = (action: string) =>
|
|
135
|
+
new PermissionGate(
|
|
136
|
+
{
|
|
137
|
+
sessionID: context.sessionID,
|
|
138
|
+
agent: context.agent,
|
|
139
|
+
messageID: context.messageID,
|
|
140
|
+
id: context.id,
|
|
141
|
+
},
|
|
142
|
+
action,
|
|
143
|
+
/* v8 ignore next */
|
|
144
|
+
(full) => sandbox.resource(full),
|
|
145
|
+
assertPermission,
|
|
146
|
+
);
|
|
147
|
+
const result = await spec.run(
|
|
148
|
+
{
|
|
149
|
+
sandbox,
|
|
150
|
+
permission: permissionFor(`fs_${spec.name}`),
|
|
151
|
+
permissionFor,
|
|
152
|
+
concurrency,
|
|
153
|
+
signal: context.signal,
|
|
154
|
+
tmpdir: os.tmpdir(),
|
|
155
|
+
maxOutputBytes,
|
|
156
|
+
},
|
|
157
|
+
parsed,
|
|
158
|
+
{},
|
|
159
|
+
);
|
|
160
|
+
return renderResult(result, maxOutputBytes);
|
|
161
|
+
} catch (error) {
|
|
162
|
+
if (error instanceof FsError) {
|
|
163
|
+
return renderError(error, error.code === "outside");
|
|
164
|
+
}
|
|
165
|
+
throw error;
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
},
|
|
172
|
+
});
|
package/src/tools/cat.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
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 concatenate. Omit to read stdin." })),
|
|
13
|
+
number: Type.Optional(Type.Boolean({ description: "Number all output lines (`-n`)." })),
|
|
14
|
+
numberNonBlank: Type.Optional(Type.Boolean({ description: "Number only non-blank lines (`-b`)." })),
|
|
15
|
+
squeezeBlank: Type.Optional(Type.Boolean({ description: "Collapse repeated blank lines (`-s`)." })),
|
|
16
|
+
showEnds: Type.Optional(Type.Boolean({ description: "Show line ends as `$` (`-E`)." })),
|
|
17
|
+
showTabs: Type.Optional(Type.Boolean({ description: "Show tabs as `^I` (`-T`)." })),
|
|
18
|
+
showNonPrinting: Type.Optional(Type.Boolean({ description: "Show non-printing characters (`-v`)." })),
|
|
19
|
+
},
|
|
20
|
+
{ additionalProperties: false },
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
type Input = Static<typeof Schema>;
|
|
24
|
+
|
|
25
|
+
export const catTool: ToolSpec<Input> = {
|
|
26
|
+
name: "cat",
|
|
27
|
+
description:
|
|
28
|
+
"Concatenate files or stdin with Linux `cat` semantics (`-n`, `-b`, `-s`, `-E`, `-T`, `-A`, `-v`).",
|
|
29
|
+
schema: Schema,
|
|
30
|
+
pipeable: "source",
|
|
31
|
+
mutates: false,
|
|
32
|
+
async run(ctx, input, io) {
|
|
33
|
+
const paths = await resolvePaths(ctx, input.paths ?? []);
|
|
34
|
+
const stream = inputStream(paths.map((entry) => entry.full), io.stdin);
|
|
35
|
+
if (
|
|
36
|
+
input.number !== true &&
|
|
37
|
+
input.numberNonBlank !== true &&
|
|
38
|
+
input.squeezeBlank !== true &&
|
|
39
|
+
input.showEnds !== true &&
|
|
40
|
+
input.showTabs !== true &&
|
|
41
|
+
input.showNonPrinting !== true
|
|
42
|
+
) {
|
|
43
|
+
return { stdout: await collect(stream), exitCode: 0, metadata: { paths: input.paths ?? [] } };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const output: string[] = [];
|
|
47
|
+
let number = 0;
|
|
48
|
+
let blank = false;
|
|
49
|
+
for await (const line of lines(stream)) {
|
|
50
|
+
if (input.squeezeBlank === true && line.text === "") {
|
|
51
|
+
if (blank) continue;
|
|
52
|
+
blank = true;
|
|
53
|
+
} else {
|
|
54
|
+
blank = false;
|
|
55
|
+
}
|
|
56
|
+
let text = line.text;
|
|
57
|
+
if (input.showTabs === true || input.showNonPrinting === true) text = text.replaceAll("\t", "^I");
|
|
58
|
+
if (input.showNonPrinting === true) text = visible(text);
|
|
59
|
+
if (input.showEnds === true) text += "$";
|
|
60
|
+
if ((input.number === true || input.numberNonBlank === true) && (input.numberNonBlank !== true || text.length > 0)) {
|
|
61
|
+
number++;
|
|
62
|
+
text = `${String(number).padStart(6)} ${text}`;
|
|
63
|
+
}
|
|
64
|
+
output.push(text + (line.newline ? "\n" : ""));
|
|
65
|
+
}
|
|
66
|
+
return textResult(output.join(""), { paths: input.paths ?? [] });
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
async function resolvePaths(
|
|
71
|
+
ctx: Parameters<ToolSpec<Input>["run"]>[0],
|
|
72
|
+
paths: readonly string[],
|
|
73
|
+
): Promise<Array<{ requested: string; full: string }>> {
|
|
74
|
+
const targets = [];
|
|
75
|
+
for (const requested of paths) {
|
|
76
|
+
const target = await ctx.sandbox.resolveFollow(requested);
|
|
77
|
+
targets.push({ requested, full: target.full, target });
|
|
78
|
+
}
|
|
79
|
+
await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
|
|
80
|
+
return targets;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function visible(text: string): string {
|
|
84
|
+
return text.replace(/[\x00-\x08\x0b-\x1f\x7f]/g, (char) => {
|
|
85
|
+
const code = char.charCodeAt(0);
|
|
86
|
+
return `^${String.fromCharCode(code === 127 ? 63 : code + 64)}`;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
|
|
@@ -0,0 +1,93 @@
|
|
|
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 } from "../core/errors.js";
|
|
9
|
+
import { num, walk } from "../core/fsutil.js";
|
|
10
|
+
import { parseMode } from "../core/mode.js";
|
|
11
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
12
|
+
|
|
13
|
+
const Schema = Type.Object(
|
|
14
|
+
{
|
|
15
|
+
paths: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
|
|
16
|
+
mode: Type.Optional(Type.String({ description: "Octal or symbolic mode, e.g. 755 or u=rwx,go=rx." })),
|
|
17
|
+
reference: Type.Optional(Type.String({ description: "Use another file's mode (`--reference`)." })),
|
|
18
|
+
recursive: Type.Optional(Type.Boolean({ description: "Change modes recursively (`-R`)." })),
|
|
19
|
+
noDereference: Type.Optional(Type.Boolean({ description: "Refuse to follow symlinks (`-h`)." })),
|
|
20
|
+
verbose: Type.Optional(Type.Boolean({ description: "Report every changed path (`-v`)." })),
|
|
21
|
+
changes: Type.Optional(Type.Boolean({ description: "Report only actual changes (`-c`)." })),
|
|
22
|
+
silent: Type.Optional(Type.Boolean({ description: "Suppress most errors (`-f`)." })),
|
|
23
|
+
},
|
|
24
|
+
{ additionalProperties: false },
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
type Input = Static<typeof Schema>;
|
|
28
|
+
|
|
29
|
+
export const chmodTool: ToolSpec<Input> = {
|
|
30
|
+
name: "chmod",
|
|
31
|
+
description:
|
|
32
|
+
"Change file modes with Linux `chmod` semantics (`-R`, `--reference`, `-v`, `-c`, `-f`). " +
|
|
33
|
+
"Supports octal and symbolic modes.",
|
|
34
|
+
schema: Schema,
|
|
35
|
+
pipeable: false,
|
|
36
|
+
mutates: true,
|
|
37
|
+
async run(ctx, input) {
|
|
38
|
+
if (input.mode === undefined && input.reference === undefined) {
|
|
39
|
+
throw new FsError("mode or reference is required.", "invalid");
|
|
40
|
+
}
|
|
41
|
+
const referenceMode =
|
|
42
|
+
input.reference === undefined
|
|
43
|
+
? undefined
|
|
44
|
+
: num((await ctx.sandbox.lstat((await ctx.sandbox.resolveExisting(input.reference, { allowRoot: true })).full, input.reference)).mode) & 0o7777;
|
|
45
|
+
|
|
46
|
+
const changed: string[] = [];
|
|
47
|
+
for (const requested of input.paths) {
|
|
48
|
+
const root = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
|
|
49
|
+
ctx.sandbox.assertSafeToDelete(root.full);
|
|
50
|
+
const targets = [root];
|
|
51
|
+
if (input.recursive === true) {
|
|
52
|
+
const rootStats = await ctx.sandbox.lstat(root.full, requested);
|
|
53
|
+
if (rootStats.isDirectory()) {
|
|
54
|
+
for await (const entry of walk(root.full, { recursive: true, signal: ctx.signal })) {
|
|
55
|
+
targets.push({
|
|
56
|
+
full: entry.path,
|
|
57
|
+
outside: root.outside,
|
|
58
|
+
requested: entry.path,
|
|
59
|
+
realAncestor: root.realAncestor,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
await ctx.permission.assert(targets.map((target) => ({ target, boundary: target.full })));
|
|
65
|
+
|
|
66
|
+
for (const target of targets) {
|
|
67
|
+
const stats = input.noDereference === true
|
|
68
|
+
? await ctx.sandbox.lstat(target.full, target.requested)
|
|
69
|
+
: await ctx.sandbox.stat(target.full, target.requested);
|
|
70
|
+
if (input.noDereference === true && stats.isSymbolicLink()) {
|
|
71
|
+
throw new FsError(`"${target.requested}" is a symlink; -h is not supported on this platform.`, "unsupported");
|
|
72
|
+
}
|
|
73
|
+
const nextMode = referenceMode ?? parseMode(input.mode as string, num(stats.mode) & 0o7777, stats.isDirectory());
|
|
74
|
+
if (input.changes === true && (num(stats.mode) & 0o7777) === nextMode) continue;
|
|
75
|
+
try {
|
|
76
|
+
await fs.chmod(target.full, nextMode);
|
|
77
|
+
} catch (error) {
|
|
78
|
+
/* v8 ignore next 3 */
|
|
79
|
+
if (input.silent === true) continue;
|
|
80
|
+
/* v8 ignore next */
|
|
81
|
+
throw fromErrno(error);
|
|
82
|
+
}
|
|
83
|
+
changed.push(target.requested);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return textResult(
|
|
87
|
+
input.verbose === true || input.changes === true
|
|
88
|
+
? changed.map((item) => `mode of '${item}' changed`).join("\n")
|
|
89
|
+
: "",
|
|
90
|
+
{ changed },
|
|
91
|
+
);
|
|
92
|
+
},
|
|
93
|
+
};
|
package/src/tools/cp.ts
ADDED
|
@@ -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 { Type, type Static } from "@sinclair/typebox";
|
|
9
|
+
import { FsError, fromErrno, isMissing } from "../core/errors.js";
|
|
10
|
+
import { copyTree, isSubpath } from "../core/fsutil.js";
|
|
11
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
12
|
+
|
|
13
|
+
const Schema = Type.Object(
|
|
14
|
+
{
|
|
15
|
+
sources: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
|
|
16
|
+
destination: Type.String({ minLength: 1 }),
|
|
17
|
+
recursive: Type.Optional(Type.Boolean({ description: "Copy directories recursively (`-r`, `-R`)." })),
|
|
18
|
+
archive: Type.Optional(Type.Boolean({ description: "Archive mode (`-a`): recursive, preserve, keep symlinks." })),
|
|
19
|
+
force: Type.Optional(Type.Boolean({ description: "Overwrite existing destinations (`-f`)." })),
|
|
20
|
+
noClobber: Type.Optional(Type.Boolean({ description: "Never overwrite existing files (`-n`)." })),
|
|
21
|
+
update: Type.Optional(Type.Boolean({ description: "Copy only when the source is newer (`-u`)." })),
|
|
22
|
+
preserve: Type.Optional(Type.Boolean({ description: "Preserve mode and timestamps (`-p`)." })),
|
|
23
|
+
dereference: Type.Optional(Type.Boolean({ description: "Follow source symlinks (`-L`); default true." })),
|
|
24
|
+
verbose: Type.Optional(Type.Boolean({ description: "Report copied paths (`-v`)." })),
|
|
25
|
+
},
|
|
26
|
+
{ additionalProperties: false },
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
type Input = Static<typeof Schema>;
|
|
30
|
+
|
|
31
|
+
interface Source {
|
|
32
|
+
requested: string;
|
|
33
|
+
full: string;
|
|
34
|
+
isDirectory: boolean;
|
|
35
|
+
isSymlink: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const cpTool: ToolSpec<Input> = {
|
|
39
|
+
name: "cp",
|
|
40
|
+
description:
|
|
41
|
+
"Copy files and directories with Linux `cp` semantics (`-r`, `-a`, `-f`, `-n`, `-u`, " +
|
|
42
|
+
"`-p`, `-L`, `-v`). Multiple sources require a directory destination.",
|
|
43
|
+
schema: Schema,
|
|
44
|
+
pipeable: false,
|
|
45
|
+
mutates: true,
|
|
46
|
+
async run(ctx, input) {
|
|
47
|
+
const archive = input.archive === true;
|
|
48
|
+
const recursive = archive || input.recursive === true;
|
|
49
|
+
const dereference = archive ? false : input.dereference !== false;
|
|
50
|
+
const preserve = archive || input.preserve === true;
|
|
51
|
+
|
|
52
|
+
const sources: Source[] = [];
|
|
53
|
+
for (const requested of input.sources) {
|
|
54
|
+
const target = dereference
|
|
55
|
+
? await ctx.sandbox.resolveFollow(requested)
|
|
56
|
+
: await ctx.sandbox.resolveExisting(requested);
|
|
57
|
+
const stats = dereference
|
|
58
|
+
? await ctx.sandbox.stat(target.full, requested)
|
|
59
|
+
: await ctx.sandbox.lstat(target.full, requested);
|
|
60
|
+
/* v8 ignore next */
|
|
61
|
+
if (stats.isDirectory() && !recursive) {
|
|
62
|
+
throw new FsError(`"${requested}" is a directory; recursive is required.`, "not-file");
|
|
63
|
+
}
|
|
64
|
+
sources.push({
|
|
65
|
+
requested,
|
|
66
|
+
full: target.full,
|
|
67
|
+
isDirectory: stats.isDirectory(),
|
|
68
|
+
isSymlink: !dereference && stats.isSymbolicLink(),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const destTarget = await ctx.sandbox.resolveForCreate(input.destination);
|
|
73
|
+
let destIsDirectory = false;
|
|
74
|
+
try {
|
|
75
|
+
destIsDirectory = (await fs.lstat(destTarget.full)).isDirectory();
|
|
76
|
+
} catch (error) {
|
|
77
|
+
/* v8 ignore next 2 */
|
|
78
|
+
if (!isMissing(error)) throw fromErrno(error, "access");
|
|
79
|
+
}
|
|
80
|
+
if (sources.length > 1 && !destIsDirectory) {
|
|
81
|
+
throw new FsError("Multiple sources require an existing directory destination.", "not-directory");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const jobs = sources.map((source) => ({
|
|
85
|
+
source,
|
|
86
|
+
destination:
|
|
87
|
+
destIsDirectory || sources.length > 1
|
|
88
|
+
? path.join(destTarget.full, path.basename(path.resolve(source.requested)))
|
|
89
|
+
: destTarget.full,
|
|
90
|
+
}));
|
|
91
|
+
|
|
92
|
+
for (const job of jobs) {
|
|
93
|
+
if (job.source.full === job.destination) {
|
|
94
|
+
throw new FsError(`"${job.source.requested}" and destination are the same file.`, "invalid");
|
|
95
|
+
}
|
|
96
|
+
if (job.source.isDirectory && isSubpath(job.source.full, job.destination)) {
|
|
97
|
+
throw new FsError(`Cannot copy a directory into itself: "${job.source.requested}".`, "invalid");
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const entries = [];
|
|
102
|
+
for (const source of sources) {
|
|
103
|
+
const target = dereference
|
|
104
|
+
? await ctx.sandbox.resolveFollow(source.requested)
|
|
105
|
+
: await ctx.sandbox.resolveExisting(source.requested);
|
|
106
|
+
entries.push({
|
|
107
|
+
target,
|
|
108
|
+
boundary: source.isDirectory ? target.full : path.dirname(target.full),
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
for (const job of jobs) {
|
|
112
|
+
const target = await ctx.sandbox.resolveForCreate(job.destination);
|
|
113
|
+
entries.push({ target, boundary: path.dirname(target.full) });
|
|
114
|
+
}
|
|
115
|
+
await ctx.permission.assert(entries);
|
|
116
|
+
|
|
117
|
+
const copied = await Promise.all(
|
|
118
|
+
jobs.map((job) =>
|
|
119
|
+
copyTree(job.source.full, job.destination, {
|
|
120
|
+
recursive,
|
|
121
|
+
dereference,
|
|
122
|
+
preserve,
|
|
123
|
+
noClobber: input.noClobber === true,
|
|
124
|
+
update: input.update === true,
|
|
125
|
+
signal: ctx.signal,
|
|
126
|
+
concurrency: ctx.concurrency,
|
|
127
|
+
}),
|
|
128
|
+
),
|
|
129
|
+
);
|
|
130
|
+
const total = copied.reduce((sum, value) => sum + value, 0);
|
|
131
|
+
const output = input.verbose === true
|
|
132
|
+
? jobs.map((job) => `'${job.source.requested}' -> '${job.destination}'`).join("\n")
|
|
133
|
+
: "";
|
|
134
|
+
return textResult(output, { copied: total, jobs: jobs.length, force: input.force === true });
|
|
135
|
+
},
|
|
136
|
+
};
|
package/src/tools/cut.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
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 { FsError } from "../core/errors.js";
|
|
8
|
+
import { inputStream, lines } from "../core/stream.js";
|
|
9
|
+
import { textResult, type ToolSpec } from "../core/types.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
|
+
fields: Type.Optional(Type.String({ description: "Field list, e.g. 1,3-5 (`-f`)." })),
|
|
15
|
+
characters: Type.Optional(Type.String({ description: "Character list (`-c`)." })),
|
|
16
|
+
bytes: Type.Optional(Type.String({ description: "Byte list (`-b`)." })),
|
|
17
|
+
delimiter: Type.Optional(Type.String({ description: "Input field delimiter (`-d`). Default: tab." })),
|
|
18
|
+
outputDelimiter: Type.Optional(Type.String({ description: "Output field delimiter (`--output-delimiter`)." })),
|
|
19
|
+
complement: Type.Optional(Type.Boolean({ description: "Select the complement (`--complement`)." })),
|
|
20
|
+
onlyDelimited: Type.Optional(Type.Boolean({ description: "Print lines without the delimiter unchanged (`-s`)." })),
|
|
21
|
+
},
|
|
22
|
+
{ additionalProperties: false },
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
type Input = Static<typeof Schema>;
|
|
26
|
+
|
|
27
|
+
export const cutTool: ToolSpec<Input> = {
|
|
28
|
+
name: "cut",
|
|
29
|
+
description:
|
|
30
|
+
"Select fields, characters or bytes with Linux `cut` semantics (`-f`, `-c`, `-b`, `-d`, " +
|
|
31
|
+
"`--complement`, `--output-delimiter`, `-s`).",
|
|
32
|
+
schema: Schema,
|
|
33
|
+
pipeable: "filter",
|
|
34
|
+
mutates: false,
|
|
35
|
+
async run(ctx, input, io) {
|
|
36
|
+
const mode = input.fields !== undefined ? "fields" : input.characters !== undefined ? "chars" : input.bytes !== undefined ? "bytes" : "";
|
|
37
|
+
if (!mode) throw new FsError("cut requires fields, characters, or bytes.", "invalid");
|
|
38
|
+
/* v8 ignore next */
|
|
39
|
+
const ranges = parseRanges(input.fields ?? input.characters ?? input.bytes ?? "");
|
|
40
|
+
const paths = input.paths ?? [];
|
|
41
|
+
const targets = [];
|
|
42
|
+
for (const requested of paths) {
|
|
43
|
+
const target = await ctx.sandbox.resolveFollow(requested);
|
|
44
|
+
targets.push({ requested, full: target.full, target });
|
|
45
|
+
}
|
|
46
|
+
if (targets.length > 0) {
|
|
47
|
+
await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const output: string[] = [];
|
|
51
|
+
for await (const line of lines(inputStream(targets.map((target) => target.full), io.stdin))) {
|
|
52
|
+
if (mode === "fields") {
|
|
53
|
+
const delimiter = input.delimiter ?? "\t";
|
|
54
|
+
if (input.onlyDelimited === true && !line.text.includes(delimiter)) {
|
|
55
|
+
output.push(line.text);
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const fields = line.text.split(delimiter);
|
|
59
|
+
const selected = select(fields, ranges, input.complement === true);
|
|
60
|
+
output.push(selected.join(input.outputDelimiter ?? delimiter));
|
|
61
|
+
} else {
|
|
62
|
+
const units = mode === "chars" ? Array.from(line.text) : [...Buffer.from(line.text, "utf8")].map((byte) => String.fromCharCode(byte));
|
|
63
|
+
output.push(select(units, ranges, input.complement === true).join(""));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return textResult(output.map((line) => `${line}\n`).join(""), { lines: output.length });
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
export function parseRanges(value: string): Array<{ start: number; end: number }> {
|
|
71
|
+
const ranges: Array<{ start: number; end: number }> = [];
|
|
72
|
+
for (const part of value.split(",")) {
|
|
73
|
+
if (part.length === 0) continue;
|
|
74
|
+
const match = /^(\d+)(?:-(\d*))?$/.exec(part);
|
|
75
|
+
if (!match) throw new FsError(`Invalid field list: ${value}`, "invalid");
|
|
76
|
+
const start = Number(match[1]);
|
|
77
|
+
const end = match[2] === undefined ? start : match[2] === "" ? Number.POSITIVE_INFINITY : Number(match[2]);
|
|
78
|
+
if (start < 1 || end < start) throw new FsError(`Invalid field range: ${part}`, "invalid");
|
|
79
|
+
ranges.push({ start, end });
|
|
80
|
+
}
|
|
81
|
+
if (ranges.length === 0) throw new FsError(`Invalid field list: ${value}`, "invalid");
|
|
82
|
+
return ranges;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function select<T>(items: T[], ranges: Array<{ start: number; end: number }>, complement: boolean): T[] {
|
|
86
|
+
const output: T[] = [];
|
|
87
|
+
for (let index = 0; index < items.length; index++) {
|
|
88
|
+
const position = index + 1;
|
|
89
|
+
const selected = ranges.some((range) => position >= range.start && position <= range.end);
|
|
90
|
+
if (selected !== complement) output.push(items[index] as T);
|
|
91
|
+
}
|
|
92
|
+
return output;
|
|
93
|
+
}
|