@taliesinb/mash 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.
Files changed (203) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +275 -2
  3. package/bin/mash.ts +253 -0
  4. package/dist/bin/mash.d.ts +39 -0
  5. package/dist/bin/mash.d.ts.map +1 -0
  6. package/dist/bin/mash.js +281 -0
  7. package/dist/bin/mash.js.map +1 -0
  8. package/dist/src/analysis/analyze.d.ts +97 -0
  9. package/dist/src/analysis/analyze.d.ts.map +1 -0
  10. package/dist/src/analysis/analyze.js +1406 -0
  11. package/dist/src/analysis/analyze.js.map +1 -0
  12. package/dist/src/analysis/fs.d.ts +39 -0
  13. package/dist/src/analysis/fs.d.ts.map +1 -0
  14. package/dist/src/analysis/fs.js +117 -0
  15. package/dist/src/analysis/fs.js.map +1 -0
  16. package/dist/src/analysis/outputs.d.ts +16 -0
  17. package/dist/src/analysis/outputs.d.ts.map +1 -0
  18. package/dist/src/analysis/outputs.js +277 -0
  19. package/dist/src/analysis/outputs.js.map +1 -0
  20. package/dist/src/analysis/value.d.ts +76 -0
  21. package/dist/src/analysis/value.d.ts.map +1 -0
  22. package/dist/src/analysis/value.js +248 -0
  23. package/dist/src/analysis/value.js.map +1 -0
  24. package/dist/src/behaviors/defs/core.d.ts +15 -0
  25. package/dist/src/behaviors/defs/core.d.ts.map +1 -0
  26. package/dist/src/behaviors/defs/core.js +1084 -0
  27. package/dist/src/behaviors/defs/core.js.map +1 -0
  28. package/dist/src/behaviors/defs/devtools.d.ts +9 -0
  29. package/dist/src/behaviors/defs/devtools.d.ts.map +1 -0
  30. package/dist/src/behaviors/defs/devtools.js +432 -0
  31. package/dist/src/behaviors/defs/devtools.js.map +1 -0
  32. package/dist/src/behaviors/defs/macos.d.ts +12 -0
  33. package/dist/src/behaviors/defs/macos.d.ts.map +1 -0
  34. package/dist/src/behaviors/defs/macos.js +454 -0
  35. package/dist/src/behaviors/defs/macos.js.map +1 -0
  36. package/dist/src/behaviors/defs/tools.d.ts +9 -0
  37. package/dist/src/behaviors/defs/tools.d.ts.map +1 -0
  38. package/dist/src/behaviors/defs/tools.js +639 -0
  39. package/dist/src/behaviors/defs/tools.js.map +1 -0
  40. package/dist/src/behaviors/dsl.d.ts +95 -0
  41. package/dist/src/behaviors/dsl.d.ts.map +1 -0
  42. package/dist/src/behaviors/dsl.js +267 -0
  43. package/dist/src/behaviors/dsl.js.map +1 -0
  44. package/dist/src/behaviors/index.d.ts +12 -0
  45. package/dist/src/behaviors/index.d.ts.map +1 -0
  46. package/dist/src/behaviors/index.js +18 -0
  47. package/dist/src/behaviors/index.js.map +1 -0
  48. package/dist/src/behaviors/registry.d.ts +45 -0
  49. package/dist/src/behaviors/registry.d.ts.map +1 -0
  50. package/dist/src/behaviors/registry.js +266 -0
  51. package/dist/src/behaviors/registry.js.map +1 -0
  52. package/dist/src/behaviors/roles.d.ts +29 -0
  53. package/dist/src/behaviors/roles.d.ts.map +1 -0
  54. package/dist/src/behaviors/roles.js +198 -0
  55. package/dist/src/behaviors/roles.js.map +1 -0
  56. package/dist/src/behaviors/types.d.ts +120 -0
  57. package/dist/src/behaviors/types.d.ts.map +1 -0
  58. package/dist/src/behaviors/types.js +12 -0
  59. package/dist/src/behaviors/types.js.map +1 -0
  60. package/dist/src/index.d.ts +27 -0
  61. package/dist/src/index.d.ts.map +1 -0
  62. package/dist/src/index.js +24 -0
  63. package/dist/src/index.js.map +1 -0
  64. package/dist/src/integrations/deepsea.d.ts +121 -0
  65. package/dist/src/integrations/deepsea.d.ts.map +1 -0
  66. package/dist/src/integrations/deepsea.js +199 -0
  67. package/dist/src/integrations/deepsea.js.map +1 -0
  68. package/dist/src/machine.d.ts +139 -0
  69. package/dist/src/machine.d.ts.map +1 -0
  70. package/dist/src/machine.js +400 -0
  71. package/dist/src/machine.js.map +1 -0
  72. package/dist/src/parser/ast.d.ts +369 -0
  73. package/dist/src/parser/ast.d.ts.map +1 -0
  74. package/dist/src/parser/ast.js +17 -0
  75. package/dist/src/parser/ast.js.map +1 -0
  76. package/dist/src/parser/parser.d.ts +48 -0
  77. package/dist/src/parser/parser.d.ts.map +1 -0
  78. package/dist/src/parser/parser.js +1950 -0
  79. package/dist/src/parser/parser.js.map +1 -0
  80. package/dist/src/policy/effects.d.ts +86 -0
  81. package/dist/src/policy/effects.d.ts.map +1 -0
  82. package/dist/src/policy/effects.js +53 -0
  83. package/dist/src/policy/effects.js.map +1 -0
  84. package/dist/src/policy/policy.d.ts +130 -0
  85. package/dist/src/policy/policy.d.ts.map +1 -0
  86. package/dist/src/policy/policy.js +532 -0
  87. package/dist/src/policy/policy.js.map +1 -0
  88. package/dist/src/printer/doc.d.ts +151 -0
  89. package/dist/src/printer/doc.d.ts.map +1 -0
  90. package/dist/src/printer/doc.js +409 -0
  91. package/dist/src/printer/doc.js.map +1 -0
  92. package/dist/src/printer/highlight.d.ts +53 -0
  93. package/dist/src/printer/highlight.d.ts.map +1 -0
  94. package/dist/src/printer/highlight.js +339 -0
  95. package/dist/src/printer/highlight.js.map +1 -0
  96. package/dist/src/printer/html.d.ts +72 -0
  97. package/dist/src/printer/html.d.ts.map +1 -0
  98. package/dist/src/printer/html.js +423 -0
  99. package/dist/src/printer/html.js.map +1 -0
  100. package/dist/src/printer/print.d.ts +63 -0
  101. package/dist/src/printer/print.d.ts.map +1 -0
  102. package/dist/src/printer/print.js +484 -0
  103. package/dist/src/printer/print.js.map +1 -0
  104. package/dist/src/printer/summary.d.ts +50 -0
  105. package/dist/src/printer/summary.d.ts.map +1 -0
  106. package/dist/src/printer/summary.js +621 -0
  107. package/dist/src/printer/summary.js.map +1 -0
  108. package/dist/src/trace/events.d.ts +183 -0
  109. package/dist/src/trace/events.d.ts.map +1 -0
  110. package/dist/src/trace/events.js +9 -0
  111. package/dist/src/trace/events.js.map +1 -0
  112. package/dist/src/trace/progress.d.ts +58 -0
  113. package/dist/src/trace/progress.d.ts.map +1 -0
  114. package/dist/src/trace/progress.js +83 -0
  115. package/dist/src/trace/progress.js.map +1 -0
  116. package/dist/src/vm/arith.d.ts +29 -0
  117. package/dist/src/vm/arith.d.ts.map +1 -0
  118. package/dist/src/vm/arith.js +258 -0
  119. package/dist/src/vm/arith.js.map +1 -0
  120. package/dist/src/vm/builtins.d.ts +31 -0
  121. package/dist/src/vm/builtins.d.ts.map +1 -0
  122. package/dist/src/vm/builtins.js +1773 -0
  123. package/dist/src/vm/builtins.js.map +1 -0
  124. package/dist/src/vm/emulate.d.ts +75 -0
  125. package/dist/src/vm/emulate.d.ts.map +1 -0
  126. package/dist/src/vm/emulate.js +380 -0
  127. package/dist/src/vm/emulate.js.map +1 -0
  128. package/dist/src/vm/expand.d.ts +68 -0
  129. package/dist/src/vm/expand.d.ts.map +1 -0
  130. package/dist/src/vm/expand.js +744 -0
  131. package/dist/src/vm/expand.js.map +1 -0
  132. package/dist/src/vm/external.d.ts +34 -0
  133. package/dist/src/vm/external.d.ts.map +1 -0
  134. package/dist/src/vm/external.js +228 -0
  135. package/dist/src/vm/external.js.map +1 -0
  136. package/dist/src/vm/fifo.d.ts +66 -0
  137. package/dist/src/vm/fifo.d.ts.map +1 -0
  138. package/dist/src/vm/fifo.js +232 -0
  139. package/dist/src/vm/fifo.js.map +1 -0
  140. package/dist/src/vm/interp.d.ts +209 -0
  141. package/dist/src/vm/interp.d.ts.map +1 -0
  142. package/dist/src/vm/interp.js +1641 -0
  143. package/dist/src/vm/interp.js.map +1 -0
  144. package/dist/src/vm/io.d.ts +180 -0
  145. package/dist/src/vm/io.d.ts.map +1 -0
  146. package/dist/src/vm/io.js +502 -0
  147. package/dist/src/vm/io.js.map +1 -0
  148. package/dist/src/vm/pattern.d.ts +46 -0
  149. package/dist/src/vm/pattern.d.ts.map +1 -0
  150. package/dist/src/vm/pattern.js +498 -0
  151. package/dist/src/vm/pattern.js.map +1 -0
  152. package/dist/src/vm/proc.d.ts +94 -0
  153. package/dist/src/vm/proc.d.ts.map +1 -0
  154. package/dist/src/vm/proc.js +130 -0
  155. package/dist/src/vm/proc.js.map +1 -0
  156. package/dist/src/vm/state.d.ts +104 -0
  157. package/dist/src/vm/state.d.ts.map +1 -0
  158. package/dist/src/vm/state.js +233 -0
  159. package/dist/src/vm/state.js.map +1 -0
  160. package/dist/src/vm/test.d.ts +11 -0
  161. package/dist/src/vm/test.d.ts.map +1 -0
  162. package/dist/src/vm/test.js +277 -0
  163. package/dist/src/vm/test.js.map +1 -0
  164. package/package.json +63 -4
  165. package/src/analysis/analyze.ts +1395 -0
  166. package/src/analysis/fs.ts +121 -0
  167. package/src/analysis/outputs.ts +242 -0
  168. package/src/analysis/value.ts +264 -0
  169. package/src/behaviors/defs/core.ts +970 -0
  170. package/src/behaviors/defs/devtools.ts +400 -0
  171. package/src/behaviors/defs/macos.ts +426 -0
  172. package/src/behaviors/defs/tools.ts +596 -0
  173. package/src/behaviors/dsl.ts +293 -0
  174. package/src/behaviors/index.ts +19 -0
  175. package/src/behaviors/registry.ts +261 -0
  176. package/src/behaviors/roles.ts +187 -0
  177. package/src/behaviors/types.ts +127 -0
  178. package/src/index.ts +27 -0
  179. package/src/integrations/deepsea.ts +259 -0
  180. package/src/machine.ts +483 -0
  181. package/src/parser/ast.ts +472 -0
  182. package/src/parser/parser.ts +1826 -0
  183. package/src/policy/effects.ts +102 -0
  184. package/src/policy/policy.ts +578 -0
  185. package/src/printer/doc.ts +454 -0
  186. package/src/printer/highlight.ts +283 -0
  187. package/src/printer/html.ts +441 -0
  188. package/src/printer/print.ts +528 -0
  189. package/src/printer/summary.ts +601 -0
  190. package/src/trace/events.ts +102 -0
  191. package/src/trace/progress.ts +119 -0
  192. package/src/vm/arith.ts +236 -0
  193. package/src/vm/builtins.ts +1590 -0
  194. package/src/vm/emulate.ts +337 -0
  195. package/src/vm/expand.ts +721 -0
  196. package/src/vm/external.ts +265 -0
  197. package/src/vm/fifo.ts +226 -0
  198. package/src/vm/interp.ts +1623 -0
  199. package/src/vm/io.ts +570 -0
  200. package/src/vm/pattern.ts +477 -0
  201. package/src/vm/proc.ts +147 -0
  202. package/src/vm/state.ts +267 -0
  203. package/src/vm/test.ts +253 -0
@@ -0,0 +1,1773 @@
1
+ /**
2
+ * Shell builtins. Each receives a {@link BuiltinContext}: `proc` has the
3
+ * command's redirections applied; `base` is the shell process itself (same
4
+ * state, original fds) for builtins that change fds permanently (`exec`).
5
+ */
6
+ import * as fs from 'node:fs';
7
+ import * as os from 'node:os';
8
+ import * as path from 'node:path';
9
+ import { parse, ParseError } from "../parser/parser.js";
10
+ import { known } from "../analysis/value.js";
11
+ import { shellQuote, varElements } from "./expand.js";
12
+ import { resolveCommand } from "./interp.js";
13
+ import { AbortRun, CommandError, DiscardError, ExitSignal, LoopSignal, ReturnSignal } from "./proc.js";
14
+ import { KNOWN_SHOPTS, newVar, SET_FLAGS, SET_O_NAMES } from "./state.js";
15
+ import { evalTest } from "./test.js";
16
+ export const BUILTINS = new Map();
17
+ const def = (names, fn) => {
18
+ for (const n of names)
19
+ BUILTINS.set(n, fn);
20
+ };
21
+ // ---------------------------------------------------------------------------
22
+ // Escapes
23
+ // ---------------------------------------------------------------------------
24
+ /** Interpret backslash escapes (echo -e, printf %b). Returns [text, stop] where stop means \c was seen. */
25
+ export function interpretEscapes(s, printfStyle = false) {
26
+ let out = '';
27
+ for (let i = 0; i < s.length; i++) {
28
+ const c = s[i];
29
+ if (c !== '\\' || i + 1 >= s.length) {
30
+ out += c;
31
+ continue;
32
+ }
33
+ const e = s[++i];
34
+ switch (e) {
35
+ case 'a':
36
+ out += '\x07';
37
+ break;
38
+ case 'b':
39
+ out += '\b';
40
+ break;
41
+ case 'c': return [out, true];
42
+ case 'e':
43
+ case 'E':
44
+ out += '\x1b';
45
+ break;
46
+ case 'f':
47
+ out += '\f';
48
+ break;
49
+ case 'n':
50
+ out += '\n';
51
+ break;
52
+ case 'r':
53
+ out += '\r';
54
+ break;
55
+ case 't':
56
+ out += '\t';
57
+ break;
58
+ case 'v':
59
+ out += '\v';
60
+ break;
61
+ case '\\':
62
+ out += '\\';
63
+ break;
64
+ case '"':
65
+ out += printfStyle ? '"' : '\\"';
66
+ break;
67
+ case "'":
68
+ out += printfStyle ? "'" : "\\'";
69
+ break;
70
+ case 'x': {
71
+ const m = /^[0-9a-fA-F]{1,2}/.exec(s.slice(i + 1));
72
+ if (!m) {
73
+ out += '\\x';
74
+ break;
75
+ }
76
+ out += String.fromCharCode(parseInt(m[0], 16));
77
+ i += m[0].length;
78
+ break;
79
+ }
80
+ case 'u':
81
+ case 'U': {
82
+ const m = new RegExp(`^[0-9a-fA-F]{1,${e === 'u' ? 4 : 8}}`).exec(s.slice(i + 1));
83
+ if (!m) {
84
+ out += '\\' + e;
85
+ break;
86
+ }
87
+ out += String.fromCodePoint(parseInt(m[0], 16));
88
+ i += m[0].length;
89
+ break;
90
+ }
91
+ case '0': {
92
+ const m = /^[0-7]{0,3}/.exec(s.slice(i + 1));
93
+ out += String.fromCharCode(parseInt(m[0] || '0', 8) & 0xff);
94
+ i += m[0].length;
95
+ break;
96
+ }
97
+ default:
98
+ if (printfStyle && /[1-7]/.test(e)) {
99
+ const m = /^[0-7]{0,2}/.exec(s.slice(i + 1));
100
+ out += String.fromCharCode(parseInt(e + m[0], 8) & 0xff);
101
+ i += m[0].length;
102
+ }
103
+ else
104
+ out += '\\' + e;
105
+ }
106
+ }
107
+ return [out, false];
108
+ }
109
+ // ---------------------------------------------------------------------------
110
+ // Trivial
111
+ // ---------------------------------------------------------------------------
112
+ def([':', 'true'], async () => 0);
113
+ def(['false'], async () => 1);
114
+ def(['echo'], async (ctx) => {
115
+ const args = ctx.argv.slice(1);
116
+ let newline = true;
117
+ let escapes = ctx.proc.state.shopts.has('xpg_echo');
118
+ while (args.length > 0 && /^-[neE]+$/.test(args[0])) {
119
+ for (const f of args[0].slice(1)) {
120
+ if (f === 'n')
121
+ newline = false;
122
+ else if (f === 'e')
123
+ escapes = true;
124
+ else
125
+ escapes = false;
126
+ }
127
+ args.shift();
128
+ }
129
+ let text = args.join(' ');
130
+ if (escapes) {
131
+ const [t, stop] = interpretEscapes(text);
132
+ if (stop) {
133
+ await ctx.out(t);
134
+ return 0;
135
+ }
136
+ text = t;
137
+ }
138
+ await ctx.out(newline ? text + '\n' : text);
139
+ return 0;
140
+ });
141
+ // ---------------------------------------------------------------------------
142
+ // printf
143
+ // ---------------------------------------------------------------------------
144
+ function parseNumArg(arg, ctx, onError) {
145
+ if (arg === undefined)
146
+ return 0n;
147
+ if (arg === '') {
148
+ // bash 5: an empty numeric argument is an invalid number (value 0, status 1); 3.2 accepted it
149
+ ctx.error(': invalid number');
150
+ onError();
151
+ return 0n;
152
+ }
153
+ if (/^['"]/.test(arg))
154
+ return BigInt(arg.length > 1 ? arg.codePointAt(1) : 0);
155
+ const t = arg.trim();
156
+ try {
157
+ if (/^[+-]?0[xX][0-9a-fA-F]+$/.test(t))
158
+ return BigInt(t.replace(/^([+-]?)0[xX]/, '$10x').replace(/^-0x(.*)$/, '-0x$1').startsWith('-') ? -BigInt(t.replace(/^-/, '')) : BigInt(t.replace(/^\+/, '')));
159
+ if (/^[+-]?0[0-7]+$/.test(t))
160
+ return (t.startsWith('-') ? -1n : 1n) * BigInt('0o' + t.replace(/^[+-]?0/, ''));
161
+ if (/^[+-]?\d+$/.test(t))
162
+ return BigInt(t);
163
+ }
164
+ catch {
165
+ // fall through
166
+ }
167
+ const m = /^([+-]?\d+)/.exec(t);
168
+ ctx.error(`${arg}: invalid number`);
169
+ onError();
170
+ return m ? BigInt(m[1]) : 0n;
171
+ }
172
+ export function formatPrintf(fmt, args, ctx) {
173
+ let out = '';
174
+ let failed = false;
175
+ let ai = 0;
176
+ const next = () => args[ai++];
177
+ const fail = () => {
178
+ failed = true;
179
+ };
180
+ let first = true;
181
+ while (first || ai < args.length) {
182
+ first = false;
183
+ const startAi = ai;
184
+ for (let i = 0; i < fmt.length; i++) {
185
+ const c = fmt[i];
186
+ if (c === '\\') {
187
+ // escapes in the format
188
+ let j = i + 1;
189
+ const e = fmt[j];
190
+ if (e === undefined) {
191
+ out += '\\';
192
+ continue;
193
+ }
194
+ let seq = '\\' + e;
195
+ if (/[0-7]/.test(e)) {
196
+ const m = /^[0-7]{1,3}/.exec(fmt.slice(j));
197
+ seq = '\\0' + m[0];
198
+ j += m[0].length - 1;
199
+ }
200
+ else if (e === 'x' || e === 'u' || e === 'U') {
201
+ const m = new RegExp(`^[0-9a-fA-F]{1,${e === 'x' ? 2 : e === 'u' ? 4 : 8}}`).exec(fmt.slice(j + 1));
202
+ if (m) {
203
+ seq += m[0];
204
+ j += m[0].length;
205
+ }
206
+ }
207
+ if (seq === '\\c') {
208
+ out += '\\c';
209
+ i = j;
210
+ continue;
211
+ }
212
+ const [t] = interpretEscapes(seq, true);
213
+ out += t;
214
+ i = j;
215
+ continue;
216
+ }
217
+ if (c !== '%') {
218
+ out += c;
219
+ continue;
220
+ }
221
+ if (fmt[i + 1] === '%') {
222
+ out += '%';
223
+ i++;
224
+ continue;
225
+ }
226
+ const m = /^%([-+ #0']*)(\*|\d+)?(?:\.(\*|\d*))?(?:hh|h|ll|l|L|q|j|z|t)?([diouxXfFeEgGcsbqaA])/.exec(fmt.slice(i));
227
+ if (!m) {
228
+ out += c;
229
+ continue;
230
+ }
231
+ i += m[0].length - 1;
232
+ const flags = m[1];
233
+ let width = m[2] === '*' ? Number(parseNumArg(next(), ctx, fail)) : m[2] ? Number(m[2]) : undefined;
234
+ let leftAlign = flags.includes('-');
235
+ if (width !== undefined && width < 0) {
236
+ leftAlign = true;
237
+ width = -width;
238
+ }
239
+ const precision = m[3] === undefined ? undefined : m[3] === '*' ? Number(parseNumArg(next(), ctx, fail)) : Number(m[3] || '0');
240
+ const conv = m[4];
241
+ const isFloat = 'fFeEgGaA'.includes(conv);
242
+ const pad = (s, numeric) => {
243
+ if (width === undefined || s.length >= width)
244
+ return s;
245
+ if (leftAlign)
246
+ return s.padEnd(width);
247
+ if (numeric && flags.includes('0') && (precision === undefined || isFloat)) {
248
+ const sign = /^[+ -]/.test(s) ? s[0] : '';
249
+ return sign + s.slice(sign.length).padStart(width - sign.length, '0');
250
+ }
251
+ return s.padStart(width);
252
+ };
253
+ switch (conv) {
254
+ case 's': {
255
+ let s = next() ?? '';
256
+ if (precision !== undefined)
257
+ s = s.slice(0, precision);
258
+ out += pad(s, false);
259
+ break;
260
+ }
261
+ case 'b': {
262
+ const [t, stop] = interpretEscapes(next() ?? '', true);
263
+ let s = t;
264
+ if (precision !== undefined)
265
+ s = s.slice(0, precision);
266
+ out += pad(s, false);
267
+ if (stop)
268
+ return { text: out, failed };
269
+ break;
270
+ }
271
+ case 'q':
272
+ out += pad(printfQuote(next() ?? ''), false);
273
+ break;
274
+ case 'c': {
275
+ // bash 5 prints the first byte, so an empty argument gives a NUL (3.2: nothing)
276
+ const a = next();
277
+ out += pad(a === '' ? '\0' : (a ?? '').slice(0, 1), false);
278
+ break;
279
+ }
280
+ case 'd':
281
+ case 'i': {
282
+ const n = parseNumArg(next(), ctx, fail);
283
+ let s = (n < 0n ? -n : n).toString();
284
+ if (precision !== undefined)
285
+ s = s.padStart(precision, '0');
286
+ s = (n < 0n ? '-' : flags.includes('+') ? '+' : flags.includes(' ') ? ' ' : '') + s;
287
+ out += pad(s, true);
288
+ break;
289
+ }
290
+ case 'u':
291
+ case 'o':
292
+ case 'x':
293
+ case 'X': {
294
+ let n = parseNumArg(next(), ctx, fail);
295
+ if (n < 0n)
296
+ n = BigInt.asUintN(64, n);
297
+ let s = conv === 'o' ? n.toString(8) : conv === 'u' ? n.toString() : n.toString(16);
298
+ if (conv === 'X')
299
+ s = s.toUpperCase();
300
+ if (precision !== undefined)
301
+ s = s.padStart(precision, '0');
302
+ if (flags.includes('#') && n !== 0n)
303
+ s = (conv === 'o' ? '0' : conv === 'x' ? '0x' : conv === 'X' ? '0X' : '') + s;
304
+ out += pad(s, true);
305
+ break;
306
+ }
307
+ default: {
308
+ // floating point
309
+ const raw = next();
310
+ let x = raw === undefined || raw === '' ? 0 : Number(raw);
311
+ if (Number.isNaN(x)) {
312
+ ctx.error(`${raw}: invalid number`);
313
+ fail();
314
+ x = 0;
315
+ }
316
+ const p = precision ?? 6;
317
+ let s;
318
+ switch (conv) {
319
+ case 'f':
320
+ case 'F':
321
+ s = toFixedHalfEven(x, p);
322
+ break;
323
+ case 'e':
324
+ case 'E':
325
+ s = x.toExponential(p).replace(/e([+-])(\d)$/, 'e$10$2');
326
+ break;
327
+ case 'g':
328
+ case 'G': {
329
+ const pp = p === 0 ? 1 : p;
330
+ const exp = x === 0 ? 0 : Math.floor(Math.log10(Math.abs(x)));
331
+ if (exp < -4 || exp >= pp)
332
+ s = x.toExponential(pp - 1).replace(/\.?0+e/, 'e').replace(/e([+-])(\d)$/, 'e$10$2');
333
+ else
334
+ s = String(Number(x.toPrecision(pp)));
335
+ break;
336
+ }
337
+ default: s = x.toString(16);
338
+ }
339
+ if (conv === 'E' || conv === 'G' || conv === 'F')
340
+ s = s.toUpperCase();
341
+ if (x >= 0 && flags.includes('+'))
342
+ s = '+' + s;
343
+ else if (x >= 0 && flags.includes(' '))
344
+ s = ' ' + s;
345
+ out += pad(s, true);
346
+ }
347
+ }
348
+ }
349
+ if (ai === startAi)
350
+ break; // format consumed no arguments
351
+ }
352
+ return { text: out, failed };
353
+ }
354
+ /** `printf %q`: backslash-escape shell metacharacters (bash style). */
355
+ function printfQuote(s) {
356
+ if (s === '')
357
+ return "''";
358
+ if (/[\x00-\x1f\x7f]/.test(s))
359
+ return shellQuote(s);
360
+ return s.replace(/[^A-Za-z0-9_@%+=:,./-]/g, (c) => '\\' + c);
361
+ }
362
+ /** C printf `%.Nf`: round the exact binary value, ties to even. */
363
+ export function toFixedHalfEven(x, digits) {
364
+ if (!Number.isFinite(x))
365
+ return String(x);
366
+ const neg = x < 0 || Object.is(x, -0);
367
+ // exact decimal expansion of the double
368
+ const [mant, exp] = (() => {
369
+ const buf = new DataView(new ArrayBuffer(8));
370
+ buf.setFloat64(0, Math.abs(x));
371
+ const bits = buf.getBigUint64(0);
372
+ const e = Number((bits >> 52n) & 0x7ffn);
373
+ const f = bits & ((1n << 52n) - 1n);
374
+ return e === 0 ? [f, -1074] : [f | (1n << 52n), e - 1075];
375
+ })();
376
+ // value = mant * 2^exp; scaled = value * 10^digits as a rational num/den
377
+ let num = mant * 10n ** BigInt(digits);
378
+ let den = 1n;
379
+ if (exp >= 0)
380
+ num <<= BigInt(exp);
381
+ else
382
+ den <<= BigInt(-exp);
383
+ let q = num / den;
384
+ const r = num % den;
385
+ if (r * 2n > den || (r * 2n === den && (q & 1n) === 1n))
386
+ q += 1n;
387
+ let s = q.toString().padStart(digits + 1, '0');
388
+ if (digits > 0)
389
+ s = s.slice(0, -digits) + '.' + s.slice(-digits);
390
+ return (neg && q !== 0n ? '-' : neg && x !== 0 ? '-' : '') + s;
391
+ }
392
+ def(['printf'], async (ctx) => {
393
+ const args = ctx.argv.slice(1);
394
+ let varName = null;
395
+ if (args[0] === '-v') {
396
+ varName = args[1] ?? null;
397
+ args.splice(0, 2);
398
+ }
399
+ if (args[0] === '--')
400
+ args.shift();
401
+ if (args.length === 0) {
402
+ ctx.error('usage: printf [-v var] format [arguments]');
403
+ return 2;
404
+ }
405
+ const { text, failed } = formatPrintf(args[0], args.slice(1), ctx);
406
+ const element = varName === null ? null : /^([A-Za-z_]\w*)\[(.+)\]$/.exec(varName);
407
+ if (element)
408
+ await ctx.interp.assignElement(ctx.proc, element[1], element[2], text);
409
+ else if (varName !== null)
410
+ ctx.interp.assignScalar(ctx.proc, varName, text);
411
+ else
412
+ await ctx.out(text);
413
+ return failed ? 1 : 0;
414
+ });
415
+ // ---------------------------------------------------------------------------
416
+ // Directories
417
+ // ---------------------------------------------------------------------------
418
+ function changeDir(ctx, target, physical) {
419
+ const st = ctx.proc.state;
420
+ let abs = path.resolve(st.cwd, target);
421
+ let stat;
422
+ try {
423
+ stat = fs.statSync(abs);
424
+ }
425
+ catch {
426
+ ctx.error(`${target}: No such file or directory`);
427
+ return 1;
428
+ }
429
+ if (!stat.isDirectory()) {
430
+ ctx.error(`${target}: Not a directory`);
431
+ return 1;
432
+ }
433
+ try {
434
+ fs.accessSync(abs, fs.constants.X_OK);
435
+ }
436
+ catch {
437
+ ctx.error(`${target}: Permission denied`);
438
+ return 1;
439
+ }
440
+ if (physical)
441
+ abs = fs.realpathSync(abs);
442
+ const old = st.cwd;
443
+ st.cwd = abs;
444
+ ctx.interp.assignScalar(ctx.proc, 'OLDPWD', old);
445
+ ctx.interp.assignScalar(ctx.proc, 'PWD', abs);
446
+ return 0;
447
+ }
448
+ def(['cd'], async (ctx) => {
449
+ const args = ctx.argv.slice(1);
450
+ let physical = false;
451
+ while (args[0] === '-P' || args[0] === '-L' || args[0] === '--') {
452
+ if (args[0] === '-P')
453
+ physical = true;
454
+ if (args.shift() === '--')
455
+ break;
456
+ }
457
+ const st = ctx.proc.state;
458
+ let target = args[0];
459
+ if (target === undefined) {
460
+ target = st.getString('HOME') ?? os.homedir();
461
+ }
462
+ else if (target === '-') {
463
+ const old = st.getString('OLDPWD');
464
+ if (!old) {
465
+ ctx.error('OLDPWD not set');
466
+ return 1;
467
+ }
468
+ target = old;
469
+ const r = changeDir(ctx, target, physical);
470
+ if (r === 0)
471
+ await ctx.out(st.cwd + '\n');
472
+ return r;
473
+ }
474
+ return changeDir(ctx, target, physical);
475
+ });
476
+ def(['pwd'], async (ctx) => {
477
+ const physical = ctx.argv.includes('-P');
478
+ await ctx.out((physical ? fs.realpathSync(ctx.proc.state.cwd) : ctx.proc.state.cwd) + '\n');
479
+ return 0;
480
+ });
481
+ def(['pushd'], async (ctx) => {
482
+ const st = ctx.proc.state;
483
+ const dir = ctx.argv[1];
484
+ if (dir === undefined) {
485
+ const top = st.dirStack.shift();
486
+ if (!top) {
487
+ ctx.error('no other directory');
488
+ return 1;
489
+ }
490
+ const cur = st.cwd;
491
+ const r = changeDir(ctx, top, false);
492
+ if (r === 0)
493
+ st.dirStack.unshift(cur);
494
+ else
495
+ st.dirStack.unshift(top);
496
+ }
497
+ else {
498
+ const cur = st.cwd;
499
+ const r = changeDir(ctx, dir, false);
500
+ if (r !== 0)
501
+ return r;
502
+ st.dirStack.unshift(cur);
503
+ }
504
+ await ctx.out([st.cwd, ...st.dirStack].join(' ') + '\n');
505
+ return 0;
506
+ });
507
+ def(['popd'], async (ctx) => {
508
+ const st = ctx.proc.state;
509
+ const top = st.dirStack.shift();
510
+ if (top === undefined) {
511
+ ctx.error('directory stack empty');
512
+ return 1;
513
+ }
514
+ const r = changeDir(ctx, top, false);
515
+ if (r !== 0)
516
+ return r;
517
+ await ctx.out([st.cwd, ...st.dirStack].join(' ') + '\n');
518
+ return 0;
519
+ });
520
+ def(['dirs'], async (ctx) => {
521
+ const st = ctx.proc.state;
522
+ if (ctx.argv.includes('-c')) {
523
+ st.dirStack = [];
524
+ return 0;
525
+ }
526
+ await ctx.out([st.cwd, ...st.dirStack].join(' ') + '\n');
527
+ return 0;
528
+ });
529
+ // ---------------------------------------------------------------------------
530
+ // Variables
531
+ // ---------------------------------------------------------------------------
532
+ function declLine(name, v) {
533
+ let flags = '';
534
+ if (v.value?.kind === 'indexed' || v.declaredKind === 'indexed')
535
+ flags += 'a';
536
+ if (v.value?.kind === 'assoc' || v.declaredKind === 'assoc')
537
+ flags += 'A';
538
+ if (v.integer)
539
+ flags += 'i';
540
+ if (v.lower)
541
+ flags += 'l';
542
+ if (v.readonly)
543
+ flags += 'r';
544
+ if (v.upper)
545
+ flags += 'u';
546
+ if (v.exported)
547
+ flags += 'x';
548
+ const f = flags === '' ? '--' : '-' + flags;
549
+ if (v.value === null)
550
+ return `declare ${f} ${name}`;
551
+ if (v.value.kind === 'string')
552
+ return `declare ${f} ${name}=${dq(v.value.value)}`;
553
+ if (v.value.kind === 'indexed') {
554
+ const items = [...v.value.values.entries()].sort((a, b) => a[0] - b[0]).map(([k, x]) => `[${k}]=${dq(x)}`);
555
+ return `declare ${f} ${name}=(${items.join(' ')})`;
556
+ }
557
+ const items = [...v.value.values.entries()].map(([k, x]) => `[${shellQuote(k)}]=${dq(x)}`);
558
+ return `declare ${f} ${name}=(${items.join(' ')} )`;
559
+ }
560
+ function dq(s) {
561
+ return '"' + s.replace(/(["\\$`])/g, '\\$1') + '"';
562
+ }
563
+ function isName(s) {
564
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(s);
565
+ }
566
+ async function declare(ctx, variant) {
567
+ const st = ctx.proc.state;
568
+ const args = ctx.argv.slice(1);
569
+ const on = new Set();
570
+ const off = new Set();
571
+ let i = 0;
572
+ for (; i < args.length; i++) {
573
+ const a = args[i];
574
+ if (ctx.assignArg(a))
575
+ break;
576
+ if (a === '--') {
577
+ i++;
578
+ break;
579
+ }
580
+ if (/^[-+][a-zA-Z]+$/.test(a)) {
581
+ for (const f of a.slice(1))
582
+ (a[0] === '-' ? on : off).add(f);
583
+ }
584
+ else
585
+ break;
586
+ }
587
+ const names = args.slice(i);
588
+ // expand every assignment value before assigning any (bash semantics)
589
+ const frozen = new Map();
590
+ for (const arg of names) {
591
+ const a = ctx.assignArg(arg);
592
+ if (a)
593
+ frozen.set(arg, await ctx.interp.freezeAssign(a, ctx.proc));
594
+ }
595
+ if (variant === 'local' && st.locals.length === 0) {
596
+ ctx.error('can only be used in a function');
597
+ return 1;
598
+ }
599
+ const inFunction = st.locals.length > 0;
600
+ const local = variant === 'local' || ((variant === 'declare') && inFunction && !on.has('g'));
601
+ if (variant === 'export')
602
+ on.add('x');
603
+ if (variant === 'readonly')
604
+ on.add('r');
605
+ if ((on.has('f') || off.has('f')) && (variant === 'export' || on.has('x') || off.has('x'))) {
606
+ let status = 0;
607
+ for (const n of names) {
608
+ const f = st.functions.get(n);
609
+ if (!f) {
610
+ ctx.error(`${n}: not a function`);
611
+ status = 1;
612
+ continue;
613
+ }
614
+ st.functions.set(n, { ...f, exported: !off.has('f') && !off.has('x') });
615
+ }
616
+ return status;
617
+ }
618
+ if (on.has('f') || on.has('F')) {
619
+ for (const n of names.length > 0 ? names : [...st.functions.keys()].sort()) {
620
+ const f = st.functions.get(n);
621
+ if (!f)
622
+ return 1;
623
+ await ctx.out(on.has('F') ? (names.length > 0 ? `${n}\n` : `declare -f ${n}\n`) : `${n} () ${ctx.interp.rt.text(f.def.body)}\n`);
624
+ }
625
+ return 0;
626
+ }
627
+ if (names.length === 0 || (on.has('p') && names.length === 0)) {
628
+ for (const n of st.visibleNames()) {
629
+ const v = st.lookup(n);
630
+ if (variant === 'export' && !v.exported)
631
+ continue;
632
+ if (variant === 'readonly' && !v.readonly)
633
+ continue;
634
+ await ctx.out(variant === 'export' ? `declare -x ${n}${v.value?.kind === 'string' ? '=' + dq(v.value.value) : ''}\n` : declLine(n, v) + '\n');
635
+ }
636
+ return 0;
637
+ }
638
+ if (on.has('p')) {
639
+ let status = 0;
640
+ for (const n of names) {
641
+ const v = st.lookup(n);
642
+ if (!v) {
643
+ ctx.error(`${n}: not found`);
644
+ status = 1;
645
+ continue;
646
+ }
647
+ await ctx.out(declLine(n, v) + '\n');
648
+ }
649
+ return status;
650
+ }
651
+ const kind = on.has('A') ? 'assoc' : on.has('a') ? 'indexed' : undefined;
652
+ let status = 0;
653
+ const applyAttrs = (v) => {
654
+ if (on.has('x'))
655
+ v.exported = true;
656
+ if (off.has('x'))
657
+ v.exported = false;
658
+ if (on.has('i'))
659
+ v.integer = true;
660
+ if (off.has('i'))
661
+ v.integer = false;
662
+ if (on.has('l')) {
663
+ v.lower = true;
664
+ v.upper = false;
665
+ }
666
+ if (on.has('u')) {
667
+ v.upper = true;
668
+ v.lower = false;
669
+ }
670
+ };
671
+ for (const arg of names) {
672
+ const assign = frozen.get(arg) ?? null;
673
+ if (assign) {
674
+ const v = local ? st.declareLocal(assign.name) : st.ensure(assign.name);
675
+ if (v.readonly) {
676
+ ctx.error(`${assign.name}: readonly variable`);
677
+ status = 1;
678
+ continue;
679
+ }
680
+ applyAttrs(v);
681
+ if (kind && v.value === null)
682
+ v.declaredKind = kind;
683
+ await ctx.interp.performAssign(assign, ctx.proc, { local, declareKind: kind });
684
+ if (on.has('r'))
685
+ v.readonly = true;
686
+ continue;
687
+ }
688
+ const eq = arg.indexOf('=');
689
+ const name = eq === -1 ? arg : arg.slice(0, eq).replace(/\+$/, '');
690
+ if (!isName(name.replace(/\[.*\]$/, ''))) {
691
+ ctx.error(`\`${arg}': not a valid identifier`);
692
+ status = 1;
693
+ continue;
694
+ }
695
+ const v = local ? st.declareLocal(name) : (variant === 'declare' && on.has('g') ? globalVar(st, name) : st.ensure(name));
696
+ if (eq !== -1 && v.readonly) {
697
+ ctx.error(`${name}: readonly variable`);
698
+ status = 1;
699
+ continue;
700
+ }
701
+ applyAttrs(v);
702
+ if (kind) {
703
+ if (v.value === null)
704
+ v.declaredKind = kind;
705
+ else if (kind === 'indexed' && v.value.kind === 'string')
706
+ v.value = { kind: 'indexed', values: new Map([[0, v.value.value]]) };
707
+ else if (kind === 'assoc' && v.value.kind !== 'assoc')
708
+ v.value = { kind: 'assoc', values: new Map() };
709
+ }
710
+ if (eq !== -1) {
711
+ const append = arg[eq - 1] === '+';
712
+ const value = arg.slice(eq + 1);
713
+ const old = append ? st.getString(name) ?? '' : '';
714
+ ctx.interp.assignScalar(ctx.proc, name, old + value, { local });
715
+ }
716
+ if (on.has('r'))
717
+ v.readonly = true;
718
+ if (off.has('r') && v.readonly) {
719
+ ctx.error(`${name}: readonly variable`);
720
+ status = 1;
721
+ }
722
+ }
723
+ return status;
724
+ }
725
+ function globalVar(st, name) {
726
+ let v = st.globals.get(name);
727
+ if (!v) {
728
+ v = newVar(null);
729
+ st.globals.set(name, v);
730
+ }
731
+ return v;
732
+ }
733
+ def(['declare', 'typeset'], (ctx) => declare(ctx, 'declare'));
734
+ def(['local'], (ctx) => declare(ctx, 'local'));
735
+ def(['export'], async (ctx) => {
736
+ if (ctx.argv[1] === '-n') {
737
+ for (const n of ctx.argv.slice(2)) {
738
+ const v = ctx.proc.state.lookup(n);
739
+ if (v)
740
+ v.exported = false;
741
+ }
742
+ return 0;
743
+ }
744
+ return declare(ctx, 'export');
745
+ });
746
+ def(['readonly'], (ctx) => declare(ctx, 'readonly'));
747
+ def(['unset'], async (ctx) => {
748
+ const st = ctx.proc.state;
749
+ let mode = 'auto';
750
+ let status = 0;
751
+ for (const a of ctx.argv.slice(1)) {
752
+ if (a === '-v') {
753
+ mode = 'v';
754
+ continue;
755
+ }
756
+ if (a === '-f') {
757
+ mode = 'f';
758
+ continue;
759
+ }
760
+ if (a === '-n')
761
+ continue;
762
+ if (mode === 'f') {
763
+ st.functions.delete(a);
764
+ continue;
765
+ }
766
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)\[(.*)\]$/.exec(a);
767
+ if (m && (m[2] === '@' || m[2] === '*')) {
768
+ st.unset(m[1]);
769
+ continue;
770
+ }
771
+ if (m) {
772
+ const v = st.lookup(m[1]);
773
+ if (v?.value?.kind === 'indexed') {
774
+ const idx = Number(await ctx.interp.arithText(m[2], ctx.proc));
775
+ v.value.values.delete(idx);
776
+ }
777
+ else if (v?.value?.kind === 'assoc')
778
+ v.value.values.delete(m[2]);
779
+ continue;
780
+ }
781
+ if (!isName(a)) {
782
+ ctx.error(`\`${a}': not a valid identifier`);
783
+ status = 1;
784
+ continue;
785
+ }
786
+ if (st.lookup(a)) {
787
+ if (!st.unset(a)) {
788
+ ctx.error(`${a}: cannot unset: readonly variable`);
789
+ status = 1;
790
+ }
791
+ }
792
+ else if (mode === 'auto')
793
+ st.functions.delete(a);
794
+ }
795
+ return status;
796
+ });
797
+ def(['set'], async (ctx) => {
798
+ const st = ctx.proc.state;
799
+ const args = ctx.argv.slice(1);
800
+ if (args.length === 0) {
801
+ for (const n of st.visibleNames()) {
802
+ const v = st.lookup(n);
803
+ if (v.value?.kind === 'string')
804
+ await ctx.out(`${n}=${shellQuote(v.value.value)}\n`);
805
+ else if (v.value)
806
+ await ctx.out(`${n}=(${varElements(v).map(shellQuote).join(' ')})\n`);
807
+ }
808
+ return 0;
809
+ }
810
+ let i = 0;
811
+ for (; i < args.length; i++) {
812
+ const a = args[i];
813
+ if (a === '--') {
814
+ st.positional = args.slice(i + 1);
815
+ return 0;
816
+ }
817
+ if (a === '-') {
818
+ st.options.xtrace = false;
819
+ st.options.verbose = false;
820
+ st.positional = args.slice(i + 1);
821
+ return 0;
822
+ }
823
+ if (!/^[-+]/.test(a))
824
+ break;
825
+ const enable = a[0] === '-';
826
+ for (let j = 1; j < a.length; j++) {
827
+ const f = a[j];
828
+ if (f === 'o') {
829
+ const name = args[i + 1];
830
+ if (name === undefined || /^[-+]/.test(name)) {
831
+ for (const [n, opt] of Object.entries(SET_O_NAMES))
832
+ await ctx.out(`${n.padEnd(15)}\t${st.options[opt] ? 'on' : 'off'}\n`);
833
+ continue;
834
+ }
835
+ i++;
836
+ const opt = SET_O_NAMES[name];
837
+ if (!opt) {
838
+ if (['posix', 'emacs', 'vi', 'monitor', 'notify', 'hashall', 'braceexpand', 'histexpand', 'history', 'ignoreeof', 'interactive-comments', 'keyword', 'onecmd', 'physical', 'privileged', 'errtrace', 'functrace'].includes(name))
839
+ continue;
840
+ ctx.error(`${name}: invalid option name`);
841
+ return 2;
842
+ }
843
+ st.options[opt] = enable;
844
+ continue;
845
+ }
846
+ const opt = SET_FLAGS[f];
847
+ if (opt)
848
+ st.options[opt] = enable;
849
+ else if (!'hBmbHPTkt'.includes(f)) {
850
+ ctx.error(`${a[0]}${f}: invalid option`);
851
+ return 2;
852
+ }
853
+ }
854
+ }
855
+ if (i < args.length)
856
+ st.positional = args.slice(i);
857
+ return 0;
858
+ });
859
+ def(['shopt'], async (ctx) => {
860
+ const st = ctx.proc.state;
861
+ const args = ctx.argv.slice(1);
862
+ let mode = 'print';
863
+ let quiet = false;
864
+ let printMode = false;
865
+ const names = [];
866
+ for (const a of args) {
867
+ if (a === '-s')
868
+ mode = 's';
869
+ else if (a === '-u')
870
+ mode = 'u';
871
+ else if (a === '-q')
872
+ quiet = true;
873
+ else if (a === '-p')
874
+ printMode = true;
875
+ else if (a === '-o')
876
+ continue;
877
+ else
878
+ names.push(a);
879
+ }
880
+ let status = 0;
881
+ for (const n of names) {
882
+ if (!KNOWN_SHOPTS.includes(n)) {
883
+ ctx.error(`${n}: invalid shell option name`);
884
+ status = 1;
885
+ }
886
+ }
887
+ if (status !== 0)
888
+ return status;
889
+ if (mode === 's')
890
+ for (const n of names)
891
+ st.shopts.add(n);
892
+ else if (mode === 'u')
893
+ for (const n of names)
894
+ st.shopts.delete(n);
895
+ else {
896
+ const list = names.length > 0 ? names : [...KNOWN_SHOPTS];
897
+ for (const n of list) {
898
+ const on = st.shopts.has(n);
899
+ if (!on)
900
+ status = 1;
901
+ if (!quiet)
902
+ await ctx.out(printMode ? `shopt ${on ? '-s' : '-u'} ${n}\n` : `${n.padEnd(20)}\t${on ? 'on' : 'off'}\n`); // bash 5 width (3.2: 15)
903
+ }
904
+ }
905
+ return status;
906
+ });
907
+ def(['shift'], async (ctx) => {
908
+ const n = ctx.argv[1] === undefined ? 1 : Number(ctx.argv[1]);
909
+ const st = ctx.proc.state;
910
+ if (!Number.isInteger(n) || n < 0) {
911
+ ctx.error(`${ctx.argv[1]}: numeric argument required`);
912
+ return 1;
913
+ }
914
+ if (n > st.positional.length)
915
+ return 1;
916
+ st.positional = st.positional.slice(n);
917
+ return 0;
918
+ });
919
+ def(['let'], async (ctx) => {
920
+ if (ctx.argv.length < 2) {
921
+ ctx.error('expression expected');
922
+ return 1;
923
+ }
924
+ let last = 0n;
925
+ for (const e of ctx.argv.slice(1))
926
+ last = await ctx.interp.arithText(e, ctx.proc);
927
+ return last !== 0n ? 0 : 1;
928
+ });
929
+ // ---------------------------------------------------------------------------
930
+ // read / mapfile
931
+ // ---------------------------------------------------------------------------
932
+ def(['read'], async (ctx) => {
933
+ const st = ctx.proc.state;
934
+ const args = ctx.argv.slice(1);
935
+ let raw = false;
936
+ let arrayName = null;
937
+ let delim = 10;
938
+ let nchars = null;
939
+ let exactChars = false;
940
+ let fd = 0;
941
+ let timeout = null;
942
+ let prompt = null;
943
+ let i = 0;
944
+ for (; i < args.length; i++) {
945
+ const a = args[i];
946
+ if (!a.startsWith('-') || a === '-')
947
+ break;
948
+ if (a === '--') {
949
+ i++;
950
+ break;
951
+ }
952
+ for (let j = 1; j < a.length; j++) {
953
+ const f = a[j];
954
+ const takeArg = () => {
955
+ const rest = a.slice(j + 1);
956
+ j = a.length;
957
+ if (rest !== '')
958
+ return rest;
959
+ return args[++i] ?? '';
960
+ };
961
+ switch (f) {
962
+ case 'r':
963
+ raw = true;
964
+ break;
965
+ case 's':
966
+ case 'e': break;
967
+ case 'a':
968
+ arrayName = takeArg();
969
+ break;
970
+ case 'd': {
971
+ const d = takeArg();
972
+ delim = d === '' ? 0 : d.charCodeAt(0);
973
+ break;
974
+ }
975
+ case 'n':
976
+ nchars = Number(takeArg());
977
+ break;
978
+ case 'N':
979
+ nchars = Number(takeArg());
980
+ exactChars = true;
981
+ break;
982
+ case 'u':
983
+ fd = Number(takeArg());
984
+ break;
985
+ case 't':
986
+ timeout = Number(takeArg());
987
+ break;
988
+ case 'p':
989
+ prompt = takeArg();
990
+ break;
991
+ case 'i':
992
+ takeArg();
993
+ break;
994
+ default:
995
+ ctx.error(`-${f}: invalid option`);
996
+ return 2;
997
+ }
998
+ }
999
+ }
1000
+ const names = args.slice(i);
1001
+ const input = ctx.proc.fds.get(fd);
1002
+ if (!input || !input.readable) {
1003
+ ctx.error(`${fd}: invalid file descriptor: Bad file descriptor`);
1004
+ return 1;
1005
+ }
1006
+ if (prompt !== null)
1007
+ await ctx.err(prompt);
1008
+ // read bytes
1009
+ let bytes;
1010
+ const doRead = async (signal) => {
1011
+ if (nchars !== null) {
1012
+ // read up to n chars (bytes; good enough for ASCII), stopping at delim unless -N
1013
+ let acc = new Uint8Array(0);
1014
+ while (acc.length < nchars) {
1015
+ const chunk = await input.read(signal);
1016
+ if (chunk === null)
1017
+ break;
1018
+ let take = Math.min(chunk.length, nchars - acc.length);
1019
+ if (!exactChars && delim !== null) {
1020
+ const idx = chunk.subarray(0, take).indexOf(delim);
1021
+ if (idx >= 0)
1022
+ take = idx + 1;
1023
+ }
1024
+ const merged = new Uint8Array(acc.length + take);
1025
+ merged.set(acc);
1026
+ merged.set(chunk.subarray(0, take), acc.length);
1027
+ acc = merged;
1028
+ input.unread(chunk.subarray(take));
1029
+ if (!exactChars && delim !== null && acc[acc.length - 1] === delim)
1030
+ break;
1031
+ }
1032
+ return acc.length === 0 ? null : acc;
1033
+ }
1034
+ let acc = new Uint8Array(0);
1035
+ for (;;) {
1036
+ const part = await input.readUntil(delim);
1037
+ if (part === null)
1038
+ return acc.length === 0 ? null : acc;
1039
+ const merged = new Uint8Array(acc.length + part.length);
1040
+ merged.set(acc);
1041
+ merged.set(part, acc.length);
1042
+ acc = merged;
1043
+ // backslash-newline continuation without -r
1044
+ if (!raw && delim === 10 && acc.length >= 2 && acc[acc.length - 1] === 10 && acc[acc.length - 2] === 92)
1045
+ continue;
1046
+ return acc;
1047
+ }
1048
+ };
1049
+ if (timeout !== null) {
1050
+ const ac = new AbortController();
1051
+ const timer = setTimeout(() => ac.abort(), timeout * 1000);
1052
+ bytes = await doRead(ac.signal);
1053
+ clearTimeout(timer);
1054
+ if (ac.signal.aborted && bytes === null)
1055
+ return 142;
1056
+ }
1057
+ else {
1058
+ bytes = await doRead();
1059
+ }
1060
+ if (bytes === null) {
1061
+ for (const n of names.length > 0 ? names : arrayName ? [] : ['REPLY'])
1062
+ ctx.interp.assignScalar(ctx.proc, n, '');
1063
+ if (arrayName)
1064
+ st.ensure(arrayName).value = { kind: 'indexed', values: new Map() };
1065
+ return 1;
1066
+ }
1067
+ let text = new TextDecoder().decode(bytes);
1068
+ let hitDelim = false;
1069
+ if (delim !== null && nchars === null && text.length > 0 && text.charCodeAt(text.length - 1) === delim) {
1070
+ text = text.slice(0, -1);
1071
+ hitDelim = true;
1072
+ }
1073
+ else if (delim !== null && nchars !== null && !exactChars && text.length > 0 && text.charCodeAt(text.length - 1) === delim) {
1074
+ text = text.slice(0, -1);
1075
+ hitDelim = true;
1076
+ }
1077
+ // process backslashes (without -r): \x -> x, \<newline> removed; mark escaped chars so IFS does not split them
1078
+ const chars = [];
1079
+ for (let k = 0; k < text.length; k++) {
1080
+ const c = text[k];
1081
+ if (!raw && c === '\\' && k + 1 < text.length) {
1082
+ k++;
1083
+ if (text[k] === '\n')
1084
+ continue;
1085
+ chars.push({ c: text[k], esc: true });
1086
+ continue;
1087
+ }
1088
+ if (!raw && c === '\\')
1089
+ continue;
1090
+ chars.push({ c, esc: false });
1091
+ }
1092
+ const ifs = st.getString('IFS') ?? ' \t\n';
1093
+ const isWs = (c) => ifs.includes(c) && (c === ' ' || c === '\t' || c === '\n');
1094
+ const isIfs = (c) => !c.esc && ifs.includes(c.c);
1095
+ if (names.length === 0 && !arrayName) {
1096
+ ctx.interp.assignScalar(ctx.proc, 'REPLY', chars.map((c) => c.c).join(''));
1097
+ return hitDelim || nchars !== null ? 0 : 1;
1098
+ }
1099
+ // split into fields
1100
+ const fields = [];
1101
+ let pos = 0;
1102
+ const skipWs = () => {
1103
+ while (pos < chars.length && !chars[pos].esc && isWs(chars[pos].c))
1104
+ pos++;
1105
+ };
1106
+ skipWs();
1107
+ const targetCount = arrayName ? Infinity : names.length;
1108
+ while (pos < chars.length && fields.length < targetCount - 1) {
1109
+ let f = '';
1110
+ while (pos < chars.length && !isIfs(chars[pos]))
1111
+ f += chars[pos++].c;
1112
+ fields.push(f);
1113
+ // consume one delimiter (with surrounding whitespace)
1114
+ skipWs();
1115
+ if (pos < chars.length && isIfs(chars[pos]) && !isWs(chars[pos].c)) {
1116
+ pos++;
1117
+ skipWs();
1118
+ }
1119
+ }
1120
+ if (pos < chars.length) {
1121
+ // remainder goes to the last name; trim trailing IFS whitespace
1122
+ let end = chars.length;
1123
+ while (end > pos && !chars[end - 1].esc && isWs(chars[end - 1].c))
1124
+ end--;
1125
+ // a single trailing non-whitespace IFS delimiter is dropped from the last field
1126
+ if (end - 1 > pos && isIfs(chars[end - 1]) && !isWs(chars[end - 1].c) && !chars.slice(pos, end - 1).some(isIfs)) {
1127
+ end--;
1128
+ while (end > pos && !chars[end - 1].esc && isWs(chars[end - 1].c))
1129
+ end--;
1130
+ }
1131
+ let rest = chars.slice(pos, end).map((c) => c.c).join('');
1132
+ if (arrayName) {
1133
+ // arrays: split remainder fully
1134
+ rest = rest;
1135
+ }
1136
+ fields.push(rest);
1137
+ }
1138
+ if (arrayName) {
1139
+ const values = new Map();
1140
+ fields.forEach((f, k) => values.set(k, f));
1141
+ const v = st.ensure(arrayName);
1142
+ v.value = { kind: 'indexed', values };
1143
+ }
1144
+ else {
1145
+ names.forEach((n, k) => ctx.interp.assignScalar(ctx.proc, n, fields[k] ?? ''));
1146
+ }
1147
+ return hitDelim || nchars !== null ? 0 : 1;
1148
+ });
1149
+ def(['mapfile', 'readarray'], async (ctx) => {
1150
+ const args = ctx.argv.slice(1);
1151
+ let strip = false;
1152
+ let count = Infinity;
1153
+ let skip = 0;
1154
+ let delim = 10;
1155
+ let fd = 0;
1156
+ let name = 'MAPFILE';
1157
+ for (let i = 0; i < args.length; i++) {
1158
+ const a = args[i];
1159
+ if (a === '-t')
1160
+ strip = true;
1161
+ else if (a === '-n')
1162
+ count = Number(args[++i]) || Infinity;
1163
+ else if (a === '-s')
1164
+ skip = Number(args[++i]);
1165
+ else if (a === '-d') {
1166
+ const d = args[++i] ?? '';
1167
+ delim = d === '' ? 0 : d.charCodeAt(0);
1168
+ }
1169
+ else if (a === '-u')
1170
+ fd = Number(args[++i]);
1171
+ else if (a === '-C' || a === '-c' || a === '-O')
1172
+ i++;
1173
+ else
1174
+ name = a;
1175
+ }
1176
+ const input = ctx.proc.fds.get(fd);
1177
+ const values = new Map();
1178
+ if (input?.readable) {
1179
+ let n = 0;
1180
+ for (;;) {
1181
+ if (values.size >= count)
1182
+ break;
1183
+ const line = await input.readUntil(delim);
1184
+ if (line === null)
1185
+ break;
1186
+ let s = new TextDecoder().decode(line);
1187
+ if (strip && s.length > 0 && s.charCodeAt(s.length - 1) === delim)
1188
+ s = s.slice(0, -1);
1189
+ if (n++ < skip)
1190
+ continue;
1191
+ values.set(values.size, s);
1192
+ }
1193
+ }
1194
+ const v = ctx.proc.state.ensure(name);
1195
+ v.value = { kind: 'indexed', values };
1196
+ return 0;
1197
+ });
1198
+ // ---------------------------------------------------------------------------
1199
+ // test
1200
+ // ---------------------------------------------------------------------------
1201
+ def(['test'], async (ctx) => evalTest(ctx.argv.slice(1), ctx.proc));
1202
+ def(['['], async (ctx) => {
1203
+ if (ctx.argv[ctx.argv.length - 1] !== ']') {
1204
+ ctx.error("missing `]'");
1205
+ return 2;
1206
+ }
1207
+ return evalTest(ctx.argv.slice(1, -1), ctx.proc);
1208
+ });
1209
+ // ---------------------------------------------------------------------------
1210
+ // Control flow
1211
+ // ---------------------------------------------------------------------------
1212
+ function numArg(ctx, s, dflt) {
1213
+ if (s === undefined)
1214
+ return dflt;
1215
+ if (!/^-?\d+$/.test(s.trim())) {
1216
+ ctx.error(`${s}: numeric argument required`);
1217
+ return 2;
1218
+ }
1219
+ return Number(s) & 0xff;
1220
+ }
1221
+ def(['exit'], async (ctx) => {
1222
+ throw new ExitSignal(numArg(ctx, ctx.argv[1], ctx.proc.state.lastStatus));
1223
+ });
1224
+ def(['return'], async (ctx) => {
1225
+ const st = ctx.proc.state;
1226
+ if (st.funcStack.length === 0 && !ctx.proc.sourcing) {
1227
+ ctx.error("can only `return' from a function or sourced script");
1228
+ return 2; // bash 5 (3.2: 1)
1229
+ }
1230
+ throw new ReturnSignal(numArg(ctx, ctx.argv[1], st.lastStatus));
1231
+ });
1232
+ def(['break', 'continue'], async (ctx) => {
1233
+ const n = ctx.argv[1] === undefined ? 1 : Number(ctx.argv[1]);
1234
+ if (!Number.isInteger(n) || n < 1) {
1235
+ ctx.error(`${ctx.argv[1]}: loop count out of range`);
1236
+ return 1;
1237
+ }
1238
+ if (ctx.proc.loopDepth === 0)
1239
+ return 0;
1240
+ throw new LoopSignal(ctx.argv[0], Math.min(n, ctx.proc.loopDepth));
1241
+ });
1242
+ def(['eval'], async (ctx) => {
1243
+ const src = ctx.argv.slice(1).join(' ');
1244
+ if (src.trim() === '')
1245
+ return 0;
1246
+ let script;
1247
+ try {
1248
+ script = ctx.interp.rt.parse(src, 'eval');
1249
+ }
1250
+ catch (e) {
1251
+ if (e instanceof ParseError) {
1252
+ ctx.error(e.message);
1253
+ return 2;
1254
+ }
1255
+ throw e;
1256
+ }
1257
+ try {
1258
+ return await ctx.interp.execList(script.body, ctx.proc);
1259
+ }
1260
+ catch (e) {
1261
+ if (e instanceof DiscardError) {
1262
+ ctx.error(e.message);
1263
+ return e.status;
1264
+ }
1265
+ throw e;
1266
+ }
1267
+ });
1268
+ def(['source', '.'], async (ctx) => {
1269
+ const file = ctx.argv[1];
1270
+ if (file === undefined) {
1271
+ ctx.error('filename argument required');
1272
+ return 2;
1273
+ }
1274
+ const st = ctx.proc.state;
1275
+ let resolved = path.resolve(st.cwd, file);
1276
+ if (!file.includes('/') && !fs.existsSync(resolved)) {
1277
+ for (const dir of (st.getString('PATH') ?? '').split(':')) {
1278
+ const p = path.resolve(st.cwd, dir || '.', file);
1279
+ if (fs.existsSync(p)) {
1280
+ resolved = p;
1281
+ break;
1282
+ }
1283
+ }
1284
+ }
1285
+ const a = await ctx.interp.rt.assessRedirects([{ kind: 'read', path: known(resolved), source: 'source' }], ctx.node, ctx.proc);
1286
+ if (a.action === 'abort')
1287
+ throw new AbortRun(a.reason, a.status);
1288
+ if (a.action === 'deny') {
1289
+ ctx.error(a.reason);
1290
+ return a.status;
1291
+ }
1292
+ let text;
1293
+ try {
1294
+ text = fs.readFileSync(resolved, 'utf8');
1295
+ }
1296
+ catch {
1297
+ ctx.error(`${file}: No such file or directory`);
1298
+ return 1;
1299
+ }
1300
+ let script;
1301
+ try {
1302
+ script = ctx.interp.rt.parse(text, resolved);
1303
+ }
1304
+ catch (e) {
1305
+ if (e instanceof ParseError) {
1306
+ ctx.error(`${file}: ${e.message}`);
1307
+ return 2;
1308
+ }
1309
+ throw e;
1310
+ }
1311
+ const saved = st.positional;
1312
+ if (ctx.argv.length > 2)
1313
+ st.positional = ctx.argv.slice(2);
1314
+ const wasSourcing = ctx.proc.sourcing;
1315
+ ctx.proc.sourcing = true;
1316
+ const savedSource = st.globals.get('BASH_SOURCE');
1317
+ st.globals.set('BASH_SOURCE', newVar({ kind: 'indexed', values: new Map([[0, file], ...[...(savedSource?.value?.kind === 'indexed' ? savedSource.value.values.values() : [])].map((v, i) => [i + 1, v])]) }));
1318
+ try {
1319
+ return await ctx.interp.execList(script.body, ctx.proc);
1320
+ }
1321
+ catch (e) {
1322
+ if (e instanceof ReturnSignal)
1323
+ return e.status;
1324
+ throw e;
1325
+ }
1326
+ finally {
1327
+ if (savedSource)
1328
+ st.globals.set('BASH_SOURCE', savedSource);
1329
+ else
1330
+ st.globals.delete('BASH_SOURCE');
1331
+ ctx.proc.sourcing = wasSourcing;
1332
+ if (ctx.argv.length > 2)
1333
+ st.positional = saved;
1334
+ }
1335
+ });
1336
+ def(['exec'], async (ctx) => {
1337
+ const args = ctx.argv.slice(1);
1338
+ while (args[0] === '-c' || args[0] === '-l' || args[0] === '--')
1339
+ args.shift();
1340
+ if (args[0] === '-a')
1341
+ args.splice(0, 2);
1342
+ if (args.length === 0) {
1343
+ // make this command's redirections permanent
1344
+ const base = ctx.base.fds;
1345
+ const mine = new Map(ctx.proc.fds.entries());
1346
+ for (const [fd] of base.entries())
1347
+ if (!mine.has(fd))
1348
+ base.close(fd);
1349
+ for (const [fd, file] of mine)
1350
+ if (base.get(fd) !== file)
1351
+ base.set(fd, file.retain());
1352
+ return 0;
1353
+ }
1354
+ const status = await ctx.interp.runArgv(args, ctx.proc, ctx.node, { externalOnly: true });
1355
+ // the shell process was replaced: its EXIT trap never runs
1356
+ ctx.proc.state.traps.delete('EXIT');
1357
+ throw new ExitSignal(status);
1358
+ });
1359
+ def(['command'], async (ctx) => {
1360
+ const args = ctx.argv.slice(1);
1361
+ let describe = null;
1362
+ while (args[0]?.startsWith('-') && args[0] !== '-') {
1363
+ const a = args.shift();
1364
+ if (a === '--')
1365
+ break;
1366
+ if (a.includes('v'))
1367
+ describe = 'v';
1368
+ if (a.includes('V'))
1369
+ describe = 'V';
1370
+ }
1371
+ if (args.length === 0)
1372
+ return 0;
1373
+ if (describe) {
1374
+ let status = 0;
1375
+ for (const n of args) {
1376
+ const d = describeCommand(n, ctx.proc.state);
1377
+ if (!d) {
1378
+ if (describe === 'V')
1379
+ ctx.error(`${n}: not found`);
1380
+ status = 1;
1381
+ continue;
1382
+ }
1383
+ await ctx.out(describe === 'v' ? (d.kind === 'file' ? d.path : n) + '\n' : d.text + '\n');
1384
+ }
1385
+ return status;
1386
+ }
1387
+ return ctx.interp.runArgv(args, ctx.proc, ctx.node, { skipFunctions: true });
1388
+ });
1389
+ def(['builtin'], async (ctx) => {
1390
+ const args = ctx.argv.slice(1);
1391
+ if (args.length === 0)
1392
+ return 0;
1393
+ if (!BUILTINS.has(args[0])) {
1394
+ ctx.error(`${args[0]}: not a shell builtin`);
1395
+ return 1;
1396
+ }
1397
+ return ctx.interp.runArgv(args, ctx.proc, ctx.node, { builtinOnly: true });
1398
+ });
1399
+ const KEYWORDS = new Set(['if', 'then', 'else', 'elif', 'fi', 'case', 'esac', 'for', 'select', 'while', 'until', 'do', 'done', 'in', 'function', 'time', '{', '}', '!', '[[', ']]']);
1400
+ function describeCommand(name, st) {
1401
+ if (st.aliases.has(name))
1402
+ return { kind: 'alias', text: `${name} is aliased to \`${st.aliases.get(name)}'` };
1403
+ if (KEYWORDS.has(name))
1404
+ return { kind: 'keyword', text: `${name} is a shell keyword` };
1405
+ if (st.functions.has(name))
1406
+ return { kind: 'function', text: `${name} is a function` };
1407
+ if (BUILTINS.has(name))
1408
+ return { kind: 'builtin', text: `${name} is a shell builtin` };
1409
+ const p = resolveCommand(name, st);
1410
+ if (p)
1411
+ return { kind: 'file', path: p, text: `${name} is ${p}` };
1412
+ return null;
1413
+ }
1414
+ def(['type'], async (ctx) => {
1415
+ const args = ctx.argv.slice(1);
1416
+ let mode = 'normal';
1417
+ let all = false;
1418
+ const names = [];
1419
+ for (const a of args) {
1420
+ if (a === '-t')
1421
+ mode = 't';
1422
+ else if (a === '-p')
1423
+ mode = 'p';
1424
+ else if (a === '-P')
1425
+ mode = 'P';
1426
+ else if (a === '-a')
1427
+ all = true;
1428
+ else if (a === '-f')
1429
+ continue;
1430
+ else
1431
+ names.push(a);
1432
+ }
1433
+ let status = 0;
1434
+ for (const n of names) {
1435
+ if (all && mode === 'normal') {
1436
+ const lines = [];
1437
+ const d0 = describeCommand(n, ctx.proc.state);
1438
+ if (d0 && d0.kind !== 'file')
1439
+ lines.push(d0.text);
1440
+ for (const dir of (ctx.proc.state.getString('PATH') ?? '').split(':')) {
1441
+ const p = path.join(dir || '.', n);
1442
+ try {
1443
+ if (fs.statSync(p).isFile()) {
1444
+ fs.accessSync(p, fs.constants.X_OK);
1445
+ lines.push(`${n} is ${p}`);
1446
+ }
1447
+ }
1448
+ catch {
1449
+ // not here
1450
+ }
1451
+ }
1452
+ if (lines.length === 0) {
1453
+ ctx.error(`${n}: not found`);
1454
+ status = 1;
1455
+ }
1456
+ for (const l of [...new Set(lines)])
1457
+ await ctx.out(l + '\n');
1458
+ continue;
1459
+ }
1460
+ const d = mode === 'P' ? (() => {
1461
+ const p = resolveCommand(n, ctx.proc.state);
1462
+ return p ? { kind: 'file', path: p, text: '' } : null;
1463
+ })() : describeCommand(n, ctx.proc.state);
1464
+ if (!d) {
1465
+ if (mode === 'normal')
1466
+ ctx.error(`${n}: not found`);
1467
+ status = 1;
1468
+ continue;
1469
+ }
1470
+ if (mode === 't')
1471
+ await ctx.out(d.kind + '\n');
1472
+ else if (mode === 'p' || mode === 'P') {
1473
+ if (d.kind === 'file')
1474
+ await ctx.out(d.path + '\n');
1475
+ }
1476
+ else
1477
+ await ctx.out(d.text + '\n');
1478
+ }
1479
+ return status;
1480
+ });
1481
+ def(['hash'], async (ctx) => {
1482
+ if (ctx.argv.includes('-r'))
1483
+ ctx.proc.state.hash.clear();
1484
+ if (ctx.argv[1] === '-t') {
1485
+ let status = 0;
1486
+ for (const n of ctx.argv.slice(2)) {
1487
+ const p = ctx.proc.state.hash.get(n);
1488
+ if (p)
1489
+ await ctx.out(p + '\n');
1490
+ else {
1491
+ ctx.error(`${n}: not found`);
1492
+ status = 1;
1493
+ }
1494
+ }
1495
+ return status;
1496
+ }
1497
+ for (const n of ctx.argv.slice(1).filter((a) => !a.startsWith('-'))) {
1498
+ if (!resolveCommand(n, ctx.proc.state)) {
1499
+ ctx.error(`${n}: not found`);
1500
+ return 1;
1501
+ }
1502
+ }
1503
+ return 0;
1504
+ });
1505
+ def(['alias'], async (ctx) => {
1506
+ const st = ctx.proc.state;
1507
+ for (const a of ctx.argv.slice(1)) {
1508
+ const eq = a.indexOf('=');
1509
+ if (eq === -1) {
1510
+ const v = st.aliases.get(a);
1511
+ if (v === undefined)
1512
+ return 1;
1513
+ await ctx.out(`alias ${a}=${shellQuote(v)}\n`);
1514
+ }
1515
+ else
1516
+ st.aliases.set(a.slice(0, eq), a.slice(eq + 1));
1517
+ }
1518
+ return 0;
1519
+ });
1520
+ def(['unalias'], async (ctx) => {
1521
+ for (const a of ctx.argv.slice(1)) {
1522
+ if (a === '-a')
1523
+ ctx.proc.state.aliases.clear();
1524
+ else
1525
+ ctx.proc.state.aliases.delete(a);
1526
+ }
1527
+ return 0;
1528
+ });
1529
+ // ---------------------------------------------------------------------------
1530
+ // Jobs, traps
1531
+ // ---------------------------------------------------------------------------
1532
+ def(['wait'], async (ctx) => {
1533
+ const proc = ctx.proc;
1534
+ const args = ctx.argv.slice(1).filter((a) => a !== '-f');
1535
+ if (args[0] === '-n') {
1536
+ const pending = [...proc.jobs.values()].filter((j) => j.status === null);
1537
+ if (pending.length === 0)
1538
+ return 127;
1539
+ const s = await Promise.race(pending.map((j) => j.done));
1540
+ return s;
1541
+ }
1542
+ if (args.length === 0) {
1543
+ for (const j of proc.jobs.values())
1544
+ await j.done;
1545
+ proc.jobs.clear();
1546
+ return 0;
1547
+ }
1548
+ let status = 0;
1549
+ for (const a of args) {
1550
+ const pid = Number(a.replace(/^%/, ''));
1551
+ const job = proc.jobs.get(pid) ?? [...proc.jobs.values()][pid - 1];
1552
+ if (!job) {
1553
+ ctx.error(`pid ${a} is not a child of this shell`);
1554
+ status = 127;
1555
+ continue;
1556
+ }
1557
+ status = await job.done;
1558
+ proc.jobs.delete(job.pid);
1559
+ }
1560
+ return status;
1561
+ });
1562
+ def(['jobs'], async (ctx) => {
1563
+ let i = 1;
1564
+ for (const j of ctx.proc.jobs.values()) {
1565
+ await ctx.out(ctx.argv.includes('-p') ? `${j.pid}\n` : `[${i++}] ${j.status === null ? 'Running' : 'Done'}\t${j.pid}\n`);
1566
+ }
1567
+ return 0;
1568
+ });
1569
+ def(['kill'], async (ctx) => {
1570
+ const args = ctx.argv.slice(1);
1571
+ let sig = 'SIGTERM';
1572
+ if (args[0] === '-l') {
1573
+ await ctx.out(Object.keys(os.constants.signals).map((s) => s.replace(/^SIG/, '')).join(' ') + '\n');
1574
+ return 0;
1575
+ }
1576
+ if (args[0] === '-s' || args[0] === '-n') {
1577
+ args.shift();
1578
+ const s = args.shift() ?? 'TERM';
1579
+ sig = (/^\d+$/.test(s) ? Object.entries(os.constants.signals).find(([, n]) => n === Number(s))?.[0] : 'SIG' + s.replace(/^SIG/, ''));
1580
+ }
1581
+ else if (args[0]?.startsWith('-') && args[0] !== '--') {
1582
+ const s = args.shift().slice(1);
1583
+ if (s === '0')
1584
+ sig = 'SIG0';
1585
+ else
1586
+ sig = (/^\d+$/.test(s) ? Object.entries(os.constants.signals).find(([, n]) => n === Number(s))?.[0] ?? 'SIGTERM' : 'SIG' + s.replace(/^SIG/, ''));
1587
+ }
1588
+ if (args[0] === '--')
1589
+ args.shift();
1590
+ let status = 0;
1591
+ for (const a of args) {
1592
+ const n = Number(a.replace(/^%/, ''));
1593
+ const job = ctx.proc.jobs.get(n) ?? (a.startsWith('%') ? [...ctx.proc.jobs.values()][n - 1] : undefined) ?? ctx.interp.rt.findJob(n);
1594
+ const signalZero = sig === undefined || sig === 'SIG0' || sig === 'SIGEXIT';
1595
+ if (job) {
1596
+ if (signalZero) {
1597
+ if (job.status !== null)
1598
+ status = 1;
1599
+ continue;
1600
+ }
1601
+ job.kill(sig);
1602
+ continue;
1603
+ }
1604
+ if (n === ctx.interp.rt.shellPid || n === ctx.proc.pid) {
1605
+ // the VM's own (virtual) shell: never signal the host process
1606
+ if (signalZero)
1607
+ continue;
1608
+ const name = String(sig).replace(/^SIG/, '');
1609
+ const trap = ctx.proc.state.traps.get(name);
1610
+ if (trap !== undefined) {
1611
+ if (trap !== '')
1612
+ await ctx.interp.execList(ctx.interp.rt.parse(trap, `trap ${name}`).body, ctx.proc);
1613
+ continue;
1614
+ }
1615
+ throw new ExitSignal(128 + (os.constants.signals[sig] ?? 15));
1616
+ }
1617
+ try {
1618
+ process.kill(n, sig);
1619
+ }
1620
+ catch (e) {
1621
+ ctx.error(`(${a}) - ${e.code === 'ESRCH' ? 'No such process' : String(e)}`);
1622
+ status = 1;
1623
+ }
1624
+ }
1625
+ return status;
1626
+ });
1627
+ def(['trap'], async (ctx) => {
1628
+ const st = ctx.proc.state;
1629
+ const args = ctx.argv.slice(1);
1630
+ if (args.length === 0 || args[0] === '-p') {
1631
+ for (const [sig, action] of st.parentTraps ?? st.traps) {
1632
+ if (args[0] === '-p' && args.length > 1 && !args.slice(1).some((a) => a.toUpperCase().replace(/^SIG/, '') === sig))
1633
+ continue;
1634
+ const name = ['EXIT', 'ERR', 'DEBUG', 'RETURN'].includes(sig) ? sig : `SIG${sig}`;
1635
+ await ctx.out(`trap -- ${shellQuote(action)} ${name}\n`);
1636
+ }
1637
+ return 0;
1638
+ }
1639
+ if (args[0] === '-l') {
1640
+ await ctx.out(Object.keys(os.constants.signals).join(' ') + '\n');
1641
+ return 0;
1642
+ }
1643
+ let action = args[0];
1644
+ let sigs = args.slice(1);
1645
+ if (/^\d+$/.test(action) && sigs.length === 0) {
1646
+ sigs = [action];
1647
+ action = null;
1648
+ }
1649
+ if (action === '-')
1650
+ action = null;
1651
+ st.parentTraps = undefined;
1652
+ for (let s of sigs) {
1653
+ s = s.toUpperCase().replace(/^SIG/, '');
1654
+ if (s === '0')
1655
+ s = 'EXIT';
1656
+ if (action === null)
1657
+ st.traps.delete(s);
1658
+ else
1659
+ st.traps.set(s, action);
1660
+ }
1661
+ return 0;
1662
+ });
1663
+ def(['getopts'], async (ctx) => {
1664
+ const st = ctx.proc.state;
1665
+ const [optstring, name, ...rest] = ctx.argv.slice(1);
1666
+ if (optstring === undefined || name === undefined) {
1667
+ ctx.error('usage: getopts optstring name [arg ...]');
1668
+ return 2;
1669
+ }
1670
+ const args = rest.length > 0 ? rest : st.positional;
1671
+ let optind = Number(st.getString('OPTIND') ?? '1') || 1;
1672
+ const silent = optstring.startsWith(':');
1673
+ const spec = silent ? optstring.slice(1) : optstring;
1674
+ const sub = Number(st.getString('__MASH_OPTPOS') ?? '1') || 1;
1675
+ const arg = args[optind - 1];
1676
+ const set = (n, v) => ctx.interp.assignScalar(ctx.proc, n, v);
1677
+ if (arg === undefined || !arg.startsWith('-') || arg === '-') {
1678
+ set(name, '?');
1679
+ return 1;
1680
+ }
1681
+ if (arg === '--') {
1682
+ set('OPTIND', String(optind + 1));
1683
+ set(name, '?');
1684
+ return 1;
1685
+ }
1686
+ const ch = arg[sub];
1687
+ let nextSub = sub + 1;
1688
+ const advance = () => {
1689
+ if (nextSub >= arg.length) {
1690
+ optind++;
1691
+ nextSub = 1;
1692
+ }
1693
+ };
1694
+ const idx = spec.indexOf(ch);
1695
+ if (idx === -1 || ch === ':') {
1696
+ if (silent) {
1697
+ set('OPTARG', ch);
1698
+ }
1699
+ else {
1700
+ ctx.error(`illegal option -- ${ch}`);
1701
+ st.unset('OPTARG');
1702
+ }
1703
+ set(name, '?');
1704
+ advance();
1705
+ set('OPTIND', String(optind));
1706
+ set('__MASH_OPTPOS', String(nextSub));
1707
+ return 0;
1708
+ }
1709
+ if (spec[idx + 1] === ':') {
1710
+ let optarg;
1711
+ if (nextSub < arg.length) {
1712
+ optarg = arg.slice(nextSub);
1713
+ optind++;
1714
+ }
1715
+ else {
1716
+ optarg = args[optind];
1717
+ optind += 2;
1718
+ }
1719
+ nextSub = 1;
1720
+ if (optarg === undefined) {
1721
+ if (silent) {
1722
+ set(name, ':');
1723
+ set('OPTARG', ch);
1724
+ }
1725
+ else {
1726
+ ctx.error(`option requires an argument -- ${ch}`);
1727
+ set(name, '?');
1728
+ }
1729
+ set('OPTIND', String(optind));
1730
+ set('__MASH_OPTPOS', '1');
1731
+ return 0;
1732
+ }
1733
+ set('OPTARG', optarg);
1734
+ }
1735
+ else {
1736
+ st.unset('OPTARG');
1737
+ advance();
1738
+ }
1739
+ set(name, ch);
1740
+ set('OPTIND', String(optind));
1741
+ set('__MASH_OPTPOS', String(nextSub));
1742
+ return 0;
1743
+ });
1744
+ def(['umask'], async (ctx) => {
1745
+ const st = ctx.proc.state;
1746
+ const args = ctx.argv.slice(1);
1747
+ const symbolic = args[0] === '-S';
1748
+ if (symbolic)
1749
+ args.shift();
1750
+ if (args[0] === '-p')
1751
+ args.shift();
1752
+ if (args.length === 0) {
1753
+ if (symbolic) {
1754
+ const perm = (shift) => ['r', 'w', 'x'].filter((_, i) => !(st.umask & (4 >> i) << shift)).join('');
1755
+ await ctx.out(`u=${perm(6)},g=${perm(3)},o=${perm(0)}\n`);
1756
+ }
1757
+ else
1758
+ await ctx.out(st.umask.toString(8).padStart(4, '0') + '\n');
1759
+ return 0;
1760
+ }
1761
+ if (!/^[0-7]{1,4}$/.test(args[0])) {
1762
+ ctx.error(`${args[0]}: octal number out of range (symbolic modes are not supported)`);
1763
+ return 1;
1764
+ }
1765
+ st.umask = parseInt(args[0], 8);
1766
+ return 0;
1767
+ });
1768
+ def(['times'], async (ctx) => {
1769
+ await ctx.out('0m0.000s 0m0.000s\n0m0.000s 0m0.000s\n');
1770
+ return 0;
1771
+ });
1772
+ def(['caller'], async () => 1);
1773
+ //# sourceMappingURL=builtins.js.map