@koneeric/onetool 0.0.0-stage → 0.1.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.
@@ -0,0 +1,270 @@
1
+ import { spawn } from "node:child_process";
2
+ import { constants } from "node:os";
3
+ import { lstat, stat, realpath, readFile as readBytes, writeFile as writeBytes } from "node:fs/promises";
4
+ import { resolve, join, dirname, basename, sep } from "node:path";
5
+
6
+ export class ShellError extends Error {
7
+ constructor(message, outside = false) {
8
+ super(message);
9
+ this.name = "ShellError";
10
+ this.outside = outside;
11
+ }
12
+ }
13
+
14
+ const DEFAULT_LIMIT = 10000000;
15
+
16
+ // ---- folders and the real place of a path
17
+
18
+ export async function realPlace(path, folders) {
19
+ if (typeof path !== "string" || path === "") throw new ShellError("the path must be a text that is not empty");
20
+ const full = resolve(folders[0], path);
21
+ const outside = () => new ShellError(`${path} is outside the listed folders`, true);
22
+
23
+ let found = full;
24
+ const names = [];
25
+ for (;;) {
26
+ try {
27
+ await lstat(found);
28
+ break;
29
+ } catch {
30
+ const parent = dirname(found);
31
+ if (parent === found) throw outside();
32
+ names.unshift(basename(found));
33
+ found = parent;
34
+ }
35
+ }
36
+
37
+ let real;
38
+ try {
39
+ real = join(await realpath(found), ...names);
40
+ } catch {
41
+ throw outside();
42
+ }
43
+
44
+ for (const folder of folders) {
45
+ let realFolder;
46
+ try {
47
+ realFolder = await realpath(folder);
48
+ } catch {
49
+ continue;
50
+ }
51
+ if (real === realFolder || real.startsWith(realFolder.endsWith(sep) ? realFolder : realFolder + sep)) return real;
52
+ }
53
+ throw outside();
54
+ }
55
+
56
+ export async function missingFolders(folders) {
57
+ const missing = [];
58
+ try {
59
+ for (let i = 0; i < folders.length; i++) {
60
+ try {
61
+ if (!(await stat(folders[i])).isDirectory()) missing.push(i);
62
+ } catch {
63
+ missing.push(i);
64
+ }
65
+ }
66
+ } catch {
67
+ // not a list: undefined by the meeting point
68
+ }
69
+ return missing;
70
+ }
71
+
72
+ // ---- the three file functions
73
+
74
+ const isGone = (err) => err && (err.code === "ENOENT" || err.code === "ENOTDIR");
75
+
76
+ // The real place and the text of the file, with the faults of `readFile`.
77
+ async function load(path, folders, limit) {
78
+ const real = await realPlace(path, folders);
79
+ let info;
80
+ try {
81
+ info = await stat(real);
82
+ } catch (err) {
83
+ throw new ShellError(isGone(err) ? `${path}: no such file` : `${path}: cannot be read`);
84
+ }
85
+ if (!info.isFile()) throw new ShellError(`${path}: not a file`);
86
+ const over = () => new ShellError(`${path}: the file is over ${limit} bytes`);
87
+ if (info.size > limit) throw over();
88
+ let bytes;
89
+ try {
90
+ bytes = await readBytes(real);
91
+ } catch {
92
+ throw new ShellError(`${path}: cannot be read`);
93
+ }
94
+ if (bytes.length > limit) throw over();
95
+ return { real, text: bytes.toString("utf8") };
96
+ }
97
+
98
+ export async function readFile(path, { folders, limit = DEFAULT_LIMIT } = {}) {
99
+ return (await load(path, folders, limit)).text;
100
+ }
101
+
102
+ export async function writeFile(path, text, { folders } = {}) {
103
+ if (typeof text !== "string") throw new ShellError("the text must be a text");
104
+ const real = await realPlace(path, folders);
105
+ let info = null;
106
+ try {
107
+ info = await stat(real);
108
+ } catch (err) {
109
+ if (!isGone(err)) throw new ShellError(`${path}: cannot be written`);
110
+ }
111
+ if (info) {
112
+ if (!info.isFile()) throw new ShellError(`${path}: not a file`);
113
+ } else {
114
+ let parent = null;
115
+ try {
116
+ parent = await stat(dirname(real));
117
+ } catch {
118
+ // handled below
119
+ }
120
+ if (!parent || !parent.isDirectory()) throw new ShellError(`${path}: its folder does not exist`);
121
+ }
122
+ try {
123
+ await writeBytes(real, text, "utf8");
124
+ } catch {
125
+ throw new ShellError(`${path}: cannot be written`);
126
+ }
127
+ }
128
+
129
+ export async function editFile(path, oldText, newText, { folders, limit = DEFAULT_LIMIT } = {}) {
130
+ if (typeof oldText !== "string" || oldText === "") {
131
+ throw new ShellError("the old text must be a text that is not empty");
132
+ }
133
+ if (typeof newText !== "string") throw new ShellError("the new text must be a text");
134
+ const { real, text } = await load(path, folders, limit);
135
+ const count = text.split(oldText).length - 1;
136
+ if (count === 0) throw new ShellError(`${path}: the old text is not in the file`);
137
+ if (count > 1) {
138
+ throw new ShellError(`${path}: the old text is in the file ${count} times, it must be there once`);
139
+ }
140
+ const at = text.indexOf(oldText);
141
+ const edited = text.slice(0, at) + newText + text.slice(at + oldText.length);
142
+ try {
143
+ await writeBytes(real, edited, "utf8");
144
+ } catch {
145
+ throw new ShellError(`${path}: cannot be written`);
146
+ }
147
+ }
148
+
149
+ // ---- running one command
150
+
151
+ // The process groups of the commands still running, by the number of their shell.
152
+ const running = new Set();
153
+ let exitListener = false;
154
+
155
+ function killGroup(pid) {
156
+ try {
157
+ process.kill(-pid, "SIGKILL");
158
+ } catch {
159
+ // the group is already gone
160
+ }
161
+ }
162
+
163
+ function listenForExit() {
164
+ if (exitListener) return;
165
+ exitListener = true;
166
+ process.on("exit", () => {
167
+ for (const pid of running) killGroup(pid);
168
+ running.clear();
169
+ });
170
+ }
171
+
172
+ export function runCommand(command, { cwd, signal, env = process.env, outputLimit = DEFAULT_LIMIT } = {}) {
173
+ if (typeof command !== "string" || command.trim() === "") {
174
+ return Promise.reject(new ShellError("the command must be a text that is not empty"));
175
+ }
176
+ if (signal && signal.aborted) return Promise.reject(new ShellError("the command was stopped"));
177
+
178
+ return new Promise((resolvePromise, rejectPromise) => {
179
+ let child;
180
+ try {
181
+ child = spawn("/bin/sh", ["-c", command], { cwd, env, detached: true, stdio: ["ignore", "pipe", "pipe"] });
182
+ } catch {
183
+ rejectPromise(new ShellError("the command could not be started"));
184
+ return;
185
+ }
186
+ const notStarted = new ShellError("the command could not be started");
187
+ let pid = null;
188
+ let killed = false;
189
+ let stopError = null;
190
+ let exited = false;
191
+ let closed = false;
192
+ let exitCode = 0;
193
+ let settled = false;
194
+ const chunks = { stdout: [], stderr: [] };
195
+ const sizes = { stdout: 0, stderr: 0 };
196
+
197
+ const kill = () => {
198
+ if (killed || pid === null) return;
199
+ killed = true;
200
+ killGroup(pid);
201
+ };
202
+ const finish = (settle, value) => {
203
+ if (settled) return;
204
+ settled = true;
205
+ if (signal) signal.removeEventListener("abort", onAbort);
206
+ if (pid !== null) running.delete(pid);
207
+ if (child.stdout) child.stdout.destroy();
208
+ if (child.stderr) child.stderr.destroy();
209
+ settle(value);
210
+ };
211
+ const check = () => {
212
+ if (!exited) return;
213
+ if (stopError) finish(rejectPromise, stopError);
214
+ else if (closed) {
215
+ finish(resolvePromise, {
216
+ exitCode,
217
+ stdout: Buffer.concat(chunks.stdout).toString("utf8"),
218
+ stderr: Buffer.concat(chunks.stderr).toString("utf8"),
219
+ });
220
+ }
221
+ };
222
+ const stop = (error) => {
223
+ if (settled || stopError) return;
224
+ stopError = error;
225
+ kill();
226
+ check();
227
+ };
228
+ function onAbort() {
229
+ stop(new ShellError("the command was stopped"));
230
+ }
231
+
232
+ child.on("error", () => {
233
+ // only a shell that never started is a fault here; one that ran is judged by its end
234
+ if (child.pid === undefined) finish(rejectPromise, notStarted);
235
+ });
236
+ if (child.pid === undefined) return;
237
+ pid = child.pid;
238
+ running.add(pid);
239
+ listenForExit();
240
+
241
+ for (const name of ["stdout", "stderr"]) {
242
+ child[name].on("data", (chunk) => {
243
+ if (stopError) return;
244
+ sizes[name] += chunk.length;
245
+ if (sizes[name] > outputLimit) {
246
+ stop(new ShellError(`the output is over ${outputLimit} bytes`));
247
+ return;
248
+ }
249
+ chunks[name].push(chunk);
250
+ });
251
+ }
252
+ child.on("exit", (code, sig) => {
253
+ exited = true;
254
+ exitCode = code !== null ? code : 128 + (constants.signals[sig] ?? 0);
255
+ // nothing the command started outlives it; a stop that came while the shell was forking
256
+ // may have missed a child, so the group is swept once more now that the shell is gone
257
+ if (pid !== null) killGroup(pid);
258
+ check();
259
+ });
260
+ child.on("close", () => {
261
+ closed = true;
262
+ check();
263
+ });
264
+
265
+ if (signal) {
266
+ signal.addEventListener("abort", onAbort, { once: true });
267
+ if (signal.aborted) onAbort();
268
+ }
269
+ });
270
+ }