opencode-fs-plugin 1.4.3 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/INSTALL.md +9 -9
- package/README.md +37 -8
- package/SPEC.md +31 -0
- package/package.json +1 -1
- package/skills/filesystem/SKILL.md +34 -9
- package/src/core/errors.ts +1 -1
- package/src/core/fsutil.ts +44 -17
- package/src/core/magic.ts +51 -0
- package/src/core/procfs.ts +84 -0
- package/src/index.ts +52 -0
- package/src/tools/ar.ts +179 -0
- package/src/tools/base64.ts +63 -0
- package/src/tools/chown.ts +89 -0
- package/src/tools/comm.ts +85 -0
- package/src/tools/cpio.ts +259 -0
- package/src/tools/date.ts +61 -0
- package/src/tools/dd.ts +120 -0
- package/src/tools/file.ts +62 -0
- package/src/tools/findmnt.ts +74 -0
- package/src/tools/fold.ts +64 -0
- package/src/tools/id.ts +70 -0
- package/src/tools/kill.ts +60 -0
- package/src/tools/mountpoint.ts +57 -0
- package/src/tools/nl.ts +51 -0
- package/src/tools/od.ts +58 -0
- package/src/tools/paste.ts +78 -0
- package/src/tools/pgrep.ts +59 -0
- package/src/tools/pipe.ts +13 -1
- package/src/tools/ps.ts +88 -0
- package/src/tools/rev.ts +41 -0
- package/src/tools/shuf.ts +49 -0
- package/src/tools/split.ts +103 -0
- package/src/tools/strings.ts +57 -0
- package/src/tools/sync.ts +51 -0
- package/src/tools/tac.ts +40 -0
- package/src/tools/uname.ts +45 -0
- package/src/tools/uptime.ts +46 -0
package/src/tools/ar.ts
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
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 } from "../core/errors.js";
|
|
10
|
+
import { num } from "../core/fsutil.js";
|
|
11
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
12
|
+
|
|
13
|
+
const Schema = Type.Object(
|
|
14
|
+
{
|
|
15
|
+
mode: Type.Union([Type.Literal("create"), Type.Literal("list"), Type.Literal("extract")], {
|
|
16
|
+
description: "Operation.",
|
|
17
|
+
}),
|
|
18
|
+
archive: Type.String({ minLength: 1, description: "Archive path." }),
|
|
19
|
+
paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Files to archive (create)." })),
|
|
20
|
+
directory: Type.Optional(Type.String({ description: "Extraction directory. Default: current." })),
|
|
21
|
+
members: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Only these members." })),
|
|
22
|
+
},
|
|
23
|
+
{ additionalProperties: false },
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
type Input = Static<typeof Schema>;
|
|
27
|
+
|
|
28
|
+
interface Member {
|
|
29
|
+
readonly name: string;
|
|
30
|
+
readonly mode: number;
|
|
31
|
+
readonly mtime: number;
|
|
32
|
+
readonly uid: number;
|
|
33
|
+
readonly gid: number;
|
|
34
|
+
readonly data: Buffer;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const MAGIC = "!<arch>\n";
|
|
38
|
+
|
|
39
|
+
export const arTool: ToolSpec<Input> = {
|
|
40
|
+
name: "ar",
|
|
41
|
+
description:
|
|
42
|
+
"Create, list, or extract Unix `ar` archives (GNU short names, mode and mtime preserved on create).",
|
|
43
|
+
schema: Schema,
|
|
44
|
+
pipeable: false,
|
|
45
|
+
mutates: true,
|
|
46
|
+
async run(ctx, input) {
|
|
47
|
+
const archive = input.mode === "create"
|
|
48
|
+
? await ctx.sandbox.resolveForCreate(input.archive)
|
|
49
|
+
: await ctx.sandbox.resolveFollow(input.archive);
|
|
50
|
+
await ctx.permission.assert([{ target: archive, boundary: archive.full }]);
|
|
51
|
+
|
|
52
|
+
if (input.mode === "create") {
|
|
53
|
+
if (input.paths === undefined || input.paths.length === 0) {
|
|
54
|
+
throw new FsError("create requires paths.", "invalid");
|
|
55
|
+
}
|
|
56
|
+
const members: Member[] = [];
|
|
57
|
+
for (const requested of input.paths) {
|
|
58
|
+
const target = await ctx.sandbox.resolveFollow(requested);
|
|
59
|
+
await ctx.permission.assert([{ target, boundary: target.full }]);
|
|
60
|
+
const stats = await ctx.sandbox.stat(target.full, requested);
|
|
61
|
+
if (!stats.isFile()) throw new FsError(`Not a regular file: "${requested}".`, "not-file");
|
|
62
|
+
const name = path.basename(requested);
|
|
63
|
+
if (Buffer.byteLength(name) > 16) {
|
|
64
|
+
throw new FsError(`Member name too long for the short ar format: "${name}".`, "invalid");
|
|
65
|
+
}
|
|
66
|
+
members.push({
|
|
67
|
+
name,
|
|
68
|
+
mode: Number(stats.mode) & 0o7777,
|
|
69
|
+
mtime: Math.floor(num(stats.mtimeMs) / 1000),
|
|
70
|
+
uid: Number(stats.uid),
|
|
71
|
+
gid: Number(stats.gid),
|
|
72
|
+
/* v8 ignore next 3 -- reading a stat-ed file normally succeeds */
|
|
73
|
+
data: await fs.readFile(target.full).catch((error: unknown) => {
|
|
74
|
+
throw fromErrno(error);
|
|
75
|
+
}),
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
/* v8 ignore next 4 -- write errors are environment-dependent */
|
|
79
|
+
try {
|
|
80
|
+
await fs.writeFile(archive.full, encode(members));
|
|
81
|
+
} catch (error) {
|
|
82
|
+
throw fromErrno(error);
|
|
83
|
+
}
|
|
84
|
+
return textResult("", { archive: input.archive, members: members.map((member) => member.name) });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
let data: Buffer;
|
|
88
|
+
/* v8 ignore next 4 -- read errors are environment-dependent */
|
|
89
|
+
try {
|
|
90
|
+
data = await fs.readFile(archive.full);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
throw fromErrno(error);
|
|
93
|
+
}
|
|
94
|
+
const all = decode(data);
|
|
95
|
+
const wanted = input.members === undefined ? undefined : new Set(input.members);
|
|
96
|
+
const selected = wanted === undefined ? all : all.filter((member) => wanted.has(member.name));
|
|
97
|
+
|
|
98
|
+
if (input.mode === "list") {
|
|
99
|
+
return textResult(`${selected.map((member) => member.name).join("\n")}\n`, { members: selected.length });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const base = input.directory === undefined
|
|
103
|
+
? (await ctx.sandbox.resolveForCreate(".")).full
|
|
104
|
+
: (await ctx.sandbox.resolveForCreate(input.directory)).full;
|
|
105
|
+
for (const member of selected) {
|
|
106
|
+
const target = path.join(base, safeName(member.name));
|
|
107
|
+
await ctx.permission.assert([{
|
|
108
|
+
target: { full: target, outside: false, requested: target, realAncestor: base },
|
|
109
|
+
boundary: target,
|
|
110
|
+
}]);
|
|
111
|
+
/* v8 ignore next 5 -- write errors are environment-dependent */
|
|
112
|
+
try {
|
|
113
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
114
|
+
await fs.writeFile(target, member.data);
|
|
115
|
+
await fs.chmod(target, member.mode);
|
|
116
|
+
} catch (error) {
|
|
117
|
+
throw fromErrno(error);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return textResult("", { extracted: selected.length });
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
function encode(members: readonly Member[]): Buffer {
|
|
125
|
+
const chunks: Buffer[] = [Buffer.from(MAGIC, "ascii")];
|
|
126
|
+
for (const member of members) {
|
|
127
|
+
const header = [
|
|
128
|
+
`${member.name}/`.padEnd(16, " "),
|
|
129
|
+
String(member.mtime).padStart(12, " ").slice(-12),
|
|
130
|
+
String(member.uid).padStart(6, " ").slice(-6),
|
|
131
|
+
String(member.gid).padStart(6, " ").slice(-6),
|
|
132
|
+
member.mode.toString(8).padStart(8, " ").slice(-8),
|
|
133
|
+
String(member.data.length).padStart(10, " ").slice(-10),
|
|
134
|
+
"`\n",
|
|
135
|
+
].join("");
|
|
136
|
+
chunks.push(Buffer.from(header, "ascii"), member.data);
|
|
137
|
+
if (member.data.length % 2 === 1) chunks.push(Buffer.from("\n", "ascii"));
|
|
138
|
+
}
|
|
139
|
+
return Buffer.concat(chunks);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function decode(data: Buffer): Member[] {
|
|
143
|
+
if (data.subarray(0, MAGIC.length).toString("ascii") !== MAGIC) {
|
|
144
|
+
throw new FsError("Not an ar archive.", "archive");
|
|
145
|
+
}
|
|
146
|
+
const members: Member[] = [];
|
|
147
|
+
let offset = MAGIC.length;
|
|
148
|
+
while (offset + 60 <= data.length) {
|
|
149
|
+
const header = data.subarray(offset, offset + 60).toString("ascii");
|
|
150
|
+
if (header.slice(58, 60) !== "`\n") throw new FsError("Corrupt ar header.", "archive");
|
|
151
|
+
const name = header.slice(0, 16).trim().replace(/\/$/, "");
|
|
152
|
+
const size = Number.parseInt(header.slice(48, 58).trim(), 10);
|
|
153
|
+
const dataStart = offset + 60;
|
|
154
|
+
if (Number.isNaN(size) || dataStart + size > data.length) {
|
|
155
|
+
throw new FsError("Truncated ar member.", "archive");
|
|
156
|
+
}
|
|
157
|
+
if (name !== "" && name !== "/" && !name.startsWith("/")) {
|
|
158
|
+
members.push({
|
|
159
|
+
name,
|
|
160
|
+
mtime: Number.parseInt(header.slice(16, 28).trim(), 10) || 0,
|
|
161
|
+
uid: Number.parseInt(header.slice(28, 34).trim(), 10) || 0,
|
|
162
|
+
gid: Number.parseInt(header.slice(34, 40).trim(), 10) || 0,
|
|
163
|
+
mode: Number.parseInt(header.slice(40, 48).trim(), 8) || 0o644,
|
|
164
|
+
data: data.subarray(dataStart, dataStart + size),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
offset = dataStart + size + (size % 2);
|
|
168
|
+
}
|
|
169
|
+
return members;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function safeName(name: string): string {
|
|
173
|
+
const normalized = name.replaceAll("\\", "/").replace(/^\/+/, "");
|
|
174
|
+
const parts = normalized.split("/").filter((part) => part !== "" && part !== ".");
|
|
175
|
+
if (parts.length === 0 || parts.includes("..")) {
|
|
176
|
+
throw new FsError(`Unsafe archive member: "${name}".`, "archive");
|
|
177
|
+
}
|
|
178
|
+
return parts.join("/");
|
|
179
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
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 { collect, inputStream } from "../core/stream.js";
|
|
9
|
+
import { textResult, type ToolSpec, type ToolResult } 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
|
+
decode: Type.Optional(Type.Boolean({ description: "Decode base64 instead of encoding (`-d`)." })),
|
|
15
|
+
wrap: Type.Optional(
|
|
16
|
+
Type.Integer({ minimum: 0, maximum: 4096, description: "Encoded line width; 0 disables wrapping. Default: 76." }),
|
|
17
|
+
),
|
|
18
|
+
ignoreGarbage: Type.Optional(Type.Boolean({ description: "Drop non-base64 characters while decoding (`-i`)." })),
|
|
19
|
+
},
|
|
20
|
+
{ additionalProperties: false },
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
type Input = Static<typeof Schema>;
|
|
24
|
+
|
|
25
|
+
export const base64Tool: ToolSpec<Input> = {
|
|
26
|
+
name: "base64",
|
|
27
|
+
description:
|
|
28
|
+
"Encode files or stdin as base64, or decode base64 (`-d`, `-i`, `-w`). Decoded bytes may be binary.",
|
|
29
|
+
schema: Schema,
|
|
30
|
+
pipeable: "source",
|
|
31
|
+
mutates: false,
|
|
32
|
+
async run(ctx, input, io): Promise<ToolResult> {
|
|
33
|
+
const targets = [];
|
|
34
|
+
for (const requested of input.paths ?? []) {
|
|
35
|
+
const target = await ctx.sandbox.resolveFollow(requested);
|
|
36
|
+
targets.push({ requested, full: target.full, target });
|
|
37
|
+
}
|
|
38
|
+
if (targets.length > 0) {
|
|
39
|
+
await ctx.permission.assert(targets.map(({ target }) => ({ target, boundary: target.full })));
|
|
40
|
+
}
|
|
41
|
+
const data = await collect(
|
|
42
|
+
inputStream(targets.map((target) => target.full), io.stdin),
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
if (input.decode !== true) {
|
|
46
|
+
const wrap = input.wrap ?? 76;
|
|
47
|
+
const encoded = data.toString("base64");
|
|
48
|
+
const body = wrap > 0
|
|
49
|
+
? encoded.replace(new RegExp(`.{1,${wrap}}`, "g"), "$&\n")
|
|
50
|
+
: `${encoded}\n`;
|
|
51
|
+
return textResult(body, { encoded: true, bytes: data.length });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const cleaned = input.ignoreGarbage === true
|
|
55
|
+
? data.toString("latin1").replace(/[^A-Za-z0-9+/=]/g, "")
|
|
56
|
+
: data.toString("latin1").replace(/\s+/g, "");
|
|
57
|
+
if (cleaned.length % 4 === 1 || !/^[A-Za-z0-9+/]*={0,2}$/.test(cleaned)) {
|
|
58
|
+
throw new FsError("Invalid base64 input.", "invalid");
|
|
59
|
+
}
|
|
60
|
+
const decoded = Buffer.from(cleaned, "base64");
|
|
61
|
+
return { stdout: decoded, exitCode: 0, metadata: { encoded: false, bytes: decoded.length } };
|
|
62
|
+
},
|
|
63
|
+
};
|
|
@@ -0,0 +1,89 @@
|
|
|
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 { resolveGid, resolveUid, walkAll } from "../core/fsutil.js";
|
|
10
|
+
import { mapLimit } from "../core/parallel.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, description: "Paths to change." }),
|
|
16
|
+
user: Type.Optional(Type.String({ description: "New owner name or uid." })),
|
|
17
|
+
uid: Type.Optional(Type.Integer({ minimum: 0, description: "New numeric owner uid." })),
|
|
18
|
+
group: Type.Optional(Type.String({ description: "New group name or gid." })),
|
|
19
|
+
gid: Type.Optional(Type.Integer({ minimum: 0, description: "New numeric group gid." })),
|
|
20
|
+
recursive: Type.Optional(Type.Boolean({ description: "Descend into directories (`-R`)." })),
|
|
21
|
+
noDereference: Type.Optional(Type.Boolean({ description: "Affect symlinks themselves (`-h`)." })),
|
|
22
|
+
},
|
|
23
|
+
{ additionalProperties: false },
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
type Input = Static<typeof Schema>;
|
|
27
|
+
|
|
28
|
+
export const chownTool: ToolSpec<Input> = {
|
|
29
|
+
name: "chown",
|
|
30
|
+
description:
|
|
31
|
+
"Change file owner and/or group by name or id (`-R`, `-h`). At least one of user or group is required.",
|
|
32
|
+
schema: Schema,
|
|
33
|
+
pipeable: false,
|
|
34
|
+
mutates: true,
|
|
35
|
+
async run(ctx, input) {
|
|
36
|
+
if (input.user !== undefined && input.uid !== undefined) {
|
|
37
|
+
throw new FsError("user and uid are mutually exclusive.", "invalid");
|
|
38
|
+
}
|
|
39
|
+
if (input.group !== undefined && input.gid !== undefined) {
|
|
40
|
+
throw new FsError("group and gid are mutually exclusive.", "invalid");
|
|
41
|
+
}
|
|
42
|
+
const uid = input.uid ?? (input.user === undefined ? undefined : await resolveUid(input.user));
|
|
43
|
+
const gid = input.gid ?? (input.group === undefined ? undefined : await resolveGid(input.group));
|
|
44
|
+
if (uid === undefined && gid === undefined) {
|
|
45
|
+
throw new FsError("at least one of user or group is required.", "invalid");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const targets = [];
|
|
49
|
+
for (const requested of input.paths) {
|
|
50
|
+
const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
|
|
51
|
+
targets.push({ requested, target });
|
|
52
|
+
}
|
|
53
|
+
const entries: Array<{ full: string; requested: string }> = [];
|
|
54
|
+
for (const { requested, target } of targets) {
|
|
55
|
+
entries.push({ full: target.full, requested });
|
|
56
|
+
if (input.recursive === true) {
|
|
57
|
+
const stats = await ctx.sandbox.lstat(target.full, requested);
|
|
58
|
+
if (stats.isDirectory()) {
|
|
59
|
+
for (const entry of await walkAll(target.full, {
|
|
60
|
+
recursive: true,
|
|
61
|
+
includeHidden: true,
|
|
62
|
+
concurrency: ctx.concurrency,
|
|
63
|
+
signal: ctx.signal,
|
|
64
|
+
})) {
|
|
65
|
+
entries.push({ full: entry.path, requested: entry.path });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
await ctx.permission.assert(entries.map((entry) => ({
|
|
71
|
+
target: { full: entry.full, outside: false, requested: entry.requested, realAncestor: entry.full },
|
|
72
|
+
boundary: entry.full,
|
|
73
|
+
})));
|
|
74
|
+
|
|
75
|
+
await mapLimit(entries, ctx.concurrency, async (entry) => {
|
|
76
|
+
try {
|
|
77
|
+
const stats = await fs.lstat(entry.full);
|
|
78
|
+
const nextUid = uid ?? Number(stats.uid);
|
|
79
|
+
const nextGid = gid ?? Number(stats.gid);
|
|
80
|
+
if (input.noDereference === true) await fs.lchown(entry.full, nextUid, nextGid);
|
|
81
|
+
else await fs.chown(entry.full, nextUid, nextGid);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
/* v8 ignore next -- chown failures are permission-dependent */
|
|
84
|
+
throw fromErrno(error);
|
|
85
|
+
}
|
|
86
|
+
}, ctx.signal);
|
|
87
|
+
return textResult("", { changed: entries.length, uid: uid ?? null, gid: gid ?? null });
|
|
88
|
+
},
|
|
89
|
+
};
|
|
@@ -0,0 +1,85 @@
|
|
|
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 { textResult, type ToolSpec } from "../core/types.js";
|
|
10
|
+
|
|
11
|
+
const Schema = Type.Object(
|
|
12
|
+
{
|
|
13
|
+
left: Type.String({ minLength: 1, description: "First sorted file." }),
|
|
14
|
+
right: Type.String({ minLength: 1, description: "Second sorted file." }),
|
|
15
|
+
suppress1: Type.Optional(Type.Boolean({ description: "Suppress column 1 (`-1`)." })),
|
|
16
|
+
suppress2: Type.Optional(Type.Boolean({ description: "Suppress column 2 (`-2`)." })),
|
|
17
|
+
suppress3: Type.Optional(Type.Boolean({ description: "Suppress column 3 (`-3`)." })),
|
|
18
|
+
outputDelimiter: Type.Optional(Type.String({ description: "Column separator. Default: tab." })),
|
|
19
|
+
},
|
|
20
|
+
{ additionalProperties: false },
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
type Input = Static<typeof Schema>;
|
|
24
|
+
|
|
25
|
+
export const commTool: ToolSpec<Input> = {
|
|
26
|
+
name: "comm",
|
|
27
|
+
description: "Compare two sorted files column by column (`-1`, `-2`, `-3`, `--output-delimiter`).",
|
|
28
|
+
schema: Schema,
|
|
29
|
+
pipeable: false,
|
|
30
|
+
mutates: false,
|
|
31
|
+
async run(ctx, input) {
|
|
32
|
+
const left = await resolve(ctx, input.left);
|
|
33
|
+
const right = await resolve(ctx, input.right);
|
|
34
|
+
let leftRows: string[];
|
|
35
|
+
let rightRows: string[];
|
|
36
|
+
try {
|
|
37
|
+
[leftRows, rightRows] = await Promise.all([
|
|
38
|
+
fs.readFile(left, "utf8").then((text) => splitLines(text)),
|
|
39
|
+
fs.readFile(right, "utf8").then((text) => splitLines(text)),
|
|
40
|
+
]);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
throw fromErrno(error);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const delimiter = input.outputDelimiter ?? "\t";
|
|
46
|
+
const output: string[] = [];
|
|
47
|
+
let leftIndex = 0;
|
|
48
|
+
let rightIndex = 0;
|
|
49
|
+
while (leftIndex < leftRows.length || rightIndex < rightRows.length) {
|
|
50
|
+
const leftValue = leftRows[leftIndex];
|
|
51
|
+
const rightValue = rightRows[rightIndex];
|
|
52
|
+
if (leftValue !== undefined && (rightValue === undefined || leftValue < rightValue)) {
|
|
53
|
+
if (input.suppress1 !== true) output.push(leftValue);
|
|
54
|
+
leftIndex++;
|
|
55
|
+
} else if (rightValue !== undefined && (leftValue === undefined || rightValue < leftValue)) {
|
|
56
|
+
if (input.suppress2 !== true) output.push(`${input.suppress1 === true ? "" : delimiter}${rightValue}`);
|
|
57
|
+
rightIndex++;
|
|
58
|
+
} else {
|
|
59
|
+
if (input.suppress3 !== true) {
|
|
60
|
+
const prefix = `${input.suppress1 === true ? "" : delimiter}${input.suppress2 === true ? "" : delimiter}`;
|
|
61
|
+
output.push(`${prefix}${leftValue}`);
|
|
62
|
+
}
|
|
63
|
+
leftIndex++;
|
|
64
|
+
rightIndex++;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return textResult(output.length > 0 ? `${output.join("\n")}\n` : "", { lines: output.length });
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
async function resolve(
|
|
72
|
+
ctx: Parameters<ToolSpec<Input>["run"]>[0],
|
|
73
|
+
requested: string,
|
|
74
|
+
): Promise<string> {
|
|
75
|
+
const target = await ctx.sandbox.resolveFollow(requested);
|
|
76
|
+
await ctx.permission.assert([{ target, boundary: target.full }]);
|
|
77
|
+
return target.full;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function splitLines(text: string): string[] {
|
|
81
|
+
const rows = text.split("\n");
|
|
82
|
+
/* v8 ignore next */
|
|
83
|
+
if (rows[rows.length - 1] === "") rows.pop();
|
|
84
|
+
return rows;
|
|
85
|
+
}
|
|
@@ -0,0 +1,259 @@
|
|
|
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 } from "../core/errors.js";
|
|
10
|
+
import { num, walkAll } from "../core/fsutil.js";
|
|
11
|
+
import { collect } from "../core/stream.js";
|
|
12
|
+
import { textResult, type ToolSpec } from "../core/types.js";
|
|
13
|
+
|
|
14
|
+
const Schema = Type.Object(
|
|
15
|
+
{
|
|
16
|
+
mode: Type.Union([Type.Literal("create"), Type.Literal("list"), Type.Literal("extract")], {
|
|
17
|
+
description: "Operation (`-o`, `-t`, `-i`).",
|
|
18
|
+
}),
|
|
19
|
+
archive: Type.String({ minLength: 1, description: "Archive path (`-F`)." }),
|
|
20
|
+
paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Members to create." })),
|
|
21
|
+
directory: Type.Optional(Type.String({ description: "Base directory for member names or extraction." })),
|
|
22
|
+
members: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Only these members." })),
|
|
23
|
+
input: Type.Optional(Type.String({ description: "Text data to archive when paths are omitted." })),
|
|
24
|
+
member: Type.Optional(Type.String({ description: "Archive member name for stream input." })),
|
|
25
|
+
verbose: Type.Optional(Type.Boolean({ description: "List processed members (`-v`)." })),
|
|
26
|
+
},
|
|
27
|
+
{ additionalProperties: false },
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
type Input = Static<typeof Schema>;
|
|
31
|
+
|
|
32
|
+
interface Entry {
|
|
33
|
+
readonly name: string;
|
|
34
|
+
readonly mode: number;
|
|
35
|
+
readonly uid: number;
|
|
36
|
+
readonly gid: number;
|
|
37
|
+
readonly mtime: number;
|
|
38
|
+
readonly data: Buffer;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const cpioTool: ToolSpec<Input> = {
|
|
42
|
+
name: "cpio",
|
|
43
|
+
description:
|
|
44
|
+
"Create, list, or extract newc cpio archives (`-o`, `-t`, `-i`); supports stdin create and traversal-safe extraction.",
|
|
45
|
+
schema: Schema,
|
|
46
|
+
pipeable: "sink",
|
|
47
|
+
mutates: true,
|
|
48
|
+
async run(ctx, input, io) {
|
|
49
|
+
const archive = input.mode === "create"
|
|
50
|
+
? await ctx.sandbox.resolveForCreate(input.archive)
|
|
51
|
+
: await ctx.sandbox.resolveFollow(input.archive);
|
|
52
|
+
await ctx.permission.assert([{ target: archive, boundary: archive.full }]);
|
|
53
|
+
|
|
54
|
+
if (input.mode === "create") {
|
|
55
|
+
const entries = await collectEntries(ctx, input, io);
|
|
56
|
+
const buffer = encode(entries);
|
|
57
|
+
/* v8 ignore next 4 -- write errors are environment-dependent */
|
|
58
|
+
try {
|
|
59
|
+
await fs.writeFile(archive.full, buffer);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
throw fromErrno(error);
|
|
62
|
+
}
|
|
63
|
+
return textResult(input.verbose === true ? `${entries.map((entry) => entry.name).join("\n")}\n` : "", {
|
|
64
|
+
archive: input.archive,
|
|
65
|
+
members: entries.length,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
let data: Buffer;
|
|
70
|
+
/* v8 ignore next 4 -- read errors are environment-dependent */
|
|
71
|
+
try {
|
|
72
|
+
data = await fs.readFile(archive.full);
|
|
73
|
+
} catch (error) {
|
|
74
|
+
throw fromErrno(error);
|
|
75
|
+
}
|
|
76
|
+
const entries = decode(data);
|
|
77
|
+
const wanted = input.members === undefined ? undefined : new Set(input.members);
|
|
78
|
+
const selected = wanted === undefined ? entries : entries.filter((entry) => wanted.has(entry.name));
|
|
79
|
+
|
|
80
|
+
if (input.mode === "list") {
|
|
81
|
+
return textResult(`${selected.map((entry) => entry.name).join("\n")}\n`, { members: selected.length });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const base = input.directory === undefined
|
|
85
|
+
? (await ctx.sandbox.resolveForCreate(".")).full
|
|
86
|
+
: (await ctx.sandbox.resolveForCreate(input.directory)).full;
|
|
87
|
+
for (const entry of selected) {
|
|
88
|
+
const target = path.join(base, safeName(entry.name));
|
|
89
|
+
await ctx.permission.assert([{
|
|
90
|
+
target: { full: target, outside: false, requested: target, realAncestor: base },
|
|
91
|
+
boundary: target,
|
|
92
|
+
}]);
|
|
93
|
+
}
|
|
94
|
+
for (const entry of selected) {
|
|
95
|
+
const target = path.join(base, safeName(entry.name));
|
|
96
|
+
/* v8 ignore next -- extraction write errors are environment-dependent */
|
|
97
|
+
try {
|
|
98
|
+
if ((entry.mode & 0o170000) === 0o040000) {
|
|
99
|
+
await fs.mkdir(target, { recursive: true });
|
|
100
|
+
} else if ((entry.mode & 0o170000) === 0o120000) {
|
|
101
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
102
|
+
await fs.symlink(entry.data.toString("utf8"), target);
|
|
103
|
+
} else {
|
|
104
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
105
|
+
await fs.writeFile(target, entry.data);
|
|
106
|
+
await fs.chmod(target, entry.mode & 0o7777);
|
|
107
|
+
}
|
|
108
|
+
} catch (error) {
|
|
109
|
+
throw fromErrno(error);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return textResult(input.verbose === true ? `${selected.map((entry) => entry.name).join("\n")}\n` : "", {
|
|
113
|
+
extracted: selected.length,
|
|
114
|
+
});
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
async function collectEntries(
|
|
119
|
+
ctx: Parameters<ToolSpec<Input>["run"]>[0],
|
|
120
|
+
input: Input,
|
|
121
|
+
io: Parameters<ToolSpec<Input>["run"]>[2],
|
|
122
|
+
): Promise<Entry[]> {
|
|
123
|
+
if (input.paths === undefined || input.paths.length === 0) {
|
|
124
|
+
if (input.input === undefined && io.stdin === undefined) {
|
|
125
|
+
throw new FsError("create requires paths, input, or stdin.", "invalid");
|
|
126
|
+
}
|
|
127
|
+
const data = io.stdin === undefined
|
|
128
|
+
? Buffer.from(input.input as string, "utf8")
|
|
129
|
+
: await collect(io.stdin);
|
|
130
|
+
const name = safeName(input.member ?? "stdin");
|
|
131
|
+
return [{ name, mode: 0o100644, uid: 0, gid: 0, mtime: now(), data }];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const base = input.directory === undefined
|
|
135
|
+
? ctx.sandbox.root
|
|
136
|
+
: (await ctx.sandbox.resolveExisting(input.directory, { allowRoot: true })).full;
|
|
137
|
+
const entries: Entry[] = [];
|
|
138
|
+
for (const requested of input.paths) {
|
|
139
|
+
const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
|
|
140
|
+
await ctx.permission.assert([{ target, boundary: target.full }]);
|
|
141
|
+
const stats = await ctx.sandbox.lstat(target.full, requested);
|
|
142
|
+
entries.push(await entryFor(target.full, path.relative(base, target.full), stats));
|
|
143
|
+
if (stats.isDirectory()) {
|
|
144
|
+
for (const child of await walkAll(target.full, {
|
|
145
|
+
recursive: true,
|
|
146
|
+
includeHidden: true,
|
|
147
|
+
concurrency: ctx.concurrency,
|
|
148
|
+
signal: ctx.signal,
|
|
149
|
+
})) {
|
|
150
|
+
entries.push(await entryFor(child.path, path.relative(base, child.path), child.stats));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return entries;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function entryFor(
|
|
158
|
+
full: string,
|
|
159
|
+
name: string,
|
|
160
|
+
stats: Awaited<ReturnType<typeof fs.lstat>>,
|
|
161
|
+
): Promise<Entry> {
|
|
162
|
+
const data = stats.isSymbolicLink()
|
|
163
|
+
? Buffer.from(await fs.readlink(full), "utf8")
|
|
164
|
+
: stats.isFile()
|
|
165
|
+
? await fs.readFile(full)
|
|
166
|
+
: Buffer.alloc(0);
|
|
167
|
+
return {
|
|
168
|
+
name: name.split(path.sep).join("/"),
|
|
169
|
+
mode: Number(stats.mode),
|
|
170
|
+
uid: Number(stats.uid),
|
|
171
|
+
gid: Number(stats.gid),
|
|
172
|
+
mtime: Math.floor(num(stats.mtimeMs) / 1000),
|
|
173
|
+
data,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function encode(entries: readonly Entry[]): Buffer {
|
|
178
|
+
const chunks: Buffer[] = [];
|
|
179
|
+
let inode = 1;
|
|
180
|
+
for (const entry of entries) {
|
|
181
|
+
const name = Buffer.from(`${entry.name}\0`, "utf8");
|
|
182
|
+
const header = [
|
|
183
|
+
"070701",
|
|
184
|
+
octal(inode++),
|
|
185
|
+
octal(entry.mode),
|
|
186
|
+
octal(entry.uid),
|
|
187
|
+
octal(entry.gid),
|
|
188
|
+
octal(1),
|
|
189
|
+
octal(entry.mtime),
|
|
190
|
+
octal(entry.data.length),
|
|
191
|
+
octal(0),
|
|
192
|
+
octal(0),
|
|
193
|
+
octal(0),
|
|
194
|
+
octal(0),
|
|
195
|
+
octal(name.length),
|
|
196
|
+
octal(0),
|
|
197
|
+
].join("");
|
|
198
|
+
chunks.push(Buffer.from(header, "ascii"), name, pad4(name.length), entry.data, pad4(entry.data.length));
|
|
199
|
+
}
|
|
200
|
+
const trailer = Buffer.from("TRAILER!!!\0", "utf8");
|
|
201
|
+
chunks.push(
|
|
202
|
+
Buffer.from(
|
|
203
|
+
["070701", octal(0), octal(0), octal(0), octal(0), octal(1), octal(now()), octal(0), octal(0), octal(0), octal(0), octal(0), octal(trailer.length), octal(0)].join(""),
|
|
204
|
+
"ascii",
|
|
205
|
+
),
|
|
206
|
+
trailer,
|
|
207
|
+
pad4(trailer.length),
|
|
208
|
+
);
|
|
209
|
+
return Buffer.concat(chunks);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function decode(data: Buffer): Entry[] {
|
|
213
|
+
const entries: Entry[] = [];
|
|
214
|
+
let offset = 0;
|
|
215
|
+
for (;;) {
|
|
216
|
+
if (offset + 110 > data.length) throw new FsError("Truncated cpio header.", "archive");
|
|
217
|
+
if (data.subarray(offset, offset + 6).toString("ascii") !== "070701") {
|
|
218
|
+
throw new FsError("Unsupported cpio format.", "archive");
|
|
219
|
+
}
|
|
220
|
+
const field = (index: number): number => Number.parseInt(data.subarray(offset + 6 + index * 8, offset + 14 + index * 8).toString("ascii"), 8);
|
|
221
|
+
const mode = field(1);
|
|
222
|
+
const uid = field(2);
|
|
223
|
+
const gid = field(3);
|
|
224
|
+
const mtime = field(5);
|
|
225
|
+
const size = field(6);
|
|
226
|
+
const nameSize = field(11);
|
|
227
|
+
const nameStart = offset + 110;
|
|
228
|
+
const name = data.subarray(nameStart, nameStart + nameSize - 1).toString("utf8");
|
|
229
|
+
const dataStart = nameStart + nameSize + align4(nameSize);
|
|
230
|
+
if (name === "TRAILER!!!") return entries;
|
|
231
|
+
entries.push({ name, mode, uid, gid, mtime, data: data.subarray(dataStart, dataStart + size) });
|
|
232
|
+
offset = dataStart + size + align4(size);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function safeName(name: string): string {
|
|
237
|
+
const normalized = name.replaceAll("\\", "/").replace(/^\/+/, "");
|
|
238
|
+
const parts = normalized.split("/").filter((part) => part !== "" && part !== ".");
|
|
239
|
+
if (parts.length === 0 || parts.includes("..")) {
|
|
240
|
+
throw new FsError(`Unsafe archive member: "${name}".`, "archive");
|
|
241
|
+
}
|
|
242
|
+
return parts.join("/");
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function octal(value: number): string {
|
|
246
|
+
return value.toString(8).padStart(8, "0").slice(-8);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function align4(value: number): number {
|
|
250
|
+
return (4 - (value % 4)) % 4;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function pad4(value: number): Buffer {
|
|
254
|
+
return Buffer.alloc(align4(value), 0);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function now(): number {
|
|
258
|
+
return Math.floor(Date.now() / 1000);
|
|
259
|
+
}
|