brsh 2.2.1 → 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.
@@ -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);
@@ -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
 
@@ -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.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
+ });