brsh 2.4.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
@@ -444,7 +444,11 @@ class Shell extends EventEmitter {
444
444
  }
445
445
 
446
446
  _evalArithmetic(expr) {
447
- 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) =>
448
452
  String(parseInt(this.context.getVar(name)) || 0));
449
453
  if (!/^[\d\s+\-*/%()]+$/.test(expanded.trim())) return 0;
450
454
  try {
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) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "2.4.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
+ });