brsh 2.2.0 → 2.3.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.
@@ -17,7 +17,14 @@ class ScriptCommand extends LocalCommand {
17
17
  this.source = source;
18
18
  }
19
19
 
20
- get captureInput() { return true; }
20
+ // Only capture input when the sandbox itself has a command waiting for it
21
+ // (e.g. an active `read`). This prevents swallowing keystrokes during
22
+ // normal command execution.
23
+ get captureInput() {
24
+ return !!(this.sandbox
25
+ && this.sandbox.runningCommand
26
+ && this.sandbox.runningCommand.captureInput);
27
+ }
21
28
 
22
29
  onInput(char) {
23
30
  if (this.sandbox) {
@@ -35,8 +42,8 @@ class ScriptCommand extends LocalCommand {
35
42
  });
36
43
  this.sandbox.context.source(this.context);
37
44
 
38
- this.sandbox.on('stdOut', data => this.stdOut = data);
39
- this.sandbox.on('stdErr', data => this.stdErr = data);
45
+ this.sandbox.on('stdOut', data => { this.stdOut = data; this.flush(); });
46
+ this.sandbox.on('stdErr', data => { this.stdErr = data; this.flush(); });
40
47
 
41
48
  this._scriptFunctions = {};
42
49
 
@@ -54,6 +61,8 @@ class ScriptCommand extends LocalCommand {
54
61
  .catch(e => {
55
62
  if (e && e.__type === 'return') {
56
63
  this.sandbox.lastCode = e.code;
64
+ } else if (e && e.__type === 'errexit') {
65
+ this.sandbox.lastCode = e.code;
57
66
  } else {
58
67
  return Promise.reject(e);
59
68
  }
@@ -110,50 +119,51 @@ class ScriptCommand extends LocalCommand {
110
119
  }
111
120
 
112
121
  _parseIf(lines, start) {
113
- let condition = lines[start].trim()
114
- .replace(/^if\s+/, '')
122
+ const parseCondition = str => str
123
+ .replace(/^(?:if|elif)\s+/, '')
115
124
  .replace(/\s*;\s*then\s*$/, '')
116
125
  .replace(/\s+then\s*$/, '')
117
126
  .trim();
118
127
 
128
+ const clauses = [{ condition: parseCondition(lines[start].trim()), bodyLines: [] }];
129
+ const elseLines = [];
130
+ let currentClause = clauses[0];
131
+ let inElse = false;
132
+ let depth = 1;
133
+
119
134
  let i = start + 1;
120
135
  if (i < lines.length && lines[i].trim() === 'then') i++;
121
136
 
122
- const thenLines = [], elseLines = [];
123
- let inElse = false, inElif = false;
124
- let depth = 1;
125
-
126
137
  while (i < lines.length) {
127
138
  const line = lines[i].trim();
128
139
 
129
- if (line.startsWith('if ')) depth++;
140
+ if (line.startsWith('if ') || line === 'if') depth++;
130
141
 
131
142
  if (line === 'fi') {
132
143
  depth--;
133
- if (depth === 0) {
134
- if (inElif) elseLines.push('fi');
135
- i++; break;
136
- }
144
+ if (depth === 0) { i++; break; }
137
145
  }
138
146
 
139
- if (depth === 1 && (line === 'else' || line.startsWith('elif '))) {
140
- if (!inElse) inElse = true;
141
- if (line.startsWith('elif ')) {
142
- inElif = true;
143
- elseLines.push(line.replace(/^elif/, 'if'));
144
- } else if (inElif) {
145
- // 'else' after an elif belongs to the inner if
146
- elseLines.push(lines[i]);
147
- }
147
+ if (depth === 1 && line.startsWith('elif ')) {
148
+ const newClause = { condition: parseCondition(line), bodyLines: [] };
149
+ clauses.push(newClause);
150
+ currentClause = newClause;
151
+ i++;
152
+ if (i < lines.length && lines[i].trim() === 'then') i++;
153
+ continue;
154
+ }
155
+
156
+ if (depth === 1 && line === 'else') {
157
+ inElse = true;
148
158
  i++; continue;
149
159
  }
150
160
 
151
161
  if (inElse) elseLines.push(lines[i]);
152
- else thenLines.push(lines[i]);
162
+ else currentClause.bodyLines.push(lines[i]);
153
163
  i++;
154
164
  }
155
165
 
156
- return { node: { type: 'if', condition, thenLines, elseLines }, consumed: i - start };
166
+ return { node: { type: 'if', clauses, elseLines }, consumed: i - start };
157
167
  }
158
168
 
159
169
  _parseWhile(lines, start) {
@@ -226,13 +236,26 @@ class ScriptCommand extends LocalCommand {
226
236
  const FuncCmd = class extends LocalCmdBase {
227
237
  static get name() { return funcName; }
228
238
  run() {
229
- return self._executeFunctionBody(funcBody).catch(e => {
230
- if (e && e.__type === 'return') {
231
- this.exitCode = e.code;
232
- return;
233
- }
234
- return Promise.reject(e);
235
- });
239
+ // Set positional parameters ($1, $2, ...) from call arguments
240
+ const saved = this.arguments.map((arg, i) => ({
241
+ key: String(i + 1),
242
+ prev: self.sandbox.context.getVar(String(i + 1))
243
+ }));
244
+ this.arguments.forEach((arg, i) =>
245
+ self.sandbox.context.setVar(String(i + 1), arg));
246
+ const restore = () => saved.forEach(({ key, prev }) =>
247
+ prev ? self.sandbox.context.setVar(key, prev)
248
+ : self.sandbox.context.unsetVar(key));
249
+ return self._executeFunctionBody(funcBody)
250
+ .then(() => { restore(); })
251
+ .catch(e => {
252
+ restore();
253
+ if (e && e.__type === 'return') {
254
+ this.exitCode = e.code;
255
+ return;
256
+ }
257
+ return Promise.reject(e);
258
+ });
236
259
  }
237
260
  };
238
261
  this.sandbox.context.setCommand(FuncCmd);
@@ -245,7 +268,19 @@ class ScriptCommand extends LocalCommand {
245
268
  const code = match ? parseInt(match[1], 10) : 0;
246
269
  return Promise.reject({ __type: 'return', code });
247
270
  }
248
- return this.sandbox.onCommand(node.line, false);
271
+ // xtrace (-x): print each command to stderr before executing
272
+ const flags = this.sandbox.context.getVar('-') || '';
273
+ if (flags.includes('x')) {
274
+ this.stdErr = `+ ${node.line.trim()}`;
275
+ this.flush();
276
+ }
277
+ return this.sandbox.onCommand(node.line, false).then(() => {
278
+ // errexit (-e): abort script on non-zero exit
279
+ const currentFlags = this.sandbox.context.getVar('-') || '';
280
+ if (currentFlags.includes('e') && this.sandbox.lastCode !== 0) {
281
+ return Promise.reject({ __type: 'errexit', code: this.sandbox.lastCode });
282
+ }
283
+ });
249
284
  }
250
285
  if (node.type === 'if') return this._executeIf(node);
251
286
  if (node.type === 'while') return this._executeWhile(node);
@@ -255,13 +290,21 @@ class ScriptCommand extends LocalCommand {
255
290
  }
256
291
 
257
292
  _executeIf(node) {
258
- return this.sandbox.onCommand(node.condition, false).then(() => {
259
- if (this.sandbox.lastCode === 0) {
260
- return this._executeNodes(this._parseLines(node.thenLines));
261
- } else if (node.elseLines.length > 0) {
262
- return this._executeNodes(this._parseLines(node.elseLines));
293
+ const tryClause = (i) => {
294
+ if (i >= node.clauses.length) {
295
+ return node.elseLines.length > 0
296
+ ? this._executeNodes(this._parseLines(node.elseLines))
297
+ : Promise.resolve();
263
298
  }
264
- });
299
+ const clause = node.clauses[i];
300
+ return this.sandbox.onCommand(clause.condition, false).then(() => {
301
+ if (this.sandbox.lastCode === 0) {
302
+ return this._executeNodes(this._parseLines(clause.bodyLines));
303
+ }
304
+ return tryClause(i + 1);
305
+ });
306
+ };
307
+ return tryClause(0);
265
308
  }
266
309
 
267
310
  _executeWhile(node) {
@@ -16,6 +16,7 @@ module.exports = [
16
16
  require('./exit'),
17
17
  require('./read'),
18
18
  require('./jsfunction'),
19
- require('./curl')
19
+ require('./curl'),
20
+ require('./set')
20
21
  ];
21
22
 
package/lib/local/read.js CHANGED
@@ -58,6 +58,16 @@ class Read extends LocalCommand {
58
58
  this.inputBuffer += key;
59
59
  }
60
60
 
61
+ if (key === 'Enter') {
62
+ if (this.var) {
63
+ this.context.setVar(this.var, this.inputBuffer || '');
64
+ this.completionCallback();
65
+ } else {
66
+ this.completionCallback(this.inputBuffer || '');
67
+ }
68
+ return;
69
+ }
70
+
61
71
  if(this.inputBuffer.length === this.nchars) {
62
72
  if(this.var) {
63
73
  this.context.setVar(this.var, this.inputBuffer)
@@ -0,0 +1,102 @@
1
+ 'use strict';
2
+
3
+ const LocalCommand = require('./LocalCommand');
4
+
5
+ // Mapping of -o option names to single-letter flags
6
+ const NAMED_FLAGS = {
7
+ errexit: 'e',
8
+ xtrace: 'x',
9
+ nounset: 'u',
10
+ noexec: 'n',
11
+ allexport: 'a',
12
+ };
13
+
14
+ class Set extends LocalCommand {
15
+ static get name() { return 'set'; }
16
+
17
+ run() {
18
+ const args = this.arguments;
19
+
20
+ // `set` with no arguments: print all variables sorted
21
+ if (args.length === 0) {
22
+ const vars = this.context.vars;
23
+ Object.keys(vars).sort().forEach(key => {
24
+ this.stdOut = `${key}=${vars[key]}`;
25
+ });
26
+ return Promise.resolve();
27
+ }
28
+
29
+ let i = 0;
30
+ while (i < args.length) {
31
+ const arg = args[i];
32
+
33
+ // `set -- [arg1 arg2 ...]`: replace positional parameters
34
+ if (arg === '--') {
35
+ const positional = args.slice(i + 1);
36
+ // Clear existing positional params
37
+ let n = 1;
38
+ while (this.context.getVar(String(n))) {
39
+ this.context.unsetVar(String(n));
40
+ n++;
41
+ }
42
+ // Set new ones
43
+ positional.forEach((val, idx) =>
44
+ this.context.setVar(String(idx + 1), val));
45
+ this.context.setVar('#', String(positional.length));
46
+ return Promise.resolve();
47
+ }
48
+
49
+ // Flag modifier: -xyz sets flags, +xyz clears flags
50
+ if ((arg.startsWith('-') || arg.startsWith('+')) && arg.length > 1 && arg[1] !== '-') {
51
+ const enabling = arg[0] === '-';
52
+ const flagStr = arg.slice(1);
53
+
54
+ // `set -o [option]` / `set +o [option]`
55
+ if (flagStr === 'o') {
56
+ i++;
57
+ const optionName = args[i];
58
+ if (optionName === undefined) {
59
+ // `set -o` with no name: list all options
60
+ Object.entries(NAMED_FLAGS).forEach(([name, char]) => {
61
+ const current = this.context.getVar('-') || '';
62
+ this.stdOut = `${name.padEnd(15)} ${current.includes(char) ? 'on' : 'off'}`;
63
+ });
64
+ i++;
65
+ continue;
66
+ }
67
+ const flagChar = NAMED_FLAGS[optionName];
68
+ if (flagChar) {
69
+ this._setFlag(flagChar, enabling);
70
+ } else {
71
+ this.stdErr = `set: ${optionName}: invalid option name`;
72
+ }
73
+ i++;
74
+ continue;
75
+ }
76
+
77
+ for (const flag of flagStr) {
78
+ this._setFlag(flag, enabling);
79
+ }
80
+ i++;
81
+ continue;
82
+ }
83
+
84
+ i++;
85
+ }
86
+
87
+ return Promise.resolve();
88
+ }
89
+
90
+ _setFlag(flag, enabled) {
91
+ const current = this.context.getVar('-') || '';
92
+ if (enabled) {
93
+ if (!current.includes(flag)) {
94
+ this.context.setVar('-', current + flag);
95
+ }
96
+ } else {
97
+ this.context.setVar('-', current.split('').filter(c => c !== flag).join(''));
98
+ }
99
+ }
100
+ }
101
+
102
+ module.exports = Set;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
4
4
  "description": "A unix like shell written in javascript",
5
5
  "main": "./dist/shell.min.js",
6
6
  "module": "./dist/shell.es.js",
@@ -602,3 +602,67 @@ describe('jsfunction', () => {
602
602
  expect(output).toContain('10');
603
603
  });
604
604
  });
605
+
606
+ describe('set', () => {
607
+ let shell;
608
+ beforeEach(async () => { shell = await createShell(); });
609
+
610
+ it('prints all variables with no arguments', async () => {
611
+ await shell.onCommand('export TESTVAR=hello');
612
+ const { output } = await run(shell, 'set');
613
+ expect(output.join('\n')).toMatch(/TESTVAR=hello/);
614
+ });
615
+
616
+ it('sets a flag with -e', async () => {
617
+ await shell.onCommand('set -e');
618
+ expect(shell.context.getVar('-')).toContain('e');
619
+ });
620
+
621
+ it('clears a flag with +e', async () => {
622
+ await shell.onCommand('set -e');
623
+ await shell.onCommand('set +e');
624
+ expect(shell.context.getVar('-')).not.toContain('e');
625
+ });
626
+
627
+ it('sets multiple flags at once', async () => {
628
+ await shell.onCommand('set -ex');
629
+ const flags = shell.context.getVar('-');
630
+ expect(flags).toContain('e');
631
+ expect(flags).toContain('x');
632
+ });
633
+
634
+ it('set -- replaces positional parameters', async () => {
635
+ await shell.onCommand('set -- alpha beta gamma');
636
+ expect(shell.context.getVar('1')).toBe('alpha');
637
+ expect(shell.context.getVar('2')).toBe('beta');
638
+ expect(shell.context.getVar('3')).toBe('gamma');
639
+ expect(shell.context.getVar('#')).toBe('3');
640
+ });
641
+
642
+ it('set -- with no args clears positional parameters', async () => {
643
+ await shell.onCommand('set -- alpha beta');
644
+ await shell.onCommand('set --');
645
+ expect(shell.context.getVar('1')).toBe('');
646
+ expect(shell.context.getVar('#')).toBe('0');
647
+ });
648
+
649
+ it('-e in a script stops execution after a failing command', async () => {
650
+ const scriptShell = await createShell({
651
+ filesystem: { scripts: { 'errexit.sh': '#!/sh.js\nset -e\necho before\nfalse\necho after' } },
652
+ permissions: { '/scripts/errexit.sh': 0o755 }
653
+ });
654
+ const { output } = await run(scriptShell, '/scripts/errexit.sh');
655
+ expect(output).toContain('before');
656
+ expect(output).not.toContain('after');
657
+ });
658
+
659
+ it('-x in a script traces commands to stderr', async () => {
660
+ const scriptShell = await createShell({
661
+ filesystem: { scripts: { 'xtrace.sh': '#!/sh.js\nset -x\necho hello' } },
662
+ permissions: { '/scripts/xtrace.sh': 0o755 }
663
+ });
664
+ const { errors, output } = await run(scriptShell, '/scripts/xtrace.sh');
665
+ expect(errors.join('\n')).toContain('+ echo hello');
666
+ expect(output).toContain('hello');
667
+ });
668
+ });