fauxnix-cli 2.0.0 → 2.1.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/README.md +17 -5
- package/dist/cli.js +12 -0
- package/dist/commands/files.js +1 -0
- package/dist/commands/gzip-node.d.ts +15 -1
- package/dist/commands/gzip-node.js +25 -8
- package/dist/commands/text-filters.js +10 -7
- package/dist/commands/text-io.js +3 -4
- package/dist/doctor.js +9 -0
- package/dist/facade-launch.d.ts +29 -0
- package/dist/facade-launch.js +197 -0
- package/dist/facade-main.d.ts +1 -0
- package/dist/facade-main.js +11 -0
- package/dist/facade-sea.cjs +17802 -0
- package/dist/facade.js +124 -4
- package/dist/parser.js +39 -32
- package/dist/ps-host.js +20 -22
- package/dist/runtime-support.d.ts +1 -1
- package/dist/runtime-support.js +11 -2
- package/dist/translator.d.ts +1 -0
- package/dist/translator.js +117 -18
- package/dist/version.js +12 -5
- package/package.json +3 -1
package/dist/facade.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { appendFileSync, writeFileSync } from 'node:fs';
|
|
1
2
|
import { parseCommand } from './parser.js';
|
|
2
3
|
import { translateCommandList, EXECUTE_TRANSLATION } from './translator.js';
|
|
3
4
|
import { FauxnixSession } from './executor.js';
|
|
@@ -28,6 +29,71 @@ async function runScript(session, script) {
|
|
|
28
29
|
function bashQuote(word) {
|
|
29
30
|
return "'" + word.replaceAll("'", `'\\''`) + "'";
|
|
30
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Claude Code's Bash tool wraps every command in private scaffolding,
|
|
34
|
+
* captured from a live session (2026-10-05; see docs/rfc-bash-facade.md):
|
|
35
|
+
*
|
|
36
|
+
* export TEMP='..' TMP='..' && shopt -u extglob 2>/dev/null || true &&
|
|
37
|
+
* { \builtin unalias -- 'unsetenv'; \builtin unset -f -- 'unsetenv'; }
|
|
38
|
+
* >/dev/null 2>&1 || true && eval 'PAYLOAD' < /dev/null &&
|
|
39
|
+
* pwd -P >| /c/.../claude-XXXX-cwd
|
|
40
|
+
*
|
|
41
|
+
* plus a shell-snapshot bootstrap built with heredocs and function
|
|
42
|
+
* definitions. The scaffolding is harness plumbing, not user bash: the
|
|
43
|
+
* facade applies the export prefix, executes the payload, and writes the
|
|
44
|
+
* cwd marker itself (only on success, matching bash's `&&` chain). Pattern
|
|
45
|
+
* drift falls through to plain translation and fails loud — visible in the
|
|
46
|
+
* FAUXNIX_FACADE_TRACE capture, never silently wrong.
|
|
47
|
+
*/
|
|
48
|
+
const CC_SNAPSHOT_RE = /^SNAPSHOT_FILE='([^']+)'[\s\S]*RIPGREP_FUNC_END/;
|
|
49
|
+
const CC_COMMAND_RE = /^(?:source \S+ 2>\/dev\/null \|\| true &&\s*)?(export\s+[^\n]*?)\s*&&\s*shopt -u extglob[\s\S]*?&& eval '([\s\S]*?)' < \/dev\/null && pwd -P >\| (\S+)\s*$/;
|
|
50
|
+
function toPosixPath(p) {
|
|
51
|
+
const s = p.replaceAll('\\', '/');
|
|
52
|
+
const m = /^([A-Za-z]):(\/.*)?$/.exec(s);
|
|
53
|
+
return m ? '/' + m[1].toLowerCase() + (m[2] ?? '') : s;
|
|
54
|
+
}
|
|
55
|
+
function fromPosixPath(p) {
|
|
56
|
+
const m = /^\/([A-Za-z])(\/.*)?$/.exec(p);
|
|
57
|
+
return m ? m[1].toUpperCase() + ':' + (m[2] ?? '').replaceAll('/', '\\') : p;
|
|
58
|
+
}
|
|
59
|
+
/** Returns the exit code, or null when the script is not Claude Code scaffolding. */
|
|
60
|
+
async function tryClaudeCodeAdapter(session, script) {
|
|
61
|
+
const snap = CC_SNAPSHOT_RE.exec(script);
|
|
62
|
+
if (snap) {
|
|
63
|
+
try {
|
|
64
|
+
writeFileSync(fromPosixPath(snap[1]), '# Snapshot file\n# fauxnix facade: shell state lives in the facade session, not a snapshot script\n');
|
|
65
|
+
return 0;
|
|
66
|
+
}
|
|
67
|
+
catch (err) {
|
|
68
|
+
process.stderr.write(`fauxnix: facade: snapshot write failed: ${err.message}\n`);
|
|
69
|
+
return 1;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const cmd = CC_COMMAND_RE.exec(script);
|
|
73
|
+
if (!cmd)
|
|
74
|
+
return null;
|
|
75
|
+
const [, exportPart, payload, markerPosix] = cmd;
|
|
76
|
+
const env = await runScript(session, exportPart);
|
|
77
|
+
if (env.exitCode !== 0) {
|
|
78
|
+
if (env.stderr)
|
|
79
|
+
process.stderr.write(env.stderr);
|
|
80
|
+
return env.exitCode;
|
|
81
|
+
}
|
|
82
|
+
const r = await runScript(session, payload);
|
|
83
|
+
if (r.stdout)
|
|
84
|
+
process.stdout.write(r.stdout);
|
|
85
|
+
if (r.stderr)
|
|
86
|
+
process.stderr.write(r.stderr);
|
|
87
|
+
if (r.exitCode !== 0)
|
|
88
|
+
return r.exitCode; // bash: && chain stops, no marker
|
|
89
|
+
try {
|
|
90
|
+
writeFileSync(fromPosixPath(markerPosix), toPosixPath(session.cwd ?? process.cwd()) + '\n');
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
/* the marker is best-effort bookkeeping for the harness */
|
|
94
|
+
}
|
|
95
|
+
return 0;
|
|
96
|
+
}
|
|
31
97
|
async function runOneShot(session, script, positionals) {
|
|
32
98
|
// bash -c '' is a successful no-op, distinct from a missing operand.
|
|
33
99
|
if (script === '')
|
|
@@ -51,6 +117,18 @@ async function runOneShot(session, script, positionals) {
|
|
|
51
117
|
process.stderr.write(r.stderr);
|
|
52
118
|
return r.exitCode;
|
|
53
119
|
}
|
|
120
|
+
/** Diagnostic trace: set FAUXNIX_FACADE_TRACE to append raw argv/stdin traffic. */
|
|
121
|
+
function trace(kind, data) {
|
|
122
|
+
const file = process.env['FAUXNIX_FACADE_TRACE'];
|
|
123
|
+
if (!file)
|
|
124
|
+
return;
|
|
125
|
+
try {
|
|
126
|
+
appendFileSync(file, `[${kind}] ${JSON.stringify(data)}\n`, 'utf8');
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
/* diagnostics must never break the facade */
|
|
130
|
+
}
|
|
131
|
+
}
|
|
54
132
|
async function runMarkerSession(session) {
|
|
55
133
|
await session.prewarm();
|
|
56
134
|
return new Promise((resolve) => {
|
|
@@ -58,6 +136,7 @@ async function runMarkerSession(session) {
|
|
|
58
136
|
let queue = Promise.resolve();
|
|
59
137
|
process.stdin.setEncoding('utf8');
|
|
60
138
|
process.stdin.on('data', (chunk) => {
|
|
139
|
+
trace('stdin', chunk);
|
|
61
140
|
buf += chunk;
|
|
62
141
|
let m;
|
|
63
142
|
while ((m = MARKER_RE.exec(buf))) {
|
|
@@ -86,20 +165,61 @@ async function runMarkerSession(session) {
|
|
|
86
165
|
});
|
|
87
166
|
});
|
|
88
167
|
}
|
|
168
|
+
/**
|
|
169
|
+
* bash argv contract: options may combine and may appear between -c and the
|
|
170
|
+
* command string. Observed from Claude Code: `bash -c env`, `bash -lc '...'`,
|
|
171
|
+
* `bash -c -l '<script>'`. Returns null when argv is not a -c invocation.
|
|
172
|
+
*/
|
|
173
|
+
function parseDashC(argv) {
|
|
174
|
+
let wantScript = false;
|
|
175
|
+
let script;
|
|
176
|
+
const positionals = [];
|
|
177
|
+
for (let i = 0; i < argv.length; i++) {
|
|
178
|
+
const token = argv[i];
|
|
179
|
+
if (token === '--') {
|
|
180
|
+
for (let j = i + 1; j < argv.length; j++)
|
|
181
|
+
positionals.push(argv[j]);
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
if (token.startsWith('-') && token.length > 1 && script === undefined) {
|
|
185
|
+
for (const ch of token.slice(1)) {
|
|
186
|
+
if (ch === 'c' || ch === 'e')
|
|
187
|
+
wantScript = true;
|
|
188
|
+
else if (ch !== 'l' && ch !== 'i' && ch !== 's' && ch !== 'r')
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
if (wantScript && script === undefined) {
|
|
194
|
+
script = token;
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
positionals.push(token);
|
|
198
|
+
}
|
|
199
|
+
if (!wantScript)
|
|
200
|
+
return null;
|
|
201
|
+
return { script, positionals };
|
|
202
|
+
}
|
|
89
203
|
export async function runFacade(argv) {
|
|
204
|
+
trace('argv', argv.join(' '));
|
|
90
205
|
const session = new FauxnixSession();
|
|
91
206
|
try {
|
|
92
207
|
if (argv[0] === '--version') {
|
|
93
208
|
process.stdout.write(VERSION_LINE);
|
|
94
209
|
return 0;
|
|
95
210
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
if (script === undefined) {
|
|
211
|
+
const dashC = parseDashC(argv);
|
|
212
|
+
if (dashC) {
|
|
213
|
+
if (dashC.script === undefined) {
|
|
99
214
|
process.stderr.write('bash: -c: option requires an argument\n');
|
|
100
215
|
return 2;
|
|
101
216
|
}
|
|
102
|
-
|
|
217
|
+
if (dashC.positionals.length === 0) {
|
|
218
|
+
const adapted = await tryClaudeCodeAdapter(session, dashC.script);
|
|
219
|
+
if (adapted !== null)
|
|
220
|
+
return adapted;
|
|
221
|
+
}
|
|
222
|
+
return await runOneShot(session, dashC.script, dashC.positionals);
|
|
103
223
|
}
|
|
104
224
|
return await runMarkerSession(session);
|
|
105
225
|
}
|
package/dist/parser.js
CHANGED
|
@@ -93,8 +93,20 @@ export function tokenize(input) {
|
|
|
93
93
|
}
|
|
94
94
|
// the fd digits were consumed earlier; advance past the operator tail only
|
|
95
95
|
advance = matched.length - fdDigits.length;
|
|
96
|
+
// fd 1 is stdout: `1>f` / `1>>f` are the same redirects as `>f` / `>>f`
|
|
97
|
+
if (matched === '1>')
|
|
98
|
+
matched = '>';
|
|
99
|
+
else if (matched === '1>>')
|
|
100
|
+
matched = '>>';
|
|
96
101
|
fdDigits = '';
|
|
97
102
|
}
|
|
103
|
+
else if (matched === '>' &&
|
|
104
|
+
input.startsWith('&2', i + 1) &&
|
|
105
|
+
!/[^\s;|&<>()]/.test(input[i + 3] ?? ' ')) {
|
|
106
|
+
// `>&2` is shorthand for `1>&2`
|
|
107
|
+
matched = '1>&2';
|
|
108
|
+
advance = 3;
|
|
109
|
+
}
|
|
98
110
|
if (matched === '<<') {
|
|
99
111
|
throw new FauxnixParseError('fauxnix: heredocs (<<) are not supported yet. Pass the text via echo pipe or a temp file instead.');
|
|
100
112
|
}
|
|
@@ -1046,11 +1058,9 @@ export function parseCommand(input) {
|
|
|
1046
1058
|
next();
|
|
1047
1059
|
expectKw('in');
|
|
1048
1060
|
const words = [];
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
if (peekKw() === 'do')
|
|
1053
|
-
break;
|
|
1061
|
+
// Reserved words are ordinary list elements until the header's separator:
|
|
1062
|
+
// `for x in do; do ...` iterates over the literal word "do".
|
|
1063
|
+
while (!(peek().type === 'OP' && isListSep(peek().op))) {
|
|
1054
1064
|
const t = peek();
|
|
1055
1065
|
if (t.type !== 'WORD' || !t.parts) {
|
|
1056
1066
|
throw new FauxnixParseError("fauxnix: `for` expected `do`");
|
|
@@ -1058,6 +1068,11 @@ export function parseCommand(input) {
|
|
|
1058
1068
|
words.push(t.parts);
|
|
1059
1069
|
next();
|
|
1060
1070
|
}
|
|
1071
|
+
// A semicolon may be followed by newlines, but another semicolon (or
|
|
1072
|
+
// more words before `do`) is not another part of the word list.
|
|
1073
|
+
next();
|
|
1074
|
+
while (peek().type === 'OP' && peek().op === '\n')
|
|
1075
|
+
next();
|
|
1061
1076
|
expectKw('do');
|
|
1062
1077
|
const body = parseListUntil(['done']);
|
|
1063
1078
|
expectKw('done');
|
|
@@ -1261,6 +1276,9 @@ export function parseCommand(input) {
|
|
|
1261
1276
|
next();
|
|
1262
1277
|
continue;
|
|
1263
1278
|
}
|
|
1279
|
+
if (t.type === 'OP' && /^\d+[<>]/.test(t.op) && !isRedirectOp(t.op)) {
|
|
1280
|
+
normalizeRedirect(t.op);
|
|
1281
|
+
}
|
|
1264
1282
|
if (t.type === 'OP' && isRedirectOp(t.op)) {
|
|
1265
1283
|
const op = t.op;
|
|
1266
1284
|
next();
|
|
@@ -1427,38 +1445,27 @@ export function parseCommand(input) {
|
|
|
1427
1445
|
* is not a valid assignment.
|
|
1428
1446
|
*/
|
|
1429
1447
|
function splitAssignment(w) {
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
last.text += p.text;
|
|
1439
|
-
}
|
|
1440
|
-
else {
|
|
1441
|
-
merged.push({ ...p });
|
|
1442
|
-
}
|
|
1443
|
-
}
|
|
1444
|
-
for (let idx = 0; idx < merged.length; idx++) {
|
|
1445
|
-
const p = merged[idx];
|
|
1446
|
-
if (p.kind !== 'Text')
|
|
1447
|
-
continue;
|
|
1448
|
+
let name = '';
|
|
1449
|
+
for (let idx = 0; idx < w.length; idx++) {
|
|
1450
|
+
const p = w[idx];
|
|
1451
|
+
// Quoting/escaping anywhere in NAME= makes this a command word.
|
|
1452
|
+
// Do not merge parts here: the value's escapes also distinguish
|
|
1453
|
+
// literal tildes/parentheses from home expansion/array assignment.
|
|
1454
|
+
if (p.kind !== 'Text' || p.escaped)
|
|
1455
|
+
return null;
|
|
1448
1456
|
const eq = p.text.indexOf('=');
|
|
1449
|
-
if (eq
|
|
1450
|
-
|
|
1451
|
-
const name = merged
|
|
1452
|
-
.slice(0, idx)
|
|
1453
|
-
.map((q) => (q.kind === 'Text' || q.kind === 'SingleQuoted' ? q.text : ''))
|
|
1454
|
-
.join('') + p.text.slice(0, eq);
|
|
1455
|
-
if (!isNameStart(name[0]) || !name.split('').every(isNameChar))
|
|
1457
|
+
if (eq < 0) {
|
|
1458
|
+
name += p.text;
|
|
1456
1459
|
continue;
|
|
1460
|
+
}
|
|
1461
|
+
name += p.text.slice(0, eq);
|
|
1462
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
|
|
1463
|
+
return null;
|
|
1457
1464
|
const value = [];
|
|
1458
1465
|
const tail = p.text.slice(eq + 1);
|
|
1459
1466
|
if (tail)
|
|
1460
|
-
value.push({
|
|
1461
|
-
value.push(...
|
|
1467
|
+
value.push({ ...p, text: tail });
|
|
1468
|
+
value.push(...w.slice(idx + 1));
|
|
1462
1469
|
return { name, value };
|
|
1463
1470
|
}
|
|
1464
1471
|
return null;
|
package/dist/ps-host.js
CHANGED
|
@@ -377,6 +377,17 @@ export class PowerShellHost {
|
|
|
377
377
|
windowsHide: true,
|
|
378
378
|
});
|
|
379
379
|
this.proc = child;
|
|
380
|
+
child.stdin.on('error', (e) => {
|
|
381
|
+
// A closed host input pipe reports EPIPE asynchronously; write()'s
|
|
382
|
+
// try/catch cannot contain it. Fail this request through the normal
|
|
383
|
+
// dead-host path and leave the next invocation free to start again.
|
|
384
|
+
if (this.proc !== child)
|
|
385
|
+
return;
|
|
386
|
+
this.closeErr = e;
|
|
387
|
+
this.closed = true;
|
|
388
|
+
this.failWaiters(e);
|
|
389
|
+
this.cancelNativeCapture();
|
|
390
|
+
});
|
|
380
391
|
child.stdout.on('data', (d) => {
|
|
381
392
|
if (this.proc !== child)
|
|
382
393
|
return;
|
|
@@ -393,6 +404,7 @@ export class PowerShellHost {
|
|
|
393
404
|
this.closeErr = e;
|
|
394
405
|
this.closed = true;
|
|
395
406
|
this.failWaiters(e);
|
|
407
|
+
this.cancelNativeCapture();
|
|
396
408
|
});
|
|
397
409
|
child.on('close', (c) => {
|
|
398
410
|
if (this.proc !== child)
|
|
@@ -401,6 +413,7 @@ export class PowerShellHost {
|
|
|
401
413
|
this.closed = true;
|
|
402
414
|
this.proc = null;
|
|
403
415
|
this.failWaiters(new Error('fauxnix: powershell host closed'));
|
|
416
|
+
this.cancelNativeCapture();
|
|
404
417
|
});
|
|
405
418
|
try {
|
|
406
419
|
const readyLine = await this.nextReadyLine(READY_TIMEOUT_MS);
|
|
@@ -512,7 +525,7 @@ export class PowerShellHost {
|
|
|
512
525
|
let outSeq = 0;
|
|
513
526
|
let errSeq = 0;
|
|
514
527
|
let end = null;
|
|
515
|
-
const nativePromise = this.beginNativeCapture(id, limits?.stderrMode ?? 'capture', limits?.stderrLimit ?? DEFAULT_STDERR_LIMIT, limits?.nativeStderrSpoolPath, timeoutMs
|
|
528
|
+
const nativePromise = this.beginNativeCapture(id, limits?.stderrMode ?? 'capture', limits?.stderrLimit ?? DEFAULT_STDERR_LIMIT, limits?.nativeStderrSpoolPath, timeoutMs);
|
|
516
529
|
// collectV2 can leave through a frame timeout before it reaches the await
|
|
517
530
|
// below. Attach a handler immediately so teardown never reports a stray
|
|
518
531
|
// promise rejection; the awaited path still receives the same failure.
|
|
@@ -547,26 +560,11 @@ export class PowerShellHost {
|
|
|
547
560
|
end = f;
|
|
548
561
|
}
|
|
549
562
|
}
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
new Promise((_, reject) => {
|
|
556
|
-
markerTimer = setTimeout(() => reject(new Error('fauxnix: native stderr marker missing')), 2000);
|
|
557
|
-
}),
|
|
558
|
-
]);
|
|
559
|
-
nativeBytes = captured.bytesSeen;
|
|
560
|
-
}
|
|
561
|
-
catch (e) {
|
|
562
|
-
this.cancelNativeCapture();
|
|
563
|
-
if (e instanceof NativeStderrSpoolError)
|
|
564
|
-
throw e;
|
|
565
|
-
}
|
|
566
|
-
finally {
|
|
567
|
-
if (markerTimer)
|
|
568
|
-
clearTimeout(markerTimer);
|
|
569
|
-
}
|
|
563
|
+
// The end frame and native marker arrive on independent pipes. Finishing
|
|
564
|
+
// stdout does not complete the request: cancellation, pipe failure and
|
|
565
|
+
// the original deadline still apply while native stderr is pending.
|
|
566
|
+
// Let invokeSerial handle failures so it also removes partial spools.
|
|
567
|
+
const { bytesSeen: nativeBytes } = await nativePromise;
|
|
570
568
|
const capturedErr = Buffer.from(Buffer.concat(err));
|
|
571
569
|
let native = Buffer.alloc(0);
|
|
572
570
|
let nativeTruncated = false;
|
|
@@ -601,7 +599,7 @@ export class PowerShellHost {
|
|
|
601
599
|
if (this.nativeCapture?.id !== id)
|
|
602
600
|
return;
|
|
603
601
|
const state = this.nativeCapture;
|
|
604
|
-
const failure = state.ioError ?? new Error('fauxnix: native stderr marker
|
|
602
|
+
const failure = state.ioError ?? Object.assign(new Error('fauxnix: native stderr marker timed out'), { timedOut: true });
|
|
605
603
|
this.closeNativeSpool(state);
|
|
606
604
|
this.nativeCapture = null;
|
|
607
605
|
reject(failure);
|
package/dist/runtime-support.js
CHANGED
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
2
|
// Keep diagnostics and the entrypoint aligned with the install contract.
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
// The SEA launcher bundle has no package.json beside its executable; the
|
|
4
|
+
// launcher build injects the engine range as a banner global instead.
|
|
5
|
+
const bundledRange = globalThis.__FAUXNIX_ENGINES_NODE__;
|
|
6
|
+
export let nodeEngineRange;
|
|
7
|
+
if (typeof bundledRange === 'string') {
|
|
8
|
+
nodeEngineRange = bundledRange;
|
|
9
|
+
}
|
|
10
|
+
else {
|
|
11
|
+
const metadata = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
12
|
+
nodeEngineRange = metadata.engines?.node;
|
|
13
|
+
}
|
|
5
14
|
const minimum = /^>=(\d+)\.(\d+)\.(\d+)$/.exec(nodeEngineRange);
|
|
6
15
|
if (!minimum)
|
|
7
16
|
throw new Error('fauxnix: unsupported package.json Node engine range');
|
package/dist/translator.d.ts
CHANGED
|
@@ -102,6 +102,7 @@ export declare function wrapTempEnv(sets: Assignment[], body: string, extra?: {
|
|
|
102
102
|
unsets?: string[];
|
|
103
103
|
persistNames?: Set<string>;
|
|
104
104
|
persistWords?: Word[];
|
|
105
|
+
preserveArgumentStatus?: boolean;
|
|
105
106
|
}): string;
|
|
106
107
|
export interface PipelineParts {
|
|
107
108
|
/** Generated function definitions (empty for single commands). */
|
package/dist/translator.js
CHANGED
|
@@ -372,7 +372,7 @@ export function pathExpr(s) {
|
|
|
372
372
|
export function exprOfWord(w, opts) {
|
|
373
373
|
// tilde expansion (unquoted leading ~)
|
|
374
374
|
const expanded = [];
|
|
375
|
-
if (w.length > 0 && w[0].kind === 'Text' && w[0].text.startsWith('~')) {
|
|
375
|
+
if (w.length > 0 && w[0].kind === 'Text' && !w[0].escaped && w[0].text.startsWith('~')) {
|
|
376
376
|
expanded.push({ kind: 'Var', name: 'HOME' });
|
|
377
377
|
const rest = w[0].text.slice(1);
|
|
378
378
|
if (rest)
|
|
@@ -490,7 +490,7 @@ export function literalOfWord(w) {
|
|
|
490
490
|
if (!w.every((p) => p.kind === 'Text' || p.kind === 'SingleQuoted'))
|
|
491
491
|
return null;
|
|
492
492
|
const text = w.map((p) => p.text).join('');
|
|
493
|
-
if (w.length > 0 && w[0].kind === 'Text' && w[0].text.startsWith('~'))
|
|
493
|
+
if (w.length > 0 && w[0].kind === 'Text' && !w[0].escaped && w[0].text.startsWith('~'))
|
|
494
494
|
return null; // needs $HOME
|
|
495
495
|
return text;
|
|
496
496
|
}
|
|
@@ -597,7 +597,14 @@ export function argListExpr(words, fn = exprOfWord) {
|
|
|
597
597
|
*/
|
|
598
598
|
export function translateCmdSub(cmdText, keepNl = false, translation = EXECUTE_TRANSLATION) {
|
|
599
599
|
const inner = translateListInline(parseCommand(cmdText), translation);
|
|
600
|
-
|
|
600
|
+
// Isolate the substitution's execution status in its generated block, so
|
|
601
|
+
// pipeline stage-slot rewriting also covers save/restore. The caller sees
|
|
602
|
+
// its last result through a separate accumulator: assignment-only commands
|
|
603
|
+
// commit it, while commands such as echo retain their own execution status.
|
|
604
|
+
const collected = '$( $fx_cs_output = fx-csub { ' +
|
|
605
|
+
'$fx_cs_saved = $script:fx_exit; $script:fx_exit = 0; try {\n' + inner +
|
|
606
|
+
'\n} finally { $script:fx_csub_exit = $script:fx_exit; $script:fx_exit = $fx_cs_saved }' +
|
|
607
|
+
' }; $fx_prev = [string]$script:fx_csub_exit; $fx_cs_output )';
|
|
601
608
|
if (keepNl)
|
|
602
609
|
return collected;
|
|
603
610
|
return ('((' +
|
|
@@ -623,7 +630,9 @@ export function translateSimple(cmd, position, hasStdin, translation = EXECUTE_T
|
|
|
623
630
|
// deviation: shell var vs exported var are indistinguishable here).
|
|
624
631
|
if (cmd.name === null) {
|
|
625
632
|
const exportHandler = lookup('export');
|
|
626
|
-
|
|
633
|
+
// Reset once for the whole assignment list: a later literal assignment
|
|
634
|
+
// must not erase an earlier substitution's status (x=$(false) y=plain).
|
|
635
|
+
const chunks = ['$script:fx_csub_exit = 0'];
|
|
627
636
|
for (const a of cmd.assignments) {
|
|
628
637
|
if (a.values) {
|
|
629
638
|
chunks.push('fx-arrput ' +
|
|
@@ -638,6 +647,9 @@ export function translateSimple(cmd, position, hasStdin, translation = EXECUTE_T
|
|
|
638
647
|
}
|
|
639
648
|
}
|
|
640
649
|
}
|
|
650
|
+
// Preserve expansion failures; otherwise the last substitution owns the
|
|
651
|
+
// status of a command with no command word. No substitutions means 0.
|
|
652
|
+
chunks.push('if ($script:fx_exit -eq 0) { $script:fx_exit = $script:fx_csub_exit }');
|
|
641
653
|
return chunks.join('\n');
|
|
642
654
|
}
|
|
643
655
|
const nameLit = literalOfWord(cmd.name);
|
|
@@ -719,7 +731,7 @@ export function translateSimple(cmd, position, hasStdin, translation = EXECUTE_T
|
|
|
719
731
|
persistWords.push(w);
|
|
720
732
|
}
|
|
721
733
|
}
|
|
722
|
-
body = wrapTempEnv(cmd.assignments, body, { persistNames, persistWords });
|
|
734
|
+
body = wrapTempEnv(cmd.assignments, body, { persistNames, persistWords, preserveArgumentStatus: true });
|
|
723
735
|
}
|
|
724
736
|
return body;
|
|
725
737
|
}
|
|
@@ -781,6 +793,7 @@ export function wrapTempEnv(sets, body, extra) {
|
|
|
781
793
|
const arrSave = '$fx_ar' + id;
|
|
782
794
|
const keep = persistWords && persistWords.length > 0 ? '$fx_ek' + id : '';
|
|
783
795
|
const lines = [
|
|
796
|
+
...(extra?.preserveArgumentStatus ? ['$fx_eprev' + id + ' = $fx_prev'] : []),
|
|
784
797
|
save + ' = @{}',
|
|
785
798
|
arrSave + ' = @{}',
|
|
786
799
|
'$fx_sv0' + id + ' = $env:FAUXNIX_SETVARS',
|
|
@@ -815,6 +828,11 @@ export function wrapTempEnv(sets, body, extra) {
|
|
|
815
828
|
lines.push(vn + ' = ' + exprOfWord(sets[i].value, { preserveCmdSub: true }));
|
|
816
829
|
}
|
|
817
830
|
}
|
|
831
|
+
// Prefix substitutions may advance $? for later prefix assignments, but
|
|
832
|
+
// their snapshots must not replace the command arguments' incoming status.
|
|
833
|
+
// `env X=... cmd` passes ordinary argv and must keep those updates instead.
|
|
834
|
+
if (extra?.preserveArgumentStatus)
|
|
835
|
+
lines.push('$fx_prev = $fx_eprev' + id);
|
|
818
836
|
lines.push('try {');
|
|
819
837
|
for (const u of unsets) {
|
|
820
838
|
const uq = u.replace(/'/g, "''");
|
|
@@ -990,29 +1008,46 @@ let pipelineSeq = 0;
|
|
|
990
1008
|
*/
|
|
991
1009
|
function translateListInline(list, translation = EXECUTE_TRANSLATION) {
|
|
992
1010
|
const chunks = [];
|
|
993
|
-
|
|
1011
|
+
list.segments.forEach((seg, i) => {
|
|
994
1012
|
const { defs, call } = translatePipelineBody(seg.pipeline, translation);
|
|
995
1013
|
const body = (defs ? defs + '\n' : '') + call;
|
|
1014
|
+
if (i === 0) {
|
|
1015
|
+
chunks.push(body);
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
1018
|
+
// Bash: every completed command updates $?, and the next element's own
|
|
1019
|
+
// &&/|| chain starts fresh (#238). Snapshot the running status into
|
|
1020
|
+
// $fx_prev (the $? source inside a segment — this also preserves the
|
|
1021
|
+
// pre-compound status a body-entry $? reads), then reset the chain
|
|
1022
|
+
// state inside the element's guard so a skipped element cannot clobber
|
|
1023
|
+
// it.
|
|
1024
|
+
const snapshot = '$fx_prev = [string]$script:fx_exit';
|
|
996
1025
|
if (seg.op === '&&') {
|
|
997
|
-
chunks.push('
|
|
1026
|
+
chunks.push(snapshot + '\nif ($script:fx_exit -eq 0) {\n$script:fx_exit = 0\n' + body + '\n}');
|
|
998
1027
|
}
|
|
999
1028
|
else if (seg.op === '||') {
|
|
1000
|
-
chunks.push('
|
|
1029
|
+
chunks.push(snapshot + '\nif ($script:fx_exit -ne 0) {\n$script:fx_exit = 0\n' + body + '\n}');
|
|
1001
1030
|
}
|
|
1002
1031
|
else {
|
|
1003
|
-
chunks.push(body);
|
|
1032
|
+
chunks.push(snapshot + '\n$script:fx_exit = 0\n' + body);
|
|
1004
1033
|
}
|
|
1005
|
-
}
|
|
1034
|
+
});
|
|
1006
1035
|
return chunks.join('\n');
|
|
1007
1036
|
}
|
|
1008
1037
|
function translateIf(cmd, translation) {
|
|
1009
1038
|
// Branch bodies reset fx_exit first: the compound's exit status must come
|
|
1010
1039
|
// from the taken branch's last command (bash semantics), not leak the test's
|
|
1011
1040
|
// failure — `if false; then A; else B; fi` exits 0 in bash.
|
|
1012
|
-
const lines = [
|
|
1041
|
+
const lines = [
|
|
1042
|
+
translateListInline(cmd.test, translation),
|
|
1043
|
+
'if ($script:fx_exit -eq 0) {',
|
|
1044
|
+
// Body-entry $? reads the test's status (bash); then reset the chain.
|
|
1045
|
+
' $fx_prev = [string]$script:fx_exit',
|
|
1046
|
+
' $script:fx_exit = 0',
|
|
1047
|
+
];
|
|
1013
1048
|
for (const l of translateListInline(cmd.then, translation).split('\n'))
|
|
1014
1049
|
lines.push(l ? ' ' + l : l);
|
|
1015
|
-
lines.push('} else {', ' $script:fx_exit = 0');
|
|
1050
|
+
lines.push('} else {', ' $fx_prev = [string]$script:fx_exit', ' $script:fx_exit = 0');
|
|
1016
1051
|
if (cmd.else) {
|
|
1017
1052
|
for (const l of translateListInline(cmd.else, translation).split('\n'))
|
|
1018
1053
|
lines.push(l ? ' ' + l : l);
|
|
@@ -1029,6 +1064,9 @@ function translateCase(cmd, translation) {
|
|
|
1029
1064
|
lines.push(head + ' (fx-casematch $fx_cw @(' + pats + ')) {');
|
|
1030
1065
|
const body = translateListInline(arm.body, translation);
|
|
1031
1066
|
if (body) {
|
|
1067
|
+
// Arm entry starts the body's own chain fresh (#238); an empty arm
|
|
1068
|
+
// keeps the top-of-case 0, matching bash's empty-body case status.
|
|
1069
|
+
lines.push(' $script:fx_exit = 0');
|
|
1032
1070
|
for (const l of body.split('\n'))
|
|
1033
1071
|
lines.push(l ? ' ' + l : l);
|
|
1034
1072
|
}
|
|
@@ -1057,9 +1095,17 @@ function translateFor(cmd, translation) {
|
|
|
1057
1095
|
" $fx_sv += ('" +
|
|
1058
1096
|
n +
|
|
1059
1097
|
"' + [string][char]61 + (fx-svenc ([string]$fx_it))); $env:FAUXNIX_SETVALS = ($fx_sv -join [string][char]10)",
|
|
1098
|
+
// Each iteration starts the body's own chain fresh (#238); the loop's
|
|
1099
|
+
// exit status is still the last command of the final iteration.
|
|
1100
|
+
' $script:fx_exit = 0',
|
|
1060
1101
|
];
|
|
1061
|
-
|
|
1062
|
-
|
|
1102
|
+
lines.push(' try {');
|
|
1103
|
+
for (const l of withLoopBody(() => translateListInline(cmd.body, translation)).split('\n'))
|
|
1104
|
+
lines.push(l ? ' ' + l : l);
|
|
1105
|
+
// Continue exits nested command script blocks before reaching the ordinary
|
|
1106
|
+
// body epilogue. Finally still snapshots its successful status for the next
|
|
1107
|
+
// iteration; the first iteration inherits the caller's snapshot.
|
|
1108
|
+
lines.push(' } finally {', ' $fx_prev = [string]$script:fx_exit', ' }');
|
|
1063
1109
|
lines.push('}');
|
|
1064
1110
|
return lines.join('\n');
|
|
1065
1111
|
}
|
|
@@ -1069,13 +1115,24 @@ function translateWhile(cmd, translation) {
|
|
|
1069
1115
|
// exit 0. Save the body status and restore it on the failing test.
|
|
1070
1116
|
const fail = cmd.until ? '$script:fx_exit -eq 0' : '$script:fx_exit -ne 0';
|
|
1071
1117
|
const lines = ['$fx_wst = 0', 'do {'];
|
|
1072
|
-
|
|
1118
|
+
// The test list re-runs every iteration: start its chain fresh too, or a
|
|
1119
|
+
// failing body status leaks into the next fail-check through handlers that
|
|
1120
|
+
// legitimately emit nothing on success (`true`).
|
|
1121
|
+
lines.push(' $script:fx_exit = 0');
|
|
1122
|
+
for (const l of withLoopBody(() => translateListInline(cmd.test, translation)).split('\n'))
|
|
1073
1123
|
lines.push(l ? ' ' + l : l);
|
|
1074
1124
|
lines.push(' if (' + fail + ') { $script:fx_exit = $fx_wst; break }');
|
|
1125
|
+
// Body-entry $? reads the test's status (bash: the passing while test / the
|
|
1126
|
+
// failing until test), then each iteration's chain starts fresh.
|
|
1127
|
+
lines.push(' $fx_prev = [string]$script:fx_exit');
|
|
1075
1128
|
lines.push(' $script:fx_exit = 0');
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1129
|
+
lines.push(' try {');
|
|
1130
|
+
for (const l of withLoopBody(() => translateListInline(cmd.body, translation)).split('\n'))
|
|
1131
|
+
lines.push(l ? ' ' + l : l);
|
|
1132
|
+
// Continue skips the ordinary body epilogue, including from nested if/case
|
|
1133
|
+
// blocks. Finally records the completed body's status on every exit path,
|
|
1134
|
+
// so the terminating test and the next condition's $? both see it.
|
|
1135
|
+
lines.push(' } finally {', ' $fx_wst = $script:fx_exit', ' $fx_prev = [string]$script:fx_exit', ' }');
|
|
1079
1136
|
lines.push('} while ($true)');
|
|
1080
1137
|
return lines.join('\n');
|
|
1081
1138
|
}
|
|
@@ -1124,6 +1181,46 @@ function rejectNonLastFdRedirects(commands) {
|
|
|
1124
1181
|
}
|
|
1125
1182
|
}
|
|
1126
1183
|
}
|
|
1184
|
+
/** Loop-control translation depth: >0 while translating for/while bodies. */
|
|
1185
|
+
let loopDepth = 0;
|
|
1186
|
+
function withLoopBody(emit) {
|
|
1187
|
+
loopDepth++;
|
|
1188
|
+
try {
|
|
1189
|
+
return emit();
|
|
1190
|
+
}
|
|
1191
|
+
finally {
|
|
1192
|
+
loopDepth--;
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
function isLoopControl(c) {
|
|
1196
|
+
if (c.assignments.length > 0 || c.redirects.length > 0 || c.name === null)
|
|
1197
|
+
return false;
|
|
1198
|
+
const n = wordToString(c.name);
|
|
1199
|
+
return n === 'break' || n === 'continue';
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* `break` / `continue` map to PowerShell loop flow with bash's status-0
|
|
1203
|
+
* semantics (`false; break` leaves the loop at 0). Bare and `break 1` are
|
|
1204
|
+
* supported; deeper N, pipelines, and top-level use fail loud — bash's own
|
|
1205
|
+
* top-level message is a non-fatal diagnostic, but silently aborting the
|
|
1206
|
+
* whole PowerShell script would be worse.
|
|
1207
|
+
*/
|
|
1208
|
+
function translateLoopControl(c, inPipeline) {
|
|
1209
|
+
const name = wordToString(c.name);
|
|
1210
|
+
const argText = c.args.length === 0 ? '' : wordToString(c.args[0]);
|
|
1211
|
+
if (c.args.length > 1 || (c.args.length === 1 && argText !== '1')) {
|
|
1212
|
+
throw new FauxnixParseError(`fauxnix: ${name} ${argText}: breaking more than one loop level is not supported yet`);
|
|
1213
|
+
}
|
|
1214
|
+
if (inPipeline) {
|
|
1215
|
+
throw new FauxnixParseError(`fauxnix: ${name} in a pipeline is not supported yet`);
|
|
1216
|
+
}
|
|
1217
|
+
if (loopDepth === 0) {
|
|
1218
|
+
return ("[Console]::Error.WriteLine('bash: " +
|
|
1219
|
+
name +
|
|
1220
|
+
": only meaningful in a for, while, or until loop'); $script:fx_exit = 0");
|
|
1221
|
+
}
|
|
1222
|
+
return '$script:fx_exit = 0\n' + name;
|
|
1223
|
+
}
|
|
1127
1224
|
export function translatePipelineBody(p, translation = EXECUTE_TRANSLATION) {
|
|
1128
1225
|
if (translation.mode === 'pure') {
|
|
1129
1226
|
for (const command of p.commands)
|
|
@@ -1152,6 +1249,8 @@ export function translatePipelineBody(p, translation = EXECUTE_TRANSLATION) {
|
|
|
1152
1249
|
bodies.push(translateWhile(c, translation));
|
|
1153
1250
|
else if (c.kind === 'Case')
|
|
1154
1251
|
bodies.push(translateCase(c, translation));
|
|
1252
|
+
else if (isLoopControl(c))
|
|
1253
|
+
bodies.push(translateLoopControl(c, p.commands.length > 1));
|
|
1155
1254
|
else
|
|
1156
1255
|
bodies.push(translateSimple(c, position, hasStdin, translation));
|
|
1157
1256
|
}
|