opencode-fs-plugin 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/INSTALL.md +186 -0
  2. package/LICENSE +225 -0
  3. package/README.md +265 -2
  4. package/SPEC.md +45 -0
  5. package/package.json +63 -4
  6. package/skills/filesystem/SKILL.md +153 -0
  7. package/src/core/errors.ts +81 -0
  8. package/src/core/format.ts +100 -0
  9. package/src/core/fsutil.ts +228 -0
  10. package/src/core/mode.ts +107 -0
  11. package/src/core/parallel.ts +76 -0
  12. package/src/core/permissions.ts +134 -0
  13. package/src/core/sandbox.ts +270 -0
  14. package/src/core/schema.ts +16 -0
  15. package/src/core/stream.ts +84 -0
  16. package/src/core/types.ts +51 -0
  17. package/src/index.ts +172 -0
  18. package/src/tools/cat.ts +90 -0
  19. package/src/tools/chmod.ts +93 -0
  20. package/src/tools/cp.ts +136 -0
  21. package/src/tools/cut.ts +93 -0
  22. package/src/tools/df.ts +78 -0
  23. package/src/tools/diff.ts +136 -0
  24. package/src/tools/du.ts +102 -0
  25. package/src/tools/find.ts +181 -0
  26. package/src/tools/grep.ts +205 -0
  27. package/src/tools/gzip.ts +164 -0
  28. package/src/tools/hash.ts +84 -0
  29. package/src/tools/head.ts +78 -0
  30. package/src/tools/ln.ts +98 -0
  31. package/src/tools/ls.ts +178 -0
  32. package/src/tools/mkdir.ts +70 -0
  33. package/src/tools/mktemp.ts +83 -0
  34. package/src/tools/mv.ts +135 -0
  35. package/src/tools/pipe.ts +107 -0
  36. package/src/tools/readlink.ts +90 -0
  37. package/src/tools/rm.ts +91 -0
  38. package/src/tools/rmdir.ts +117 -0
  39. package/src/tools/sed.ts +151 -0
  40. package/src/tools/sort.ts +73 -0
  41. package/src/tools/stat.ts +157 -0
  42. package/src/tools/tail.ts +74 -0
  43. package/src/tools/tar.ts +195 -0
  44. package/src/tools/tee.ts +51 -0
  45. package/src/tools/touch.ts +130 -0
  46. package/src/tools/tr.ts +123 -0
  47. package/src/tools/trash.ts +86 -0
  48. package/src/tools/truncate.ts +96 -0
  49. package/src/tools/uniq.ts +76 -0
  50. package/src/tools/wc.ts +97 -0
  51. package/src/tools/zip.ts +231 -0
package/SPEC.md ADDED
@@ -0,0 +1,45 @@
1
+ # Compatibility specification
2
+
3
+ This fork targets Linux and Node 22+. Tool names follow native commands; option
4
+ fields follow the native long options. The model-facing tools are grouped under
5
+ the `fs` namespace (`tools.fs.cp`, direct `fs_cp`).
6
+
7
+ ## Principles
8
+
9
+ - Every tool is async and uses `fs/promises`.
10
+ - Every mutating tool asserts `fs_<tool>` permission before touching the disk.
11
+ - External targets require `external_directory` first.
12
+ - Output is native-style text plus structured metadata; errors are `ERROR:` or
13
+ `BLOCKED:` with a stable code.
14
+ - Unsupported options fail with `unsupported` rather than being ignored.
15
+ - No tool invokes a shell or `child_process`.
16
+
17
+ ## Deliberate gaps
18
+
19
+ These are not implemented:
20
+
21
+ - `xz`, `zstd`, `7z`, `rar`
22
+ - `awk`, full `sed` command language, `find -exec`, `tail -f`
23
+ - `chown`, `chgrp`, `chattr`, `dd`, `rsync`
24
+ - ACL and xattr preservation in `cp -a`
25
+ - full GNU edge-flag parity for `ls`, `stat`, `sort`, `find`
26
+ - symlink-race-proof sandboxing
27
+ - `tar`/`zip` creation from arbitrary streams; archives are file-backed
28
+ - cross-filesystem `trash`; use `rm` or a mount-trash helper
29
+
30
+ ## Format details
31
+
32
+ - `stat` supports `%n %N %s %F %a %A %u %U %g %G %d %i %h %b %B %o %x %X %y
33
+ %Y %z %Z %t %T %L`, plus `\n`, `\t`, `\\` and `%%`.
34
+ - `chmod` supports octal modes and symbolic `[ugoa]*[-+=][rwxXst]*` clauses.
35
+ - `find -size` uses binary suffixes (`K`, `M`, `G`, ...); `-mtime`/`-mmin`
36
+ accept `+N` (older), `-N` (newer), and exact `N`.
37
+ - `tar`/`zip` extraction rejects path traversal and escaping links.
38
+ - `pipe` passes raw bytes and only accepts registered pipeable stages.
39
+
40
+ ## Coverage policy
41
+
42
+ `npm run coverage` enforces 100% on `src/**`. `/* v8 ignore next */` is used only
43
+ for OS-error branches that cannot be produced deterministically in the test
44
+ environment; those paths remain in the source and are still exercised by the
45
+ type checker and integration tests where possible.
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "opencode-fs-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "type": "module",
5
+ "description": "OpenCode 2 plugin: Linux-style filesystem and text tools under the fs namespace.",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/masterjg/opencode-fs-plugin.git"
9
+ },
10
+ "homepage": "https://github.com/masterjg/opencode-fs-plugin#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/masterjg/opencode-fs-plugin/issues"
13
+ },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "exports": {
18
+ ".": "./src/index.ts"
19
+ },
20
+ "files": [
21
+ "src",
22
+ "skills",
23
+ "SPEC.md",
24
+ "INSTALL.md"
25
+ ],
26
+ "scripts": {
27
+ "typecheck": "tsc --noEmit",
28
+ "test": "vitest run",
29
+ "test:watch": "vitest",
30
+ "coverage": "vitest run --coverage"
31
+ },
32
+ "dependencies": {
33
+ "@sinclair/typebox": "^0.34.52",
34
+ "diff": "^9.0.0",
35
+ "picomatch": "^4.0.7",
36
+ "tar-stream": "^3.2.2",
37
+ "yauzl": "^3.4.0",
38
+ "yazl": "^3.3.1"
39
+ },
40
+ "peerDependencies": {
41
+ "@opencode/plugin": "^2.2.7"
42
+ },
43
+ "peerDependenciesMeta": {
44
+ "@opencode/plugin": {
45
+ "optional": true
46
+ }
47
+ },
48
+ "devDependencies": {
49
+ "@opencode/plugin": "^2.2.7",
50
+ "@types/node": "^24.0.0",
51
+ "@types/picomatch": "^4.0.2",
52
+ "@types/yauzl": "^2.10.3",
53
+ "@types/yazl": "^3.3.0",
54
+ "@vitest/coverage-v8": "^5.1.0",
55
+ "typescript": "^5.9.0",
56
+ "vitest": "^5.1.0"
57
+ },
58
+ "license": "EPL-2.0",
59
+ "license-wizard": {
60
+ "licenseId": "EPL-2.0",
61
+ "headers": {
62
+ "style": "short"
63
+ }
64
+ }
65
+ }
@@ -0,0 +1,153 @@
1
+ ---
2
+ name: Filesystem
3
+ description: Use when a task needs Linux-style filesystem or text operations beyond OpenCode's built-ins - copy, move, metadata, touch, truncate, symlinks, chmod, hashes, disk usage, find, archives, diff, trash, or composing filters through a pipe. Covers the fs namespace, argument shapes, native options, permissions, limits, and verification.
4
+ ---
5
+
6
+ # Filesystem
7
+
8
+ The `opencode-fs-plugin` exposes a Linux-style toolkit under the `fs` namespace.
9
+ With `execute` allowed, call it as `tools.fs.<command>`; agents without
10
+ `execute` get direct `fs_<command>` tools.
11
+
12
+ ## Choose the right tool
13
+
14
+ | Task | Use |
15
+ |---|---|
16
+ | Read file text or directory names | built-in `read` |
17
+ | Create or overwrite text | built-in `write` |
18
+ | Exact text replacement | built-in `edit` |
19
+ | Find paths by name | built-in `glob` |
20
+ | Ordinary content search | built-in `grep` |
21
+ | Copy, move, remove, metadata, links, archives | `fs.*` |
22
+ | Byte-exact concatenation or pipe input | `fs.cat` |
23
+ | Search inside a pipe or with extra flags | `fs.grep` |
24
+ | Metadata/predicate search | `fs.find` |
25
+ | Regex substitution or in-place edit | `fs.sed` |
26
+ | Recoverable deletion | `fs.trash` |
27
+
28
+ Do not duplicate a built-in when it already covers the job. `fs` exists for the
29
+ operations the built-ins do not cover, and for composable text/archive work.
30
+
31
+ ## Command map
32
+
33
+ | Need | Command |
34
+ |---|---|
35
+ | Copy files/directories | `fs.cp` (`recursive`, `archive`, `noClobber`, `preserve`) |
36
+ | Move or rename | `fs.mv` (`noClobber`, `update`) |
37
+ | List, metadata | `fs.ls`, `fs.stat` (`long`, `human`, `format`) |
38
+ | Create, remove | `fs.mkdir`, `fs.rmdir`, `fs.rm` |
39
+ | Times and sizes | `fs.touch`, `fs.truncate` |
40
+ | Links and modes | `fs.ln`, `fs.readlink`, `fs.chmod` |
41
+ | Hash, usage | `fs.hash`, `fs.du`, `fs.df` |
42
+ | Predicate search | `fs.find` (`name`, `type`, `size`, `mtime`, `maxDepth`) |
43
+ | Archives | `fs.tar`, `fs.zip`, `fs.unzip`, `fs.gzip`, `fs.gunzip` |
44
+ | Compare | `fs.diff` |
45
+ | Temp and trash | `fs.mktemp`, `fs.trash` |
46
+ | Text filters | `fs.cat`, `fs.head`, `fs.tail`, `fs.grep`, `fs.sed`, `fs.sort`, `fs.uniq`, `fs.cut`, `fs.tr`, `fs.wc`, `fs.tee` |
47
+ | Compose filters | `fs.pipe` |
48
+
49
+ ## Argument shapes
50
+
51
+ Use the exact field names; scalar `path` is only valid for `fs.mkdir`.
52
+
53
+ | Field | Commands |
54
+ |---|---|
55
+ | `path` | `fs.mkdir` |
56
+ | `sources` + `destination` | `fs.cp`, `fs.mv`, `fs.ln` |
57
+ | `paths` | `fs.stat`, `fs.ls`, `fs.find`, `fs.rm`, `fs.rmdir`, `fs.touch`, `fs.truncate`, `fs.chmod`, `fs.readlink`, `fs.du`, `fs.df`, `fs.cat`, `fs.head`, `fs.tail`, `fs.tee`, `fs.wc`, `fs.sort`, `fs.uniq`, `fs.cut`, `fs.tr`, `fs.grep`, `fs.sed`, `fs.gzip`, `fs.gunzip`, `fs.trash` |
58
+ | `files` | `fs.hash` |
59
+ | `left` + `right` | `fs.diff` |
60
+ | `archive` + `paths` | `fs.tar` create, `fs.zip` create |
61
+ | `archive` + `mode` | `fs.tar`, `fs.unzip` |
62
+ | `stages` + optional `input`/`output` | `fs.pipe` |
63
+
64
+ ## Pipe
65
+
66
+ Stages run sequentially and pass bytes. Only pipeable tools are allowed. The
67
+ first stage may be a source or a filter; later stages consume stdin.
68
+
69
+ ```js
70
+ await tools.fs.pipe({
71
+ stages: [
72
+ { tool: "cat", args: { paths: ["app.log"] } },
73
+ { tool: "grep", args: { pattern: "ERROR", lineNumbers: true } },
74
+ { tool: "sort", args: { unique: true } },
75
+ ],
76
+ output: "errors.txt",
77
+ })
78
+ ```
79
+
80
+ `output` writes the final stream and `append` appends. Stage names are the short
81
+ native names (`cat`, `grep`, `sort`), not `fs.cat`. There is no shell,
82
+ redirection operator, nested pipe, or `find -exec`. A filter stage needs
83
+ `input` or a preceding source stage.
84
+
85
+ ## Recipes
86
+
87
+ ```js
88
+ // copy a tree and keep modes/timestamps
89
+ await tools.fs.cp({ sources: ["src"], destination: "backup", recursive: true, preserve: true })
90
+
91
+ // metadata and a human-readable listing
92
+ await tools.fs.stat({ paths: ["package.json"], format: "%n %s %a %y" })
93
+ await tools.fs.ls({ paths: ["dist"], long: true, human: true })
94
+
95
+ // find by name and size, then remove or trash deliberately
96
+ await tools.fs.find({ paths: ["."], name: "*.log", size: "+10M" })
97
+ await tools.fs.trash({ paths: ["old.log"] })
98
+
99
+ // create and extract an archive
100
+ await tools.fs.tar({ mode: "create", archive: "dist.tgz", paths: ["dist"], gzip: true })
101
+ await tools.fs.tar({ mode: "extract", archive: "dist.tgz", directory: "out" })
102
+
103
+ // compare two files
104
+ await tools.fs.diff({ left: "old.txt", right: "new.txt", unified: 3 })
105
+ ```
106
+
107
+ ## Limits
108
+
109
+ - Linux only; there is no Windows branch.
110
+ - `fs.sed` supports `s<delim>pattern<delim>replacement<delim>flags` with `g`,
111
+ `i` and `p`. It is not a full sed interpreter.
112
+ - `fs.find` has no `-exec`; use `fs.rm`/`fs.trash` separately.
113
+ - No `xz`, `zstd`, `7z`, `chown`, `chattr`, `dd`, or `rsync`.
114
+ - `fs.tail` has no follow mode; `fs.diff` compares files/directories only.
115
+ - `cp -a` preserves mode and timestamps but not ACLs or xattrs.
116
+ - `fs.tar`/`fs.zip` are file-backed; they are not pipe stages.
117
+ - `fs.trash` uses the XDG home trash only and refuses cross-device moves.
118
+ - `fs.mktemp` uses the OS temp directory unless `tmpdir` is supplied.
119
+
120
+ ## Paths and safety
121
+
122
+ - Paths resolve against the project directory. Paths outside it require
123
+ `external_directory` approval, except tool-owned temp/trash paths.
124
+ - Symlinks are handled per command: `rm`/`mv` never follow the final link, `cp`
125
+ follows unless `archive`/`dereference: false`, and `stat`/`ls` use lstat
126
+ unless asked to follow.
127
+ - The project root, its ancestors, `/`, `$HOME`, and core system directories are
128
+ hard stops for destructive operations.
129
+ - Archive extraction rejects absolute paths, `..`, and escaping links.
130
+ - `rm` is permanent; prefer `trash` for recoverable deletes.
131
+ - Pass `recursive: true` only when you intend to remove a whole tree.
132
+
133
+ ## Permissions
134
+
135
+ Command actions are `fs_<command>` (for example `fs_cp`). `fs_*` wildcards work
136
+ in agent rules. `fs.pipe` asserts each stage's action; a denied stage cannot be
137
+ hidden inside a pipeline. Do not work around a denied tool with shell.
138
+
139
+ ## Errors and output
140
+
141
+ - `ERROR: ...` is a recoverable tool failure; `BLOCKED: ...` is a sandbox hard
142
+ stop. Both carry a stable `code` in metadata.
143
+ - `fs.grep` with no matches and `fs.diff` with differences return exit code 1;
144
+ that is a result, not a tool failure.
145
+ - Binary output is returned as base64 when no `output` file is supplied.
146
+ - Invalid arguments return `ERROR: Invalid ...`; fix the field names or option
147
+ values rather than retrying the same call.
148
+
149
+ ## Verification
150
+
151
+ Use `fs.stat`, `fs.ls`, `fs.hash`, `fs.cat`, or `fs.diff` to confirm the result.
152
+ Report the tool result, such as `copied: 1`, `found: 2`, or
153
+ `differences: true`.
@@ -0,0 +1,81 @@
1
+ /*
2
+ * SPDX-License-Identifier: EPL-2.0
3
+ * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
+ */
5
+
6
+ export type FsErrorCode =
7
+ | "empty"
8
+ | "invalid"
9
+ | "unsupported"
10
+ | "not-found"
11
+ | "not-directory"
12
+ | "not-file"
13
+ | "not-empty"
14
+ | "outside"
15
+ | "access"
16
+ | "exists"
17
+ | "cross-device"
18
+ | "archive"
19
+ | "checksum"
20
+ | "interrupted"
21
+ | "io";
22
+
23
+ /**
24
+ * A domain failure that the model should see and can recover from. Permission
25
+ * denials and unexpected programming errors are deliberately not converted to
26
+ * this type; they must propagate as tool errors.
27
+ */
28
+ export class FsError extends Error {
29
+ readonly code: FsErrorCode;
30
+
31
+ constructor(message: string, code: FsErrorCode) {
32
+ super(message);
33
+ this.name = "FsError";
34
+ this.code = code;
35
+ }
36
+ }
37
+
38
+ export function errnoCode(error: unknown): string | undefined {
39
+ if (typeof error !== "object" || error === null) return undefined;
40
+ const code = (error as NodeJS.ErrnoException).code;
41
+ return typeof code === "string" ? code : undefined;
42
+ }
43
+
44
+ export function errorMessage(error: unknown): string {
45
+ if (error instanceof Error && error.message) return error.message;
46
+ return String(error);
47
+ }
48
+
49
+ export function isMissing(error: unknown): boolean {
50
+ const code = errnoCode(error);
51
+ return code === "ENOENT" || code === "ENOTDIR";
52
+ }
53
+
54
+ export function isPermission(error: unknown): boolean {
55
+ const code = errnoCode(error);
56
+ return code === "EACCES" || code === "EPERM";
57
+ }
58
+
59
+ export function fromErrno(error: unknown, fallback: FsErrorCode = "io"): FsError {
60
+ const code = errnoCode(error);
61
+ const message = errorMessage(error);
62
+ if (code === "ENOENT" || code === "ENOTDIR") {
63
+ return new FsError(message, "not-found");
64
+ }
65
+ if (code === "EACCES" || code === "EPERM") {
66
+ return new FsError(message, "access");
67
+ }
68
+ if (code === "EEXIST") {
69
+ return new FsError(message, "exists");
70
+ }
71
+ if (code === "ENOTEMPTY") {
72
+ return new FsError(message, "not-empty");
73
+ }
74
+ if (code === "EXDEV") {
75
+ return new FsError(message, "cross-device");
76
+ }
77
+ if (code === "EISDIR") {
78
+ return new FsError(message, "not-file");
79
+ }
80
+ return new FsError(message, fallback);
81
+ }
@@ -0,0 +1,100 @@
1
+ /*
2
+ * SPDX-License-Identifier: EPL-2.0
3
+ * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
+ */
5
+
6
+ import type { ToolResult } from "./types.js";
7
+ import { FsError } from "./errors.js";
8
+
9
+ export interface RenderedResult {
10
+ content: string;
11
+ metadata: Record<string, unknown>;
12
+ }
13
+
14
+ const BINARY_PROBE = 8192;
15
+
16
+ export function isBinary(buffer: Buffer): boolean {
17
+ const length = Math.min(buffer.length, BINARY_PROBE);
18
+ for (let index = 0; index < length; index++) {
19
+ if (buffer[index] === 0) return true;
20
+ }
21
+ return false;
22
+ }
23
+
24
+ export function renderResult(result: ToolResult, maxOutputBytes: number): RenderedResult {
25
+ const exitCode = result.exitCode ?? 0;
26
+ const metadata: Record<string, unknown> = {
27
+ ...result.metadata,
28
+ ok: exitCode === 0,
29
+ exitCode,
30
+ };
31
+ if (result.stderr) metadata.stderr = result.stderr;
32
+
33
+ if (result.stdout.length === 0) {
34
+ return { content: "", metadata };
35
+ }
36
+
37
+ const slice = result.stdout.subarray(0, maxOutputBytes);
38
+ const truncated = result.stdout.length > maxOutputBytes;
39
+ if (truncated) metadata.truncated = true;
40
+ metadata.bytes = result.stdout.length;
41
+
42
+ if (isBinary(slice)) {
43
+ metadata.encoding = "base64";
44
+ return { content: slice.toString("base64"), metadata };
45
+ }
46
+
47
+ let content = slice.toString("utf8");
48
+ if (result.stderr) content += `${content.endsWith("\n") ? "" : "\n"}[stderr]\n${result.stderr}`;
49
+ return { content, metadata };
50
+ }
51
+
52
+ export function renderError(error: FsError, blocked: boolean): RenderedResult {
53
+ return {
54
+ content: `${blocked ? "BLOCKED" : "ERROR"}: ${error.message}`,
55
+ metadata: {
56
+ ok: false,
57
+ blocked,
58
+ code: error.code,
59
+ exitCode: 1,
60
+ },
61
+ };
62
+ }
63
+
64
+ export function humanSize(bytes: number): string {
65
+ const units = ["B", "K", "M", "G", "T", "P", "E"];
66
+ let value = Math.abs(bytes);
67
+ let unit = 0;
68
+ while (value >= 1024 && unit < units.length - 1) {
69
+ value /= 1024;
70
+ unit++;
71
+ }
72
+ const sign = bytes < 0 ? "-" : "";
73
+ if (unit === 0) return `${sign}${Math.trunc(value)}`;
74
+ return `${sign}${value < 10 ? value.toFixed(1) : Math.trunc(value)}${units[unit]}`;
75
+ }
76
+
77
+ export function parseSize(value: string): number {
78
+ if (typeof value !== "string" || value.length === 0) {
79
+ throw new FsError("size is empty.", "invalid");
80
+ }
81
+ const match = /^([+-]?)(\d+(?:\.\d+)?)([KMGTPE]?)(?:i?B)?$/i.exec(value.trim());
82
+ if (!match) throw new FsError(`Invalid size: ${value}`, "invalid");
83
+ const sign = match[1] === "-" ? -1 : 1;
84
+ const number = Number(match[2]);
85
+ const suffix = (match[3] as string).toUpperCase();
86
+ const exponent = suffix === "" ? 0 : "KMGTPE".indexOf(suffix) + 1;
87
+ const multiplier = exponent === 0 ? 1 : 1024 ** exponent;
88
+ return sign * Math.round(number * multiplier);
89
+ }
90
+
91
+ export function splitLines(input: string): string[] {
92
+ if (input.length === 0) return [];
93
+ const lines = input.split("\n");
94
+ if (lines[lines.length - 1] === "") lines.pop();
95
+ return lines;
96
+ }
97
+
98
+ export function withTrailingNewline(text: string): string {
99
+ return text.endsWith("\n") ? text : `${text}\n`;
100
+ }
@@ -0,0 +1,228 @@
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 { constants } from "node:fs";
9
+ import { FsError, fromErrno, isMissing } from "./errors.js";
10
+ import { formatMode } from "./mode.js";
11
+
12
+ export interface WalkEntry {
13
+ readonly path: string;
14
+ readonly name: string;
15
+ readonly stats: Awaited<ReturnType<typeof fs.lstat>>;
16
+ }
17
+
18
+ export interface WalkOptions {
19
+ readonly recursive?: boolean;
20
+ readonly followSymlinks?: boolean;
21
+ readonly maxDepth?: number;
22
+ readonly includeHidden?: boolean;
23
+ readonly signal?: AbortSignal;
24
+ }
25
+
26
+ export async function* walk(root: string, options: WalkOptions = {}): AsyncGenerator<WalkEntry> {
27
+ const maxDepth = options.maxDepth ?? (options.recursive === false ? 0 : Infinity);
28
+ yield* walkAt(root, 0, maxDepth, options);
29
+ }
30
+
31
+ async function* walkAt(
32
+ current: string,
33
+ depth: number,
34
+ maxDepth: number,
35
+ options: WalkOptions,
36
+ ): AsyncGenerator<WalkEntry> {
37
+ if (options.signal?.aborted) throw new FsError("Operation interrupted.", "interrupted");
38
+ let entries;
39
+ try {
40
+ entries = await fs.readdir(current, { withFileTypes: true });
41
+ } catch (error) {
42
+ throw fromErrno(error, "access");
43
+ }
44
+ for (const dirent of entries) {
45
+ if (!options.includeHidden && dirent.name.startsWith(".")) continue;
46
+ const full = path.join(current, dirent.name);
47
+ let stats;
48
+ try {
49
+ stats = options.followSymlinks ? await fs.stat(full) : await fs.lstat(full);
50
+ } catch (error) {
51
+ /* v8 ignore next 3 */
52
+ if (isMissing(error)) continue;
53
+ /* v8 ignore next */
54
+ throw fromErrno(error, "access");
55
+ }
56
+ yield { path: full, name: dirent.name, stats };
57
+ if (depth + 1 < maxDepth && stats.isDirectory()) {
58
+ yield* walkAt(full, depth + 1, maxDepth, options);
59
+ }
60
+ }
61
+ }
62
+
63
+ export interface CopyOptions {
64
+ readonly recursive?: boolean;
65
+ readonly dereference?: boolean;
66
+ readonly preserve?: boolean;
67
+ readonly noClobber?: boolean;
68
+ readonly update?: boolean;
69
+ readonly signal?: AbortSignal;
70
+ readonly concurrency: number;
71
+ }
72
+
73
+ export async function copyTree(src: string, dest: string, options: CopyOptions): Promise<number> {
74
+ if (options.signal?.aborted) throw new FsError("Operation interrupted.", "interrupted");
75
+ const stats = options.dereference === false ? await fs.lstat(src) : await fs.stat(src);
76
+ if (options.update === true) {
77
+ try {
78
+ const destStats = await fs.lstat(dest);
79
+ /* v8 ignore next */
80
+ if (destStats.mtimeMs >= stats.mtimeMs) return 0;
81
+ } catch (error) {
82
+ /* v8 ignore next 2 */
83
+ if (!isMissing(error)) throw fromErrno(error, "access");
84
+ }
85
+ }
86
+
87
+ if (stats.isSymbolicLink() && options.dereference === false) {
88
+ const target = await fs.readlink(src);
89
+ await ensureParent(dest);
90
+ try {
91
+ await fs.symlink(target, dest);
92
+ } catch (error) {
93
+ /* v8 ignore next */
94
+ if (isExists(error) && options.noClobber !== true) {
95
+ await fs.unlink(dest);
96
+ await fs.symlink(target, dest);
97
+ } else {
98
+ throw fromErrno(error);
99
+ }
100
+ }
101
+ return 1;
102
+ }
103
+
104
+ if (stats.isDirectory()) {
105
+ if (options.recursive !== true) {
106
+ throw new FsError(`"${src}" is a directory; recursive is required.`, "not-file");
107
+ }
108
+ try {
109
+ await fs.mkdir(dest, { recursive: true });
110
+ } catch (error) {
111
+ /* v8 ignore next */
112
+ throw fromErrno(error);
113
+ }
114
+ const entries = await fs.readdir(src);
115
+ let copied = 1;
116
+ const limit = Math.max(1, options.concurrency);
117
+ let index = 0;
118
+ const workers = Array.from({ length: Math.min(limit, entries.length) }, async () => {
119
+ for (;;) {
120
+ const current = index++;
121
+ if (current >= entries.length) return;
122
+ const name = entries[current] as string;
123
+ copied += await copyTree(path.join(src, name), path.join(dest, name), options);
124
+ }
125
+ });
126
+ await Promise.all(workers);
127
+ if (options.preserve === true) await preserve(dest, stats);
128
+ return copied;
129
+ }
130
+
131
+ if (!stats.isFile()) {
132
+ throw new FsError(`"${src}" is not a regular file or directory.`, "unsupported");
133
+ }
134
+ await ensureParent(dest);
135
+ try {
136
+ await fs.copyFile(src, dest, options.noClobber === true ? constants.COPYFILE_EXCL : 0);
137
+ } catch (error) {
138
+ /* v8 ignore next */
139
+ if (options.noClobber === true && isExists(error)) return 0;
140
+ /* v8 ignore next */
141
+ throw fromErrno(error);
142
+ }
143
+ if (options.preserve === true) await preserve(dest, stats);
144
+ return 1;
145
+ }
146
+
147
+ export async function ensureParent(dest: string): Promise<void> {
148
+ try {
149
+ await fs.mkdir(path.dirname(dest), { recursive: true });
150
+ } catch (error) {
151
+ throw fromErrno(error);
152
+ }
153
+ }
154
+
155
+ export function num(value: number | bigint): number {
156
+ return typeof value === "bigint" ? Number(value) : value;
157
+ }
158
+
159
+ export async function preserve(dest: string, stats: Awaited<ReturnType<typeof fs.stat>>): Promise<void> {
160
+ try {
161
+ await fs.chmod(dest, num(stats.mode) & 0o7777);
162
+ await fs.utimes(dest, stats.atime, stats.mtime);
163
+ } catch (error) {
164
+ throw fromErrno(error, "io");
165
+ }
166
+ }
167
+
168
+ export async function lookupUser(uid: number): Promise<string> {
169
+ return (await lookupId("/etc/passwd", uid)) ?? String(uid);
170
+ }
171
+
172
+ export async function lookupGroup(gid: number): Promise<string> {
173
+ return (await lookupId("/etc/group", gid)) ?? String(gid);
174
+ }
175
+
176
+ async function lookupId(file: string, id: number): Promise<string | undefined> {
177
+ let text: string;
178
+ try {
179
+ text = await fs.readFile(file, "utf8");
180
+ } catch {
181
+ /* v8 ignore next */
182
+ return undefined;
183
+ }
184
+ for (const line of text.split("\n")) {
185
+ const fields = line.split(":");
186
+ if (fields.length >= 3 && Number(fields[2]) === id) return fields[0] as string;
187
+ }
188
+ return undefined;
189
+ }
190
+
191
+ export function formatDate(date: Date, now = new Date()): string {
192
+ const month = date.toLocaleString("en-US", { month: "short" });
193
+ const day = String(date.getDate()).padStart(2, " ");
194
+ const sixMonths = 183 * 24 * 60 * 60 * 1000;
195
+ const recent = Math.abs(now.getTime() - date.getTime()) < sixMonths;
196
+ const time = recent
197
+ ? `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`
198
+ : String(date.getFullYear());
199
+ return `${month} ${day} ${recent ? time : ` ${time}`}`;
200
+ }
201
+
202
+ export function typeName(stats: Awaited<ReturnType<typeof fs.lstat>>): string {
203
+ if (stats.isDirectory()) return "directory";
204
+ if (stats.isSymbolicLink()) return "symbolic link";
205
+ if (stats.isFile()) return "regular file";
206
+ if (stats.isFIFO()) return "fifo";
207
+ /* v8 ignore next */
208
+ if (stats.isSocket()) return "socket";
209
+ /* v8 ignore next */
210
+ if (stats.isCharacterDevice()) return "character special file";
211
+ /* v8 ignore next */
212
+ if (stats.isBlockDevice()) return "block special file";
213
+ /* v8 ignore next */
214
+ return "unknown";
215
+ }
216
+
217
+ export function modeString(stats: Awaited<ReturnType<typeof fs.lstat>>): string {
218
+ return formatMode(num(stats.mode));
219
+ }
220
+
221
+ export function isSubpath(parent: string, child: string): boolean {
222
+ const rel = path.relative(parent, child);
223
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
224
+ }
225
+
226
+ export function isExists(error: unknown): boolean {
227
+ return (error as NodeJS.ErrnoException | undefined)?.code === "EEXIST";
228
+ }