brsh 2.3.0 → 2.4.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/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;
@@ -439,7 +444,11 @@ class Shell extends EventEmitter {
439
444
  }
440
445
 
441
446
  _evalArithmetic(expr) {
442
- const expanded = expr.replace(/\${?([\w\d]+)}?/g, (m, name) =>
447
+ // First expand $VAR and ${VAR} references
448
+ let expanded = expr.replace(/\${?([\w\d]+)}?/g, (m, name) =>
449
+ String(parseInt(this.context.getVar(name)) || 0));
450
+ // Then expand bare variable names (e.g. I in $((I+1)))
451
+ expanded = expanded.replace(/\b([A-Za-z_]\w*)\b/g, (m, name) =>
443
452
  String(parseInt(this.context.getVar(name)) || 0));
444
453
  if (!/^[\d\s+\-*/%()]+$/.test(expanded.trim())) return 0;
445
454
  try {
@@ -464,6 +473,56 @@ class Shell extends EventEmitter {
464
473
  return lines.join('\n').trimEnd();
465
474
  }
466
475
 
476
+ _groupPipes(segments) {
477
+ const groups = [];
478
+ let commands = [];
479
+ for (const { command, op } of segments) {
480
+ commands.push(command);
481
+ if (op !== '|') {
482
+ groups.push({ commands, op });
483
+ commands = [];
484
+ }
485
+ }
486
+ if (commands.length) groups.push({ commands, op: null });
487
+ return groups;
488
+ }
489
+
490
+ async _runPipeChain(commands) {
491
+ if (commands.length === 1) {
492
+ return this._runCommand(commands[0]);
493
+ }
494
+ let stdinData = undefined;
495
+ for (let i = 0; i < commands.length; i++) {
496
+ const isLast = i === commands.length - 1;
497
+ if (isLast) {
498
+ if (stdinData !== undefined) this._stdin = stdinData;
499
+ try {
500
+ await this._runCommand(commands[i]);
501
+ } finally {
502
+ delete this._stdin;
503
+ }
504
+ } else {
505
+ stdinData = await this._captureForPipe(commands[i], stdinData);
506
+ }
507
+ }
508
+ }
509
+
510
+ async _captureForPipe(cmd, stdin) {
511
+ const subshell = new global.shell({
512
+ cwd: this.context.fs.cwd,
513
+ filesystem: this.context.fs.getRaw(),
514
+ permissions: this.context.fs.getRawPermissions()
515
+ });
516
+ subshell.context.source(this.context);
517
+ if (stdin !== undefined) subshell.stdin = stdin;
518
+ const lines = [];
519
+ subshell.on('stdOut', line => lines.push(line));
520
+ subshell.on('stdErr', line => this.emit('stdErr', line));
521
+ await subshell.onCommand(cmd, false);
522
+ this.lastCode = subshell.lastCode;
523
+ return lines.join('\n');
524
+ }
525
+
467
526
  // Returns Array<{value: string, hasQuote: boolean}>.
468
527
  // hasQuote=true means the token contained an explicit quoted segment (even empty ""),
469
528
  // which must be preserved even if the final value is an empty string.
package/lib/Command.js CHANGED
@@ -29,6 +29,12 @@ class Command extends EventEmitter {
29
29
  return this.result;
30
30
  })
31
31
  .catch(e => {
32
+ // Re-throw shell control-flow signals (break, continue, return,
33
+ // errexit) so they propagate correctly through function calls
34
+ // and nested script execution.
35
+ if (e && e.__type) {
36
+ throw e;
37
+ }
32
38
  if(e) {
33
39
  this.stdErr = e.message || e;
34
40
  }
@@ -63,6 +63,9 @@ class ScriptCommand extends LocalCommand {
63
63
  this.sandbox.lastCode = e.code;
64
64
  } else if (e && e.__type === 'errexit') {
65
65
  this.sandbox.lastCode = e.code;
66
+ } else if (e && (e.__type === 'break' || e.__type === 'continue')) {
67
+ this.stdErr = `${e.__type}: only meaningful in a for or while loop`;
68
+ this.sandbox.lastCode = 1;
66
69
  } else {
67
70
  return Promise.reject(e);
68
71
  }
@@ -221,10 +224,10 @@ class ScriptCommand extends LocalCommand {
221
224
  return { node: { type: 'for', variable, list, bodyLines }, consumed: i - start };
222
225
  }
223
226
 
224
- _executeNodes(nodes) {
225
- return nodes.reduce((chain, node) => {
226
- return chain.then(() => this._executeNode(node));
227
- }, Promise.resolve());
227
+ async _executeNodes(nodes) {
228
+ for (const node of nodes) {
229
+ await this._executeNode(node);
230
+ }
228
231
  }
229
232
 
230
233
  _executeNode(node) {
@@ -268,6 +271,17 @@ class ScriptCommand extends LocalCommand {
268
271
  const code = match ? parseInt(match[1], 10) : 0;
269
272
  return Promise.reject({ __type: 'return', code });
270
273
  }
274
+ // Intercept 'break [n]' and 'continue [n]' loop control signals
275
+ if (/^break(\s+\d+)?\s*$/.test(node.line.trim())) {
276
+ const match = node.line.trim().match(/^break\s+(\d+)/);
277
+ const count = match ? parseInt(match[1], 10) : 1;
278
+ return Promise.reject({ __type: 'break', count });
279
+ }
280
+ if (/^continue(\s+\d+)?\s*$/.test(node.line.trim())) {
281
+ const match = node.line.trim().match(/^continue\s+(\d+)/);
282
+ const count = match ? parseInt(match[1], 10) : 1;
283
+ return Promise.reject({ __type: 'continue', count });
284
+ }
271
285
  // xtrace (-x): print each command to stderr before executing
272
286
  const flags = this.sandbox.context.getVar('-') || '';
273
287
  if (flags.includes('x')) {
@@ -289,43 +303,58 @@ class ScriptCommand extends LocalCommand {
289
303
  return Promise.resolve();
290
304
  }
291
305
 
292
- _executeIf(node) {
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();
306
+ async _executeIf(node) {
307
+ for (const clause of node.clauses) {
308
+ await this.sandbox.onCommand(clause.condition, false);
309
+ if (this.sandbox.lastCode === 0) {
310
+ return this._executeNodes(this._parseLines(clause.bodyLines));
298
311
  }
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);
312
+ }
313
+ if (node.elseLines.length > 0) {
314
+ return this._executeNodes(this._parseLines(node.elseLines));
315
+ }
308
316
  }
309
317
 
310
- _executeWhile(node) {
311
- const step = () => this.sandbox.onCommand(node.condition, false).then(() => {
312
- if (this.sandbox.lastCode === 0) {
313
- return this._executeNodes(this._parseLines(node.bodyLines)).then(step);
318
+ async _executeWhile(node) {
319
+ while (true) {
320
+ await this.sandbox.onCommand(node.condition, false);
321
+ if (this.sandbox.lastCode !== 0) break;
322
+ try {
323
+ await this._executeNodes(this._parseLines(node.bodyLines));
324
+ } catch (e) {
325
+ if (e && e.__type === 'break') {
326
+ if (e.count <= 1) break;
327
+ throw { __type: 'break', count: e.count - 1 };
328
+ }
329
+ if (e && e.__type === 'continue') {
330
+ if (e.count <= 1) continue;
331
+ throw { __type: 'continue', count: e.count - 1 };
332
+ }
333
+ throw e;
314
334
  }
315
- });
316
- return step();
335
+ }
317
336
  }
318
337
 
319
- _executeFor(node) {
338
+ async _executeFor(node) {
320
339
  const expanded = node.list.replace(/\${?([\w\d]+)}?/g, (m, name) =>
321
340
  this.sandbox.context.getVar(name) || '');
322
341
  const items = expanded.split(/\s+/).filter(Boolean);
323
- return items.reduce((chain, value) => {
324
- return chain.then(() => {
325
- this.sandbox.context.setVar(node.variable, value);
326
- return this._executeNodes(this._parseLines(node.bodyLines));
327
- });
328
- }, Promise.resolve());
342
+ for (const value of items) {
343
+ this.sandbox.context.setVar(node.variable, value);
344
+ try {
345
+ await this._executeNodes(this._parseLines(node.bodyLines));
346
+ } catch (e) {
347
+ if (e && e.__type === 'break') {
348
+ if (e.count <= 1) break;
349
+ throw { __type: 'break', count: e.count - 1 };
350
+ }
351
+ if (e && e.__type === 'continue') {
352
+ if (e.count <= 1) continue;
353
+ throw { __type: 'continue', count: e.count - 1 };
354
+ }
355
+ throw e;
356
+ }
357
+ }
329
358
  }
330
359
 
331
360
  _parseFunction(lines, start) {
@@ -421,19 +450,18 @@ class ScriptCommand extends LocalCommand {
421
450
  return this._executeNodes(this._parseLines(bodyLines));
422
451
  }
423
452
 
424
- _executeCase(node) {
425
- return this.sandbox._replaceVariables(node.word).then(expanded => {
426
- // Strip outer quotes produced by variable expansion
427
- const value = ((expanded.startsWith('"') && expanded.endsWith('"'))
428
- || (expanded.startsWith("'") && expanded.endsWith("'")))
429
- ? expanded.slice(1, -1) : expanded;
453
+ async _executeCase(node) {
454
+ const expanded = await this.sandbox._replaceVariables(node.word);
455
+ // Strip outer quotes produced by variable expansion
456
+ const value = ((expanded.startsWith('"') && expanded.endsWith('"'))
457
+ || (expanded.startsWith("'") && expanded.endsWith("'")))
458
+ ? expanded.slice(1, -1) : expanded;
430
459
 
431
- for (const clause of node.clauses) {
432
- if (this._matchPattern(clause.pattern, value)) {
433
- return this._executeNodes(this._parseLines(clause.bodyLines));
434
- }
460
+ for (const clause of node.clauses) {
461
+ if (this._matchPattern(clause.pattern, value)) {
462
+ return this._executeNodes(this._parseLines(clause.bodyLines));
435
463
  }
436
- });
464
+ }
437
465
  }
438
466
 
439
467
  _matchPattern(pattern, value) {
@@ -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;
@@ -17,6 +17,7 @@ module.exports = [
17
17
  require('./read'),
18
18
  require('./jsfunction'),
19
19
  require('./curl'),
20
- require('./set')
20
+ require('./set'),
21
+ require('./dot')
21
22
  ];
22
23
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "2.3.0",
3
+ "version": "2.4.1",
4
4
  "description": "A unix like shell written in javascript",
5
5
  "main": "./dist/shell.min.js",
6
6
  "module": "./dist/shell.es.js",
@@ -332,3 +332,94 @@ describe('for loop', () => {
332
332
  expect(output).toContain('2y');
333
333
  });
334
334
  });
335
+
336
+ describe('break and continue', () => {
337
+ let shell;
338
+
339
+ beforeEach(async () => {
340
+ shell = await createShell({
341
+ filesystem: {
342
+ scripts: {
343
+ 'while-break.sh': '#!/sh.js\nI=0\nwhile true; do\nI=$((I+1))\nif [ $I -eq 3 ]; then\nbreak\nfi\necho $I\ndone\necho done',
344
+ 'for-break.sh': '#!/sh.js\nfor x in a b c d; do\nif [ $x = c ]; then\nbreak\nfi\necho $x\ndone\necho end',
345
+ 'for-continue.sh': '#!/sh.js\nfor x in 1 2 3 4 5; do\nif [ $x = 3 ]; then\ncontinue\nfi\necho $x\ndone',
346
+ 'nested-break.sh': '#!/sh.js\nfor a in 1 2; do\nfor b in x y z; do\nif [ $b = y ]; then\nbreak\nfi\necho $a$b\ndone\ndone',
347
+ }
348
+ },
349
+ permissions: execPerms(
350
+ '/scripts/while-break.sh',
351
+ '/scripts/for-break.sh',
352
+ '/scripts/for-continue.sh',
353
+ '/scripts/nested-break.sh'
354
+ )
355
+ });
356
+ });
357
+
358
+ it('break exits a while loop early', async () => {
359
+ const { output } = await run(shell, '/scripts/while-break.sh');
360
+ expect(output).toContain('1');
361
+ expect(output).toContain('2');
362
+ expect(output).not.toContain('3');
363
+ expect(output).toContain('done');
364
+ });
365
+
366
+ it('break exits a for loop early', async () => {
367
+ const { output } = await run(shell, '/scripts/for-break.sh');
368
+ expect(output).toContain('a');
369
+ expect(output).toContain('b');
370
+ expect(output).not.toContain('c');
371
+ expect(output).not.toContain('d');
372
+ expect(output).toContain('end');
373
+ });
374
+
375
+ it('continue skips the current iteration', async () => {
376
+ const { output } = await run(shell, '/scripts/for-continue.sh');
377
+ expect(output).toContain('1');
378
+ expect(output).toContain('2');
379
+ expect(output).not.toContain('3');
380
+ expect(output).toContain('4');
381
+ expect(output).toContain('5');
382
+ });
383
+
384
+ it('break only exits the innermost loop', async () => {
385
+ const { output } = await run(shell, '/scripts/nested-break.sh');
386
+ expect(output).toContain('1x');
387
+ expect(output).toContain('2x');
388
+ expect(output).not.toContain('1y');
389
+ expect(output).not.toContain('2y');
390
+ });
391
+ });
392
+
393
+ describe('sequential script execution', () => {
394
+ it('pipe output appears before the next script line runs', async () => {
395
+ const shell = await createShell({
396
+ filesystem: {
397
+ scripts: {
398
+ 'pipe-seq.sh': '#!/sh.js\necho first | cat\necho second'
399
+ }
400
+ },
401
+ permissions: execPerms('/scripts/pipe-seq.sh')
402
+ });
403
+ const output = [];
404
+ shell.on('stdOut', l => output.push(l));
405
+ await shell.onCommand('/scripts/pipe-seq.sh', false);
406
+ expect(output.indexOf('first')).toBeLessThan(output.indexOf('second'));
407
+ });
408
+
409
+ it('loop iterations run in order when body contains a pipe', async () => {
410
+ const shell = await createShell({
411
+ filesystem: {
412
+ scripts: {
413
+ 'loop-pipe.sh': '#!/sh.js\nfor x in 1 2 3; do\necho $x | cat\ndone'
414
+ }
415
+ },
416
+ permissions: execPerms('/scripts/loop-pipe.sh')
417
+ });
418
+ const output = [];
419
+ shell.on('stdOut', l => output.push(l));
420
+ await shell.onCommand('/scripts/loop-pipe.sh', false);
421
+ expect(output[0]).toBe('1');
422
+ expect(output[1]).toBe('2');
423
+ expect(output[2]).toBe('3');
424
+ });
425
+ });
@@ -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
+ });