Skip to content

Commit 2249209

Browse files
authored
Merge pull request microsoft#776 from Microsoft/pgonzal/rushell-execute2
[rushell] Add basic script evaluator that can spawn new processes
2 parents efa4a1a + 9bf7883 commit 2249209

14 files changed

Lines changed: 254 additions & 61 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"changes": [
3+
{
4+
"packageName": "@microsoft/node-core-library",
5+
"comment": "Fix an issue where Executable.spawnSync() was returning SpawnSyncReturns<Buffer> instead of SpawnSyncReturns<string>",
6+
"type": "patch"
7+
}
8+
],
9+
"packageName": "@microsoft/node-core-library",
10+
"email": "pgonzal@users.noreply.github.com"
11+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"changes": [
3+
{
4+
"packageName": "@microsoft/node-core-library",
5+
"comment": "Fix an issue where Executable.spawnSync() did not support command paths containing spaces",
6+
"type": "patch"
7+
}
8+
],
9+
"packageName": "@microsoft/node-core-library",
10+
"email": "pgonzal@users.noreply.github.com"
11+
}

‎common/reviews/api/rushell.api.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1+
// @beta
2+
interface IRushellExecuteResult {
3+
value: string;
4+
}
5+
16
// @beta
27
class Rushell {
8+
// (undocumented)
9+
execute(script: string): IRushellExecuteResult;
310
}
411

‎libraries/node-core-library/src/Executable.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,10 @@ export class Executable {
160160
timeout: options.timeoutMs,
161161
maxBuffer: options.maxBuffer,
162162

163+
// Contrary to what the NodeJS typings imply, we must explicitly specify "utf8" here
164+
// if we want the result to be SpawnSyncReturns<string> instead of SpawnSyncReturns<Buffer>.
165+
encoding: 'utf8',
166+
163167
// NOTE: This is always false, because Rushell is recommended instead of relying on the OS shell.
164168
shell: false
165169
} as child_process.SpawnSyncOptionsWithStringEncoding;
@@ -213,7 +217,10 @@ export class Executable {
213217
shellArgs.push('/s');
214218
// /C: Execute the following command and then exit immediately
215219
shellArgs.push('/c');
216-
shellArgs.push(resolvedPath);
220+
221+
// If the path contains special charactrers (e.g. spaces), escape them so that
222+
// they don't get interpreted by the shell
223+
shellArgs.push(Executable._getEscapedForWindowsShell(resolvedPath));
217224
shellArgs.push(...args);
218225

219226
return child_process.spawnSync(shellPath, shellArgs, spawnOptions);
@@ -412,6 +419,15 @@ export class Executable {
412419
};
413420
}
414421

422+
/**
423+
* Given an input string containing special symbol characters, this inserts the "^" escape
424+
* character to ensure the symbols are interpreted literally by the Windows shell.
425+
*/
426+
private static _getEscapedForWindowsShell(text: string): string {
427+
const escapableCharRegExp: RegExp = /[%\^&|<> ]/g;
428+
return text.replace(escapableCharRegExp, (value) => '^' + value);
429+
}
430+
415431
/**
416432
* Checks for characters that are unsafe to pass to a Windows batch file
417433
* due to the way that cmd.exe implements escaping.

‎libraries/rushell/package.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@
1616
"start": "jest --watch"
1717
},
1818
"license": "MIT",
19-
"dependencies": {},
19+
"dependencies": {
20+
"@microsoft/node-core-library": "2.1.0"
21+
},
2022
"devDependencies": {
2123
"@microsoft/node-library-build": "4.4.8",
2224
"@types/jest": "21.1.10",

‎libraries/rushell/src/AstNode.ts‎

Lines changed: 74 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -2,42 +2,46 @@
22
// See LICENSE in the project root for license information.
33

44
import { Token } from './Tokenizer';
5-
6-
export enum AstKind {
7-
Script,
8-
AndIf,
9-
Command,
10-
CompoundWord,
11-
VariableExpansion,
12-
Text
5+
import { TextRange } from './TextRange';
6+
7+
export const enum AstKind {
8+
None = 'None',
9+
Script = 'Script',
10+
AndIf = 'AndIf',
11+
Command = 'Command',
12+
CompoundWord = 'CompoundWord',
13+
VariableExpansion = 'VariableExpansion',
14+
Text = 'Text'
1315
}
1416

1517
/**
1618
* Base class for all AST nodes.
1719
*/
18-
export abstract class AstNode {
19-
public abstract get kind(): AstKind;
20+
export abstract class AstBaseNode {
21+
public readonly kind: AstKind = AstKind.None;
22+
public range: TextRange | undefined;
2023

2124
/**
2225
* Returns a diagnostic dump of the tree, showing the prefix/suffix/separator for
2326
* each node.
2427
*/
2528
public getDump(indent: string = ''): string {
26-
let result: string = indent + AstKind[this.kind];
29+
const nestedIndent: string = indent + ' ';
30+
let result: string = indent + `- ${this.kind}:\n`;
2731

2832
const dumpText: string | undefined = this.getDumpText();
2933
if (dumpText) {
30-
result += '=' + JSON.stringify(dumpText);
34+
result += nestedIndent + 'Value=' + JSON.stringify(dumpText) + '\n';
35+
}
36+
37+
const fullRange: TextRange = this.getFullRange();
38+
if (!fullRange.isEmpty()) {
39+
result += nestedIndent + 'Range=' + JSON.stringify(fullRange.toString()) + '\n';
3140
}
3241

3342
const childNodes: AstNode[] = this.getChildNodes();
34-
if (childNodes.length === 0) {
35-
result += '\n';
36-
} else {
37-
result += ':\n';
38-
for (const child of this.getChildNodes()) {
39-
result += child.getDump(indent + ' ');
40-
}
43+
for (const child of childNodes) {
44+
result += child.getDump(nestedIndent);
4145
}
4246

4347
return result;
@@ -49,19 +53,34 @@ export abstract class AstNode {
4953
return nodes;
5054
}
5155

56+
public getFullRange(): TextRange {
57+
if (this.range) {
58+
return this.range;
59+
}
60+
61+
let encompassingRange: TextRange = TextRange.empty;
62+
63+
for (const child of this.getChildNodes()) {
64+
encompassingRange = encompassingRange.getEncompassingRange(child.getFullRange());
65+
}
66+
67+
return encompassingRange;
68+
}
69+
5270
protected abstract collectChildNodesInto(nodes: AstNode[]): void;
5371

5472
protected getDumpText(): string | undefined {
5573
return undefined;
5674
}
5775
}
5876

59-
export class AstScript extends AstNode {
60-
public body: AstNode | undefined;
77+
/**
78+
* Represents a complete script that can be executed.
79+
*/
80+
export class AstScript extends AstBaseNode {
81+
public readonly kind: AstKind.Script = AstKind.Script;
6182

62-
public get kind(): AstKind {
63-
return AstKind.Script;
64-
}
83+
public body: AstNode | undefined;
6584

6685
/** @override */
6786
protected collectChildNodesInto(nodes: AstNode[]): void {
@@ -71,7 +90,12 @@ export class AstScript extends AstNode {
7190
}
7291
}
7392

74-
export class AstAndIf extends AstNode {
93+
/**
94+
* Represents the "&&" operator, which is used to join two individual commands.
95+
*/
96+
export class AstAndIf extends AstBaseNode {
97+
public readonly kind: AstKind.AndIf = AstKind.AndIf;
98+
7599
/**
76100
* The command that executes first, and always.
77101
*/
@@ -82,10 +106,6 @@ export class AstAndIf extends AstNode {
82106
*/
83107
public secondCommand: AstCommand | undefined;
84108

85-
public get kind(): AstKind {
86-
return AstKind.AndIf;
87-
}
88-
89109
/** @override */
90110
protected collectChildNodesInto(nodes: AstNode[]): void {
91111
if (this.firstCommand) {
@@ -97,14 +117,15 @@ export class AstAndIf extends AstNode {
97117
}
98118
}
99119

100-
export class AstCommand extends AstNode {
120+
/**
121+
* Represents a command. For example, the name of an executable to be started.
122+
*/
123+
export class AstCommand extends AstBaseNode {
124+
public readonly kind: AstKind.Command = AstKind.Command;
125+
101126
public commandPath: AstCompoundWord | undefined;
102127
public arguments: AstCompoundWord[] = [];
103128

104-
public get kind(): AstKind {
105-
return AstKind.Command;
106-
}
107-
108129
/** @override */
109130
protected collectChildNodesInto(nodes: AstNode[]): void {
110131
if (this.commandPath) {
@@ -114,35 +135,39 @@ export class AstCommand extends AstNode {
114135
}
115136
}
116137

117-
export class AstCompoundWord extends AstNode {
118-
public readonly parts: AstNode[] = [];
138+
/**
139+
* Represents a compound word, e.g. "--the-thing" or "./the/thing".
140+
*/
141+
export class AstCompoundWord extends AstBaseNode {
142+
public readonly kind: AstKind.CompoundWord = AstKind.CompoundWord;
119143

120-
public get kind(): AstKind {
121-
return AstKind.CompoundWord;
122-
}
144+
public readonly parts: AstNode[] = [];
123145

124146
/** @override */
125147
protected collectChildNodesInto(nodes: AstNode[]): void {
126148
nodes.push(...this.parts);
127149
}
128150
}
129151

130-
export class AstVariableExpansion extends AstNode {
131-
public get kind(): AstKind {
132-
return AstKind.VariableExpansion;
133-
}
152+
/**
153+
* Represents an environment variable expansion expression, e.g. "${VARIABLE}"
154+
*/
155+
export class AstVariableExpansion extends AstBaseNode {
156+
public readonly kind: AstKind.VariableExpansion = AstKind.VariableExpansion;
134157

135158
/** @override */
136159
protected collectChildNodesInto(nodes: AstNode[]): void {
137160
// no children
138161
}
139162
}
140163

141-
export class AstText extends AstNode {
164+
/**
165+
* Represents some plain text.
166+
*/
167+
export class AstText extends AstBaseNode {
168+
public readonly kind: AstKind.Text = AstKind.Text;
169+
142170
public token: Token | undefined;
143-
public get kind(): AstKind {
144-
return AstKind.Text;
145-
}
146171

147172
/** @override */
148173
protected collectChildNodesInto(nodes: AstNode[]): void {
@@ -157,3 +182,5 @@ export class AstText extends AstNode {
157182
return undefined;
158183
}
159184
}
185+
186+
export type AstNode = AstScript | AstAndIf | AstCommand | AstCompoundWord | AstVariableExpansion | AstText;

‎libraries/rushell/src/Parser.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ export class Parser {
9393

9494
const astText: AstText = new AstText();
9595
astText.token = token;
96+
astText.range = token.range;
9697
return astText;
9798
}
9899

‎libraries/rushell/src/Rushell.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,74 @@
11
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
22
// See LICENSE in the project root for license information.
33

4+
import * as child_process from 'child_process';
5+
import { Executable } from '@microsoft/node-core-library';
6+
import { Parser } from './Parser';
7+
8+
import { Tokenizer } from './Tokenizer';
9+
import { AstNode, AstScript, AstKind, AstCommand } from './AstNode';
10+
import { ParseError } from './ParseError';
11+
12+
/**
13+
* The returned value for {@link Rushell.execute}.
14+
* @beta
15+
*/
16+
export interface IRushellExecuteResult {
17+
/**
18+
* A text value that was the result of evaluating the script expression.
19+
*/
20+
value: string;
21+
}
22+
423
/**
524
* The shell command interpreter.
625
* @beta
726
*/
827
export class Rushell {
28+
public execute(script: string): IRushellExecuteResult {
29+
30+
const tokenizer: Tokenizer = new Tokenizer(script);
31+
const parser: Parser = new Parser(tokenizer);
32+
const astScript: AstScript = parser.parse();
33+
34+
return this._evaluateNode(astScript);
35+
}
36+
37+
private _evaluateNode(astNode: AstNode): IRushellExecuteResult {
38+
switch (astNode.kind) {
39+
case AstKind.CompoundWord:
40+
return { value: astNode.parts.map(x => this._evaluateNode(x).value).join('') };
41+
case AstKind.Text:
42+
return { value: astNode.token!.range.toString() };
43+
case AstKind.Script:
44+
if (astNode.body) {
45+
return this._evaluateNode(astNode.body);
46+
}
47+
break;
48+
case AstKind.Command:
49+
return this._evaluateCommand(astNode);
50+
default:
51+
throw new ParseError('Unsupported operation type: ' + astNode.kind, astNode.getFullRange());
52+
}
53+
return { value: '' };
54+
}
55+
56+
private _evaluateCommand(astCommand: AstCommand): IRushellExecuteResult {
57+
if (!astCommand.commandPath) {
58+
throw new ParseError('Missing command path', astCommand.getFullRange());
59+
}
60+
61+
const commandPathResult: IRushellExecuteResult = this._evaluateNode(astCommand.commandPath);
62+
const commandArgResults: IRushellExecuteResult[] = [];
63+
for (let i: number = 0; i < astCommand.arguments.length; ++i) {
64+
commandArgResults.push(this._evaluateNode(astCommand.arguments[i]));
65+
}
66+
67+
const commandPath: string = commandPathResult.value;
68+
const commandArgs: string[] = commandArgResults.map(x => x.value);
69+
70+
const result: child_process.SpawnSyncReturns<string> = Executable.spawnSync(commandPath, commandArgs);
71+
72+
return { value: result.stdout };
73+
}
974
}

0 commit comments

Comments
 (0)