@kmmz1127/wash 0.0.0-stage → 0.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.
- package/LICENSE +21 -0
- package/README.md +148 -3
- package/dist/command-fs.d.ts +4 -0
- package/dist/command-fs.js +42 -0
- package/dist/fs.d.ts +32 -0
- package/dist/fs.js +8 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/just-bash-fs.d.ts +55 -0
- package/dist/just-bash-fs.js +235 -0
- package/dist/just-bash-shell.d.ts +13 -0
- package/dist/just-bash-shell.js +360 -0
- package/dist/line-editor.d.ts +35 -0
- package/dist/line-editor.js +198 -0
- package/dist/mountable-fs.d.ts +7 -0
- package/dist/mountable-fs.js +58 -0
- package/dist/shell.d.ts +74 -0
- package/dist/shell.js +1 -0
- package/dist/terminal-input.d.ts +35 -0
- package/dist/terminal-input.js +98 -0
- package/dist/terminal.d.ts +2 -0
- package/dist/terminal.js +3 -0
- package/docs/shell-io-and-mounts.md +48 -0
- package/package.json +43 -6
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
import { Bash, defineCommand, getCommandNames, InMemoryFs } from "just-bash";
|
|
2
|
+
import { commandFileSystem } from "./command-fs.js";
|
|
3
|
+
import { JustBashFsAdapter } from "./just-bash-fs.js";
|
|
4
|
+
import { WashMountableFs } from "./mountable-fs.js";
|
|
5
|
+
const HOME = "/home/user";
|
|
6
|
+
// Only standalone commands with literal arguments can stream to the terminal.
|
|
7
|
+
const literalWord = /(?:[^\s;&|<>(){}$'"`\\#!~*?=]|'[^'\r\n]*'|"[^"`$\\\r\n]*")+/;
|
|
8
|
+
const directCommand = new RegExp(`^[ \\t]*${literalWord.source}(?:[ \\t]+${literalWord.source})*[ \\t]*$`);
|
|
9
|
+
// 行の最後まで実行されたかを確かめるコマンド。直前の終了コードをそのまま返す。
|
|
10
|
+
const DONE = "__wash_done";
|
|
11
|
+
// 前の行の終了コードを $? として引き継ぐコマンド。
|
|
12
|
+
const STATUS = "__wash_status";
|
|
13
|
+
// 行末の奇数個の \ は次の行への継続になるため、目印を付けない。
|
|
14
|
+
const continuation = /(?:^|[^\\])(?:\\\\)*\\$/;
|
|
15
|
+
const exitWord = /(?:^|[\s;&|(){}])exit(?:$|[\s;&|(){}])/;
|
|
16
|
+
const commandPosition = /(?:^|[;&|(]|\bthen|\bdo|\belse)$/;
|
|
17
|
+
const ALIAS_PREFIX = "BASH_ALIAS_";
|
|
18
|
+
const NAME = /^[a-zA-Z_][a-zA-Z0-9_+-]*$/;
|
|
19
|
+
const COMPLETE_TIMEOUT = 1000;
|
|
20
|
+
const BUILTINS = [
|
|
21
|
+
"alias", "break", "builtin", "cd", "command", "continue", "declare", "eval", "exec", "exit", "export",
|
|
22
|
+
"false", "getopts", "hash", "help", "history", "let", "local", "pwd", "read", "readonly", "return",
|
|
23
|
+
"set", "shift", "shopt", "source", "test", "true", "type", "unalias", "unset",
|
|
24
|
+
];
|
|
25
|
+
/** just-bashを利用したWashShellの実装。just-bashへの依存はこのファイルに閉じ込める。 */
|
|
26
|
+
export async function createJustBashShell(options = {}) {
|
|
27
|
+
const fs = new WashMountableFs({ base: new InMemoryFs() });
|
|
28
|
+
for (const [path, mounted] of Object.entries(options.mounts ?? {})) {
|
|
29
|
+
fs.mount(path, new JustBashFsAdapter(mounted));
|
|
30
|
+
}
|
|
31
|
+
let activeTerminal;
|
|
32
|
+
let pending = Promise.resolve();
|
|
33
|
+
let finished = false;
|
|
34
|
+
let lastStatus = 0;
|
|
35
|
+
// just-bashのコマンドは削除できないため、名前ごとに登録表を引くコマンドを1つだけ登録する。
|
|
36
|
+
const commands = new Map();
|
|
37
|
+
const dispatchers = new Set();
|
|
38
|
+
// 既定の別名と、利用者がunaliasで解除したために追加し直さない名前。
|
|
39
|
+
const defaultAliases = new Map();
|
|
40
|
+
const declinedAliases = new Set();
|
|
41
|
+
const doneCommand = defineCommand(DONE, async ([code]) => {
|
|
42
|
+
finished = true;
|
|
43
|
+
return { stdout: "", stderr: "", exitCode: Number(code) || 0 };
|
|
44
|
+
});
|
|
45
|
+
const statusCommand = defineCommand(STATUS, async ([code]) => ({ stdout: "", stderr: "", exitCode: Number(code) || 0 }));
|
|
46
|
+
const bash = new Bash({ fs, cwd: HOME,
|
|
47
|
+
env: { HOME, USER: "user", PATH: `${HOME}/bin:/usr/bin:/bin` }, customCommands: [doneCommand, statusCommand] });
|
|
48
|
+
const dispatcher = (name) => defineCommand(name, async (args, ctx) => {
|
|
49
|
+
const command = commands.get(name);
|
|
50
|
+
if (!command)
|
|
51
|
+
return { stdout: "", stderr: `bash: ${name}: command not found\n`, exitCode: 127 };
|
|
52
|
+
return command.run(args, {
|
|
53
|
+
fs: commandFileSystem(ctx.fs, ctx.cwd),
|
|
54
|
+
async exec(line, execOptions) {
|
|
55
|
+
if (!ctx.exec)
|
|
56
|
+
throw new Error("exec is not available in this context");
|
|
57
|
+
const result = await ctx.exec(line, { cwd: ctx.cwd, stdin: execOptions?.stdin, signal: execOptions?.signal ?? ctx.signal });
|
|
58
|
+
return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };
|
|
59
|
+
},
|
|
60
|
+
cwd: ctx.cwd,
|
|
61
|
+
env: Object.fromEntries(ctx.env),
|
|
62
|
+
stdin: decodeLatin1Bytes(ctx.stdin),
|
|
63
|
+
signal: ctx.signal,
|
|
64
|
+
terminal: ctx.stdinProvided || ctx.stdinUnavailable ? undefined : activeTerminal,
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
function registerCommand(command) {
|
|
68
|
+
if (!NAME.test(command.name))
|
|
69
|
+
throw new Error(`Invalid command name: ${command.name}`);
|
|
70
|
+
if (commands.has(command.name))
|
|
71
|
+
throw new Error(`Command already registered: ${command.name}`);
|
|
72
|
+
commands.set(command.name, command);
|
|
73
|
+
if (!dispatchers.has(command.name)) {
|
|
74
|
+
bash.registerCommand(dispatcher(command.name));
|
|
75
|
+
dispatchers.add(command.name);
|
|
76
|
+
}
|
|
77
|
+
return () => {
|
|
78
|
+
if (commands.get(command.name) === command)
|
|
79
|
+
commands.delete(command.name);
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
for (const command of options.commands ?? [])
|
|
83
|
+
registerCommand(command);
|
|
84
|
+
await bash.exec(`mkdir -p /tmp /etc ${HOME}/bin`);
|
|
85
|
+
let env = bash.getEnv();
|
|
86
|
+
/** 行の実行で消えた既定の別名を、利用者が解除したものとして記録する。 */
|
|
87
|
+
function recordUnalias(before) {
|
|
88
|
+
for (const [name, expansion] of defaultAliases) {
|
|
89
|
+
const key = ALIAS_PREFIX + name;
|
|
90
|
+
if (before[key] === expansion && env[key] === undefined)
|
|
91
|
+
declinedAliases.add(name);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async function commandExists(name) {
|
|
95
|
+
if (commands.has(name) || BUILTINS.includes(name) || getCommandNames().includes(name))
|
|
96
|
+
return true;
|
|
97
|
+
for (const directory of (env.PATH ?? "").split(":")) {
|
|
98
|
+
if (directory && await fs.exists(fs.resolvePath(directory, name)))
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
async function addDefaultAlias(name, expansion) {
|
|
104
|
+
if (!NAME.test(name) || !expansion.trim())
|
|
105
|
+
throw new Error(`Invalid default alias: ${name}`);
|
|
106
|
+
const key = ALIAS_PREFIX + name;
|
|
107
|
+
const added = await queue(async () => {
|
|
108
|
+
if (declinedAliases.has(name) || env[key] !== undefined || await commandExists(name))
|
|
109
|
+
return false;
|
|
110
|
+
defaultAliases.set(name, expansion);
|
|
111
|
+
env = { ...env, [key]: expansion };
|
|
112
|
+
return true;
|
|
113
|
+
});
|
|
114
|
+
return () => {
|
|
115
|
+
if (!added || defaultAliases.get(name) !== expansion)
|
|
116
|
+
return;
|
|
117
|
+
defaultAliases.delete(name);
|
|
118
|
+
if (env[key] === expansion) {
|
|
119
|
+
const { [key]: _removed, ...rest } = env;
|
|
120
|
+
env = rest;
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
for (const [name, expansion] of Object.entries(options.aliases ?? {}))
|
|
125
|
+
await addDefaultAlias(name, expansion);
|
|
126
|
+
let expandAliases = true;
|
|
127
|
+
if (options.cwd)
|
|
128
|
+
env = (await bash.exec(`cd ${quote(options.cwd)}`, { env, replaceEnv: true, cwd: env.PWD })).env;
|
|
129
|
+
/** シェルの操作を1つずつ順に実行する。 */
|
|
130
|
+
function queue(run) {
|
|
131
|
+
const result = pending.then(run);
|
|
132
|
+
pending = result.catch(() => { });
|
|
133
|
+
return result;
|
|
134
|
+
}
|
|
135
|
+
/** 補完のときに登録コマンドへ渡すコンテキスト。 */
|
|
136
|
+
function completionContext(signal) {
|
|
137
|
+
const cwd = env.PWD ?? HOME;
|
|
138
|
+
return {
|
|
139
|
+
fs: commandFileSystem(fs, cwd),
|
|
140
|
+
async exec(line, execOptions) {
|
|
141
|
+
const result = await bash.exec(line, { env, replaceEnv: true, cwd, stdin: execOptions?.stdin, signal: execOptions?.signal ?? signal });
|
|
142
|
+
return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };
|
|
143
|
+
},
|
|
144
|
+
cwd,
|
|
145
|
+
env: { ...env },
|
|
146
|
+
stdin: "",
|
|
147
|
+
signal,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
async function commandNames(prefix) {
|
|
151
|
+
const names = [
|
|
152
|
+
...BUILTINS,
|
|
153
|
+
...getCommandNames(),
|
|
154
|
+
...commands.keys(),
|
|
155
|
+
...Object.keys(env).filter((key) => key.startsWith(ALIAS_PREFIX)).map((key) => key.slice(ALIAS_PREFIX.length)),
|
|
156
|
+
];
|
|
157
|
+
for (const directory of (env.PATH ?? "").split(":")) {
|
|
158
|
+
if (!directory)
|
|
159
|
+
continue;
|
|
160
|
+
try {
|
|
161
|
+
names.push(...await fs.readdir(directory));
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
// PATHに存在しないディレクトリが含まれていても補完を続ける。
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const matched = names.filter((name) => name.startsWith(prefix) && name !== DONE && name !== STATUS);
|
|
168
|
+
const descriptions = {};
|
|
169
|
+
for (const name of matched) {
|
|
170
|
+
const description = commands.get(name)?.description;
|
|
171
|
+
if (description)
|
|
172
|
+
descriptions[name] = description;
|
|
173
|
+
}
|
|
174
|
+
return { names: matched.map((name) => name + " "), descriptions };
|
|
175
|
+
}
|
|
176
|
+
async function pathNames(word) {
|
|
177
|
+
const slash = word.lastIndexOf("/");
|
|
178
|
+
const directoryPart = word.slice(0, slash + 1);
|
|
179
|
+
const prefix = unescapeWord(word.slice(slash + 1));
|
|
180
|
+
const expanded = directoryPart === "~/" || directoryPart.startsWith("~/") ? HOME + directoryPart.slice(1) : directoryPart;
|
|
181
|
+
try {
|
|
182
|
+
const directory = fs.resolvePath(env.PWD ?? HOME, unescapeWord(expanded) || ".");
|
|
183
|
+
const names = (await fs.readdir(directory))
|
|
184
|
+
.filter((name) => name.startsWith(prefix) && (prefix.startsWith(".") || !name.startsWith(".")));
|
|
185
|
+
return await Promise.all(names.map(async (name) => {
|
|
186
|
+
const isDirectory = await fs.stat(fs.resolvePath(directory, name)).then((stat) => stat.isDirectory, () => false);
|
|
187
|
+
return directoryPart + escapeWord(name) + (isDirectory ? "/" : " ");
|
|
188
|
+
}));
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
return [];
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/** 登録コマンドの complete に引数の補完を委ねる。対象外、エラー、時間切れのときは undefined を返す。 */
|
|
195
|
+
async function commandArguments(before, word) {
|
|
196
|
+
let words = splitWords(before.slice(lastSeparator(before)));
|
|
197
|
+
const alias = words.length ? env[ALIAS_PREFIX + words[0]] : undefined;
|
|
198
|
+
if (alias !== undefined)
|
|
199
|
+
words = [...splitWords(alias), ...words.slice(1)];
|
|
200
|
+
const command = words.length ? commands.get(words[0]) : undefined;
|
|
201
|
+
if (!command?.complete)
|
|
202
|
+
return undefined;
|
|
203
|
+
const controller = new AbortController();
|
|
204
|
+
let timer;
|
|
205
|
+
try {
|
|
206
|
+
const timeout = new Promise((resolve) => {
|
|
207
|
+
timer = setTimeout(() => {
|
|
208
|
+
controller.abort();
|
|
209
|
+
resolve(undefined);
|
|
210
|
+
}, COMPLETE_TIMEOUT);
|
|
211
|
+
});
|
|
212
|
+
const candidates = await Promise.race([
|
|
213
|
+
command.complete([...words.slice(1), unescapeWord(word)], completionContext(controller.signal)),
|
|
214
|
+
timeout,
|
|
215
|
+
]);
|
|
216
|
+
return candidates?.map((candidate) => escapeWord(candidate) + (candidate.endsWith("/") ? "" : " "));
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
finally {
|
|
222
|
+
clearTimeout(timer);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return {
|
|
226
|
+
get cwd() {
|
|
227
|
+
return env.PWD ?? HOME;
|
|
228
|
+
},
|
|
229
|
+
get home() {
|
|
230
|
+
return env.HOME ?? HOME;
|
|
231
|
+
},
|
|
232
|
+
exec(line, signal, terminal) {
|
|
233
|
+
return queue(async () => {
|
|
234
|
+
signal?.throwIfAborted();
|
|
235
|
+
activeTerminal = terminal && directCommand.test(line) ? terminal : undefined;
|
|
236
|
+
try {
|
|
237
|
+
const marked = !continuation.test(line);
|
|
238
|
+
let script = `${STATUS} ${lastStatus}\n${marked ? `${line}\n${DONE} $?` : line}`;
|
|
239
|
+
// just-bash resets shopt state for each exec. Apply the terminal's setting before the input.
|
|
240
|
+
if (expandAliases)
|
|
241
|
+
script = "shopt -s expand_aliases\n" + script;
|
|
242
|
+
finished = false;
|
|
243
|
+
const before = env;
|
|
244
|
+
const result = await bash.exec(script, { env, replaceEnv: true, cwd: env.PWD, signal });
|
|
245
|
+
env = result.env;
|
|
246
|
+
recordUnalias(before);
|
|
247
|
+
expandAliases = env.BASHOPTS?.split(":").includes("expand_aliases") ?? false;
|
|
248
|
+
// just-bashはexitで終了したことを返さないため、行の最後まで実行されたかで判断する。
|
|
249
|
+
const exited = marked && !finished && !signal?.aborted && exitWord.test(line);
|
|
250
|
+
lastStatus = result.exitCode;
|
|
251
|
+
return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode, ...(exited ? { exited } : {}) };
|
|
252
|
+
}
|
|
253
|
+
finally {
|
|
254
|
+
activeTerminal = undefined;
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
},
|
|
258
|
+
async complete(text) {
|
|
259
|
+
const start = wordStart(text);
|
|
260
|
+
const word = text.slice(start);
|
|
261
|
+
const before = text.slice(0, start);
|
|
262
|
+
if (commandPosition.test(before.trimEnd()) && !word.includes("/")) {
|
|
263
|
+
const { names, descriptions } = await commandNames(word);
|
|
264
|
+
return { start, candidates: [...new Set(names)].sort(), ...(Object.keys(descriptions).length ? { descriptions } : {}) };
|
|
265
|
+
}
|
|
266
|
+
const candidates = await commandArguments(before, word) ?? await pathNames(word);
|
|
267
|
+
return { start, candidates: [...new Set(candidates)].sort() };
|
|
268
|
+
},
|
|
269
|
+
registerCommand,
|
|
270
|
+
addDefaultAlias,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
/** 補完する単語の開始位置。引用符の外にある空白や区切り記号の直後から始まる。 */
|
|
274
|
+
function wordStart(text) {
|
|
275
|
+
let start = 0;
|
|
276
|
+
scan(text, (char, index) => {
|
|
277
|
+
if (/[\s;&|<>()]/.test(char))
|
|
278
|
+
start = index + 1;
|
|
279
|
+
});
|
|
280
|
+
return start;
|
|
281
|
+
}
|
|
282
|
+
/** 引用符の外にある最後のコマンド区切り(; & | ( )の次の位置。 */
|
|
283
|
+
function lastSeparator(text) {
|
|
284
|
+
let position = 0;
|
|
285
|
+
scan(text, (char, index) => {
|
|
286
|
+
if (/[;&|(]/.test(char))
|
|
287
|
+
position = index + 1;
|
|
288
|
+
});
|
|
289
|
+
return position;
|
|
290
|
+
}
|
|
291
|
+
/** 引用符とバックスラッシュを考慮して、引用符の外にある文字ごとに visit を呼ぶ。 */
|
|
292
|
+
function scan(text, visit) {
|
|
293
|
+
let quoted;
|
|
294
|
+
for (let index = 0; index < text.length; index++) {
|
|
295
|
+
const char = text[index];
|
|
296
|
+
if (quoted) {
|
|
297
|
+
if (char === quoted)
|
|
298
|
+
quoted = undefined;
|
|
299
|
+
}
|
|
300
|
+
else if (char === "\\") {
|
|
301
|
+
index++;
|
|
302
|
+
}
|
|
303
|
+
else if (char === "'" || char === '"') {
|
|
304
|
+
quoted = char;
|
|
305
|
+
}
|
|
306
|
+
else {
|
|
307
|
+
visit(char, index);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/** 補完のために、空白で区切られた単語へ分ける。引用符とバックスラッシュは外す。 */
|
|
312
|
+
function splitWords(text) {
|
|
313
|
+
const words = [];
|
|
314
|
+
let current = "";
|
|
315
|
+
let quoted;
|
|
316
|
+
let inWord = false;
|
|
317
|
+
for (let index = 0; index < text.length; index++) {
|
|
318
|
+
const char = text[index];
|
|
319
|
+
if (quoted) {
|
|
320
|
+
if (char === quoted)
|
|
321
|
+
quoted = undefined;
|
|
322
|
+
else
|
|
323
|
+
current += char;
|
|
324
|
+
}
|
|
325
|
+
else if (char === "\\" && index + 1 < text.length) {
|
|
326
|
+
current += text[++index];
|
|
327
|
+
inWord = true;
|
|
328
|
+
}
|
|
329
|
+
else if (char === "'" || char === '"') {
|
|
330
|
+
quoted = char;
|
|
331
|
+
inWord = true;
|
|
332
|
+
}
|
|
333
|
+
else if (/\s/.test(char)) {
|
|
334
|
+
if (inWord)
|
|
335
|
+
words.push(current);
|
|
336
|
+
current = "";
|
|
337
|
+
inWord = false;
|
|
338
|
+
}
|
|
339
|
+
else {
|
|
340
|
+
current += char;
|
|
341
|
+
inWord = true;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
if (inWord)
|
|
345
|
+
words.push(current);
|
|
346
|
+
return words;
|
|
347
|
+
}
|
|
348
|
+
function escapeWord(name) {
|
|
349
|
+
return name.replace(/[\s'"\\$`;&|<>()*?![\]{}#~]/g, "\\$&");
|
|
350
|
+
}
|
|
351
|
+
function unescapeWord(word) {
|
|
352
|
+
return word.replace(/\\(.)/g, "$1");
|
|
353
|
+
}
|
|
354
|
+
/** just-bashのstdin(1文字1バイトの文字列)をUTF-8として復号する。 */
|
|
355
|
+
function decodeLatin1Bytes(bytes) {
|
|
356
|
+
return new TextDecoder().decode(Uint8Array.from(bytes, (c) => c.charCodeAt(0)));
|
|
357
|
+
}
|
|
358
|
+
function quote(text) {
|
|
359
|
+
return `'${text.replace(/'/g, "'\\''")}'`;
|
|
360
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** 端末に表示したときの文字の幅。全角文字は2、結合文字は0とする。 */
|
|
2
|
+
export declare function charWidth(char: string): number;
|
|
3
|
+
export declare function textWidth(text: string): number;
|
|
4
|
+
/** 端末からの入力を、エスケープシーケンスと1文字ずつのキーに分ける。 */
|
|
5
|
+
export declare function splitKeys(data: string): string[];
|
|
6
|
+
export type EditResult = "edited" | "submit" | "eof" | "interrupt" | "clear" | "complete" | "ignored";
|
|
7
|
+
/** プロンプト付きの1行入力。文字はコードポイント単位で扱い、表示は端末の折り返しを考慮して書き直す。 */
|
|
8
|
+
export declare class LineEditor {
|
|
9
|
+
private readonly write;
|
|
10
|
+
private readonly history;
|
|
11
|
+
private chars;
|
|
12
|
+
private cursor;
|
|
13
|
+
private renderedRow;
|
|
14
|
+
private historyIndex;
|
|
15
|
+
private draft?;
|
|
16
|
+
columns: number;
|
|
17
|
+
constructor(write: (text: string) => void, history: () => readonly string[]);
|
|
18
|
+
get text(): string;
|
|
19
|
+
/** カーソルより前の入力。補完に使う。 */
|
|
20
|
+
get beforeCursor(): string;
|
|
21
|
+
/** カーソルより前の入力のうち、start(UTF-16の位置)からカーソルまでを text に置き換える。 */
|
|
22
|
+
replaceBeforeCursor(start: number, text: string): void;
|
|
23
|
+
/** 入力を空にして、表示上の位置を新しい行の先頭として扱う。 */
|
|
24
|
+
reset(): void;
|
|
25
|
+
/** 画面を消去した後に呼び、カーソルが左上にあるものとして扱う。 */
|
|
26
|
+
screenCleared(): void;
|
|
27
|
+
key(key: string): EditResult;
|
|
28
|
+
/** プロンプトと入力行を書き直し、カーソルを入力位置へ戻す。 */
|
|
29
|
+
render(prompt: string): void;
|
|
30
|
+
/** カーソルを入力の末尾の次の行へ移す。実行や中断の前に呼ぶ。 */
|
|
31
|
+
finish(prompt: string): void;
|
|
32
|
+
private deleteRange;
|
|
33
|
+
private move;
|
|
34
|
+
private recall;
|
|
35
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/** 端末に表示したときの文字の幅。全角文字は2、結合文字は0とする。 */
|
|
2
|
+
export function charWidth(char) {
|
|
3
|
+
const code = char.codePointAt(0);
|
|
4
|
+
if (code < 0x20 || (code >= 0x7f && code < 0xa0))
|
|
5
|
+
return 0;
|
|
6
|
+
if ((code >= 0x300 && code <= 0x36f) || (code >= 0x200b && code <= 0x200f) || (code >= 0xfe00 && code <= 0xfe0f))
|
|
7
|
+
return 0;
|
|
8
|
+
if ((code >= 0x1100 && code <= 0x115f) ||
|
|
9
|
+
(code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f) ||
|
|
10
|
+
(code >= 0xac00 && code <= 0xd7a3) ||
|
|
11
|
+
(code >= 0xf900 && code <= 0xfaff) ||
|
|
12
|
+
(code >= 0xfe30 && code <= 0xfe4f) ||
|
|
13
|
+
(code >= 0xff00 && code <= 0xff60) ||
|
|
14
|
+
(code >= 0xffe0 && code <= 0xffe6) ||
|
|
15
|
+
(code >= 0x1f300 && code <= 0x1f64f) ||
|
|
16
|
+
(code >= 0x1f900 && code <= 0x1f9ff) ||
|
|
17
|
+
(code >= 0x20000 && code <= 0x3fffd)) {
|
|
18
|
+
return 2;
|
|
19
|
+
}
|
|
20
|
+
return 1;
|
|
21
|
+
}
|
|
22
|
+
export function textWidth(text) {
|
|
23
|
+
let width = 0;
|
|
24
|
+
for (const char of text.replace(/\x1b\[[0-9;]*[A-Za-z]/g, ""))
|
|
25
|
+
width += charWidth(char);
|
|
26
|
+
return width;
|
|
27
|
+
}
|
|
28
|
+
const escapeSequence = /^\x1b(?:\[[0-9;]*[~A-Za-z]|O[A-Za-z]|.)?/;
|
|
29
|
+
/** 端末からの入力を、エスケープシーケンスと1文字ずつのキーに分ける。 */
|
|
30
|
+
export function splitKeys(data) {
|
|
31
|
+
const keys = [];
|
|
32
|
+
let rest = data.replace(/\r\n/g, "\r");
|
|
33
|
+
while (rest) {
|
|
34
|
+
const escape = rest.startsWith("\x1b") ? escapeSequence.exec(rest)[0] : undefined;
|
|
35
|
+
const key = escape ?? String.fromCodePoint(rest.codePointAt(0));
|
|
36
|
+
keys.push(key);
|
|
37
|
+
rest = rest.slice(key.length);
|
|
38
|
+
}
|
|
39
|
+
return keys;
|
|
40
|
+
}
|
|
41
|
+
/** プロンプト付きの1行入力。文字はコードポイント単位で扱い、表示は端末の折り返しを考慮して書き直す。 */
|
|
42
|
+
export class LineEditor {
|
|
43
|
+
write;
|
|
44
|
+
history;
|
|
45
|
+
chars = [];
|
|
46
|
+
cursor = 0;
|
|
47
|
+
renderedRow = 0;
|
|
48
|
+
historyIndex = 0;
|
|
49
|
+
draft;
|
|
50
|
+
columns = 80;
|
|
51
|
+
constructor(write, history) {
|
|
52
|
+
this.write = write;
|
|
53
|
+
this.history = history;
|
|
54
|
+
}
|
|
55
|
+
get text() {
|
|
56
|
+
return this.chars.join("");
|
|
57
|
+
}
|
|
58
|
+
/** カーソルより前の入力。補完に使う。 */
|
|
59
|
+
get beforeCursor() {
|
|
60
|
+
return this.chars.slice(0, this.cursor).join("");
|
|
61
|
+
}
|
|
62
|
+
/** カーソルより前の入力のうち、start(UTF-16の位置)からカーソルまでを text に置き換える。 */
|
|
63
|
+
replaceBeforeCursor(start, text) {
|
|
64
|
+
const kept = Array.from(this.beforeCursor.slice(0, start));
|
|
65
|
+
const inserted = Array.from(text);
|
|
66
|
+
this.chars.splice(0, this.cursor, ...kept, ...inserted);
|
|
67
|
+
this.cursor = kept.length + inserted.length;
|
|
68
|
+
}
|
|
69
|
+
/** 入力を空にして、表示上の位置を新しい行の先頭として扱う。 */
|
|
70
|
+
reset() {
|
|
71
|
+
this.chars = [];
|
|
72
|
+
this.cursor = 0;
|
|
73
|
+
this.renderedRow = 0;
|
|
74
|
+
this.historyIndex = this.history().length;
|
|
75
|
+
this.draft = undefined;
|
|
76
|
+
}
|
|
77
|
+
/** 画面を消去した後に呼び、カーソルが左上にあるものとして扱う。 */
|
|
78
|
+
screenCleared() {
|
|
79
|
+
this.renderedRow = 0;
|
|
80
|
+
}
|
|
81
|
+
key(key) {
|
|
82
|
+
switch (key) {
|
|
83
|
+
case "\r":
|
|
84
|
+
case "\n":
|
|
85
|
+
return "submit";
|
|
86
|
+
case "\x03":
|
|
87
|
+
return "interrupt";
|
|
88
|
+
case "\x04":
|
|
89
|
+
if (this.chars.length === 0)
|
|
90
|
+
return "eof";
|
|
91
|
+
return this.deleteRange(this.cursor, this.cursor + 1);
|
|
92
|
+
case "\x0c":
|
|
93
|
+
return "clear";
|
|
94
|
+
case "\t":
|
|
95
|
+
return "complete";
|
|
96
|
+
case "\x7f":
|
|
97
|
+
case "\b":
|
|
98
|
+
return this.deleteRange(this.cursor - 1, this.cursor);
|
|
99
|
+
case "\x1b[3~":
|
|
100
|
+
return this.deleteRange(this.cursor, this.cursor + 1);
|
|
101
|
+
case "\x15":
|
|
102
|
+
return this.deleteRange(0, this.cursor);
|
|
103
|
+
case "\x0b":
|
|
104
|
+
return this.deleteRange(this.cursor, this.chars.length);
|
|
105
|
+
case "\x17": {
|
|
106
|
+
let start = this.cursor;
|
|
107
|
+
while (start > 0 && this.chars[start - 1] === " ")
|
|
108
|
+
start--;
|
|
109
|
+
while (start > 0 && this.chars[start - 1] !== " ")
|
|
110
|
+
start--;
|
|
111
|
+
return this.deleteRange(start, this.cursor);
|
|
112
|
+
}
|
|
113
|
+
case "\x1b[D":
|
|
114
|
+
case "\x02":
|
|
115
|
+
return this.move(this.cursor - 1);
|
|
116
|
+
case "\x1b[C":
|
|
117
|
+
case "\x06":
|
|
118
|
+
return this.move(this.cursor + 1);
|
|
119
|
+
case "\x01":
|
|
120
|
+
case "\x1b[H":
|
|
121
|
+
case "\x1bOH":
|
|
122
|
+
case "\x1b[1~":
|
|
123
|
+
return this.move(0);
|
|
124
|
+
case "\x05":
|
|
125
|
+
case "\x1b[F":
|
|
126
|
+
case "\x1bOF":
|
|
127
|
+
case "\x1b[4~":
|
|
128
|
+
return this.move(this.chars.length);
|
|
129
|
+
case "\x1b[A":
|
|
130
|
+
case "\x10":
|
|
131
|
+
return this.recall(-1);
|
|
132
|
+
case "\x1b[B":
|
|
133
|
+
case "\x0e":
|
|
134
|
+
return this.recall(1);
|
|
135
|
+
}
|
|
136
|
+
if (key.startsWith("\x1b") || charWidth(key) === 0 && key.codePointAt(0) < 0x20)
|
|
137
|
+
return "ignored";
|
|
138
|
+
this.chars.splice(this.cursor, 0, key);
|
|
139
|
+
this.cursor++;
|
|
140
|
+
return "edited";
|
|
141
|
+
}
|
|
142
|
+
/** プロンプトと入力行を書き直し、カーソルを入力位置へ戻す。 */
|
|
143
|
+
render(prompt) {
|
|
144
|
+
const columns = Math.max(this.columns, 1);
|
|
145
|
+
const promptWidth = textWidth(prompt);
|
|
146
|
+
const end = promptWidth + textWidth(this.text);
|
|
147
|
+
const cursor = promptWidth + textWidth(this.chars.slice(0, this.cursor).join(""));
|
|
148
|
+
let output = this.renderedRow > 0 ? `\x1b[${this.renderedRow}A` : "";
|
|
149
|
+
output += `\r\x1b[J${prompt}${this.text}`;
|
|
150
|
+
// 行末ちょうどで止まったカーソルを次の行へ進め、以降の計算と実際の位置を合わせる。
|
|
151
|
+
if (end > 0 && end % columns === 0)
|
|
152
|
+
output += " \r";
|
|
153
|
+
const endRow = Math.floor(end / columns);
|
|
154
|
+
const cursorRow = Math.floor(cursor / columns);
|
|
155
|
+
if (endRow > cursorRow)
|
|
156
|
+
output += `\x1b[${endRow - cursorRow}A`;
|
|
157
|
+
output += "\r";
|
|
158
|
+
if (cursor % columns > 0)
|
|
159
|
+
output += `\x1b[${cursor % columns}C`;
|
|
160
|
+
this.renderedRow = cursorRow;
|
|
161
|
+
this.write(output);
|
|
162
|
+
}
|
|
163
|
+
/** カーソルを入力の末尾の次の行へ移す。実行や中断の前に呼ぶ。 */
|
|
164
|
+
finish(prompt) {
|
|
165
|
+
const columns = Math.max(this.columns, 1);
|
|
166
|
+
const end = textWidth(prompt) + textWidth(this.text);
|
|
167
|
+
const rows = Math.floor(end / columns) - this.renderedRow;
|
|
168
|
+
this.write(`${rows > 0 ? `\x1b[${rows}B` : ""}\r\n`);
|
|
169
|
+
this.renderedRow = 0;
|
|
170
|
+
}
|
|
171
|
+
deleteRange(start, end) {
|
|
172
|
+
start = Math.max(start, 0);
|
|
173
|
+
end = Math.min(end, this.chars.length);
|
|
174
|
+
if (start >= end)
|
|
175
|
+
return "ignored";
|
|
176
|
+
this.chars.splice(start, end - start);
|
|
177
|
+
this.cursor = start;
|
|
178
|
+
return "edited";
|
|
179
|
+
}
|
|
180
|
+
move(position) {
|
|
181
|
+
if (position < 0 || position > this.chars.length || position === this.cursor)
|
|
182
|
+
return "ignored";
|
|
183
|
+
this.cursor = position;
|
|
184
|
+
return "edited";
|
|
185
|
+
}
|
|
186
|
+
recall(delta) {
|
|
187
|
+
const history = this.history();
|
|
188
|
+
const index = this.historyIndex + delta;
|
|
189
|
+
if (index < 0 || index > history.length)
|
|
190
|
+
return "ignored";
|
|
191
|
+
if (this.historyIndex === history.length)
|
|
192
|
+
this.draft = this.chars;
|
|
193
|
+
this.historyIndex = index;
|
|
194
|
+
this.chars = index === history.length ? (this.draft ?? []) : Array.from(history[index]);
|
|
195
|
+
this.cursor = this.chars.length;
|
|
196
|
+
return "edited";
|
|
197
|
+
}
|
|
198
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { MountableFs } from "just-bash";
|
|
2
|
+
export declare class WashMountableFs extends MountableFs {
|
|
3
|
+
cp(src: string, dest: string, options?: Parameters<MountableFs["cp"]>[2]): Promise<void>;
|
|
4
|
+
mv(src: string, dest: string): Promise<void>;
|
|
5
|
+
private adapter;
|
|
6
|
+
private transfer;
|
|
7
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { MountableFs } from "just-bash";
|
|
2
|
+
import { JustBashFsAdapter } from "./just-bash-fs.js";
|
|
3
|
+
const EXECUTE = 0o111;
|
|
4
|
+
export class WashMountableFs extends MountableFs {
|
|
5
|
+
async cp(src, dest, options) {
|
|
6
|
+
await this.transfer(this.resolvePath("/", src), this.resolvePath("/", dest), options?.recursive ?? false, false);
|
|
7
|
+
}
|
|
8
|
+
async mv(src, dest) {
|
|
9
|
+
const from = this.resolvePath("/", src);
|
|
10
|
+
const to = this.resolvePath("/", dest);
|
|
11
|
+
const origin = this.adapter(from);
|
|
12
|
+
if (origin === this.adapter(to) || this.isMountPoint(from)) {
|
|
13
|
+
return super.mv(from, to);
|
|
14
|
+
}
|
|
15
|
+
if (origin?.readOnly)
|
|
16
|
+
throw new Error(`EROFS: cannot move '${from}' from a read-only mount`);
|
|
17
|
+
await this.transfer(from, to, true, true);
|
|
18
|
+
await this.rm(from, { recursive: true });
|
|
19
|
+
}
|
|
20
|
+
adapter(path) {
|
|
21
|
+
const mount = this.getMounts().find(({ mountPoint }) => path === mountPoint || path.startsWith(mountPoint + "/"));
|
|
22
|
+
return mount?.filesystem instanceof JustBashFsAdapter ? mount.filesystem : undefined;
|
|
23
|
+
}
|
|
24
|
+
async transfer(src, dest, recursive, moving) {
|
|
25
|
+
const stat = await this.lstat(src);
|
|
26
|
+
if (stat.isDirectory) {
|
|
27
|
+
if (!recursive)
|
|
28
|
+
throw new Error(`EISDIR: is a directory, cp '${src}'`);
|
|
29
|
+
if (src === dest || dest.startsWith(src === "/" ? "/" : src + "/")) {
|
|
30
|
+
throw new Error(`EINVAL: cannot copy '${src}' into itself, '${dest}'`);
|
|
31
|
+
}
|
|
32
|
+
await this.mkdir(dest, { recursive: true });
|
|
33
|
+
for (const name of await this.readdir(src)) {
|
|
34
|
+
await this.transfer(this.resolvePath(src, name), this.resolvePath(dest, name), true, moving);
|
|
35
|
+
}
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (!stat.isFile)
|
|
39
|
+
return super.cp(src, dest, { recursive });
|
|
40
|
+
if (src === dest)
|
|
41
|
+
throw new Error(`EINVAL: '${src}' and '${dest}' are the same file`);
|
|
42
|
+
const previous = await this.exists(dest) ? await this.stat(dest) : undefined;
|
|
43
|
+
const mode = previous?.mode ?? 0o644;
|
|
44
|
+
const execute = (moving || !previous ? stat.mode : mode) & EXECUTE;
|
|
45
|
+
const target = this.adapter(dest);
|
|
46
|
+
const canSetMode = !target || target.preservesModes;
|
|
47
|
+
if (moving && !canSetMode && (mode & EXECUTE) !== execute) {
|
|
48
|
+
throw new Error(`ENOSYS: cannot preserve execute permissions on '${dest}'`);
|
|
49
|
+
}
|
|
50
|
+
await this.writeFile(dest, await this.readFileBuffer(src));
|
|
51
|
+
const nextMode = (mode & ~EXECUTE) | execute;
|
|
52
|
+
if (canSetMode && (await this.stat(dest)).mode !== nextMode)
|
|
53
|
+
await this.chmod(dest, nextMode);
|
|
54
|
+
if (moving && ((await this.stat(dest)).mode & EXECUTE) !== execute) {
|
|
55
|
+
throw new Error(`EIO: destination did not preserve execute permissions on '${dest}'`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|