brsh 2.2.1 → 2.4.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.
package/index.js CHANGED
@@ -102,9 +102,10 @@ class Shell extends EventEmitter {
102
102
 
103
103
  onCommand(raw, events = true) {
104
104
  const segments = this._splitInput(raw);
105
+ const groups = this._groupPipes(segments);
105
106
  let shouldRun = true;
106
107
 
107
- const promise = segments.reduce((chain, { command, op }) => {
108
+ const promise = groups.reduce((chain, { commands, op }) => {
108
109
  return chain.then(() => {
109
110
  if (!shouldRun) {
110
111
  if (op === '&&') shouldRun = this._lastCode === 0;
@@ -112,7 +113,7 @@ class Shell extends EventEmitter {
112
113
  else if (op === ';') shouldRun = true;
113
114
  return;
114
115
  }
115
- return this._runCommand(command).then(() => {
116
+ return this._runPipeChain(commands).then(() => {
116
117
  if (op === '&&') shouldRun = this._lastCode === 0;
117
118
  else if (op === '||') shouldRun = this._lastCode !== 0;
118
119
  else if (op === ';') shouldRun = true;
@@ -318,6 +319,10 @@ class Shell extends EventEmitter {
318
319
  segments.push({ command: current.trim(), op: '||' });
319
320
  current = ''; i += 2; continue;
320
321
  }
322
+ if (ch === '|') {
323
+ segments.push({ command: current.trim(), op: '|' });
324
+ current = ''; i++; continue;
325
+ }
321
326
  if (ch === ';') {
322
327
  segments.push({ command: current.trim(), op: ';' });
323
328
  current = ''; i++; continue;
@@ -464,6 +469,56 @@ class Shell extends EventEmitter {
464
469
  return lines.join('\n').trimEnd();
465
470
  }
466
471
 
472
+ _groupPipes(segments) {
473
+ const groups = [];
474
+ let commands = [];
475
+ for (const { command, op } of segments) {
476
+ commands.push(command);
477
+ if (op !== '|') {
478
+ groups.push({ commands, op });
479
+ commands = [];
480
+ }
481
+ }
482
+ if (commands.length) groups.push({ commands, op: null });
483
+ return groups;
484
+ }
485
+
486
+ async _runPipeChain(commands) {
487
+ if (commands.length === 1) {
488
+ return this._runCommand(commands[0]);
489
+ }
490
+ let stdinData = undefined;
491
+ for (let i = 0; i < commands.length; i++) {
492
+ const isLast = i === commands.length - 1;
493
+ if (isLast) {
494
+ if (stdinData !== undefined) this._stdin = stdinData;
495
+ try {
496
+ await this._runCommand(commands[i]);
497
+ } finally {
498
+ delete this._stdin;
499
+ }
500
+ } else {
501
+ stdinData = await this._captureForPipe(commands[i], stdinData);
502
+ }
503
+ }
504
+ }
505
+
506
+ async _captureForPipe(cmd, stdin) {
507
+ const subshell = new global.shell({
508
+ cwd: this.context.fs.cwd,
509
+ filesystem: this.context.fs.getRaw(),
510
+ permissions: this.context.fs.getRawPermissions()
511
+ });
512
+ subshell.context.source(this.context);
513
+ if (stdin !== undefined) subshell.stdin = stdin;
514
+ const lines = [];
515
+ subshell.on('stdOut', line => lines.push(line));
516
+ subshell.on('stdErr', line => this.emit('stdErr', line));
517
+ await subshell.onCommand(cmd, false);
518
+ this.lastCode = subshell.lastCode;
519
+ return lines.join('\n');
520
+ }
521
+
467
522
  // Returns Array<{value: string, hasQuote: boolean}>.
468
523
  // hasQuote=true means the token contained an explicit quoted segment (even empty ""),
469
524
  // which must be preserved even if the final value is an empty string.
@@ -61,6 +61,8 @@ class ScriptCommand extends LocalCommand {
61
61
  .catch(e => {
62
62
  if (e && e.__type === 'return') {
63
63
  this.sandbox.lastCode = e.code;
64
+ } else if (e && e.__type === 'errexit') {
65
+ this.sandbox.lastCode = e.code;
64
66
  } else {
65
67
  return Promise.reject(e);
66
68
  }
@@ -266,7 +268,19 @@ class ScriptCommand extends LocalCommand {
266
268
  const code = match ? parseInt(match[1], 10) : 0;
267
269
  return Promise.reject({ __type: 'return', code });
268
270
  }
269
- 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
+ });
270
284
  }
271
285
  if (node.type === 'if') return this._executeIf(node);
272
286
  if (node.type === 'while') return this._executeWhile(node);
@@ -0,0 +1,9 @@
1
+ 'use strict';
2
+
3
+ const Source = require('./source');
4
+
5
+ class Dot extends Source {
6
+ static get name() { return '.'; }
7
+ }
8
+
9
+ module.exports = Dot;
@@ -16,6 +16,8 @@ module.exports = [
16
16
  require('./exit'),
17
17
  require('./read'),
18
18
  require('./jsfunction'),
19
- require('./curl')
19
+ require('./curl'),
20
+ require('./set'),
21
+ require('./dot')
20
22
  ];
21
23
 
@@ -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.1",
3
+ "version": "2.4.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
+ });
@@ -285,3 +285,53 @@ describe('tabCompletion', () => {
285
285
  expect(result.options).toContain('mydir/');
286
286
  });
287
287
  });
288
+
289
+ describe('Pipes', () => {
290
+ let shell;
291
+ beforeEach(async () => { shell = await createShell(); });
292
+
293
+ it('pipes stdout of first command to stdin of second', async () => {
294
+ const { output } = await run(shell, 'echo hello world | cat');
295
+ expect(output.join('\n')).toContain('hello world');
296
+ });
297
+
298
+ it('filters output through grep via pipe', async () => {
299
+ const { output } = await run(shell, 'echo -e "foo\nbar\nbaz" | grep bar');
300
+ expect(output.join('\n')).toContain('bar');
301
+ expect(output.join('\n')).not.toContain('foo');
302
+ });
303
+
304
+ it('supports chaining three commands', async () => {
305
+ const { output } = await run(shell, 'echo -e "alpha\nbeta\nalpha" | grep alpha | cat');
306
+ const joined = output.join('\n');
307
+ expect(joined).toContain('alpha');
308
+ expect(joined).not.toContain('beta');
309
+ });
310
+
311
+ it('sets exit code from the last command in the pipe', async () => {
312
+ const { exitCode } = await run(shell, 'echo hello | grep nomatch');
313
+ expect(exitCode).toBe(1);
314
+ });
315
+
316
+ it('does not confuse || with |', async () => {
317
+ await shell.onCommand('export X=0');
318
+ const { output } = await run(shell, 'false || echo fallback');
319
+ expect(output.join('\n')).toContain('fallback');
320
+ });
321
+ });
322
+
323
+ describe('. (dot) command', () => {
324
+ it('is an alias for source and executes a script file', async () => {
325
+ const shell = await createShell({
326
+ filesystem: {
327
+ bin: {},
328
+ home: {
329
+ 'greet.sh': '#!/bin/sh\nexport GREETED=yes\n'
330
+ }
331
+ }
332
+ });
333
+ await shell.onCommand('cd /home');
334
+ await shell.onCommand('. /home/greet.sh');
335
+ expect(shell.context.getVar('GREETED')).toBe('yes');
336
+ });
337
+ });