forked from microsoft/rushstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRushell.ts
More file actions
74 lines (62 loc) · 2.39 KB
/
Rushell.ts
File metadata and controls
74 lines (62 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import * as child_process from 'child_process';
import { Executable } from '@rushstack/node-core-library';
import { Parser } from './Parser';
import { Tokenizer } from './Tokenizer';
import { AstNode, AstScript, AstKind, AstCommand } from './AstNode';
import { ParseError } from './ParseError';
/**
* The returned value for {@link Rushell.execute}.
* @beta
*/
export interface IRushellExecuteResult {
/**
* A text value that was the result of evaluating the script expression.
*/
value: string;
}
/**
* The shell command interpreter.
* @beta
*/
export class Rushell {
public execute(script: string): IRushellExecuteResult {
const tokenizer: Tokenizer = new Tokenizer(script);
const parser: Parser = new Parser(tokenizer);
const astScript: AstScript = parser.parse();
return this._evaluateNode(astScript);
}
private _evaluateNode(astNode: AstNode): IRushellExecuteResult {
switch (astNode.kind) {
case AstKind.CompoundWord:
return { value: astNode.parts.map(x => this._evaluateNode(x).value).join('') };
case AstKind.Text:
return { value: astNode.token!.range.toString() };
case AstKind.Script:
if (astNode.body) {
return this._evaluateNode(astNode.body);
}
break;
case AstKind.Command:
return this._evaluateCommand(astNode);
default:
throw new ParseError('Unsupported operation type: ' + astNode.kind, astNode.getFullRange());
}
return { value: '' };
}
private _evaluateCommand(astCommand: AstCommand): IRushellExecuteResult {
if (!astCommand.commandPath) {
throw new ParseError('Missing command path', astCommand.getFullRange());
}
const commandPathResult: IRushellExecuteResult = this._evaluateNode(astCommand.commandPath);
const commandArgResults: IRushellExecuteResult[] = [];
for (let i: number = 0; i < astCommand.arguments.length; ++i) {
commandArgResults.push(this._evaluateNode(astCommand.arguments[i]));
}
const commandPath: string = commandPathResult.value;
const commandArgs: string[] = commandArgResults.map(x => x.value);
const result: child_process.SpawnSyncReturns<string> = Executable.spawnSync(commandPath, commandArgs);
return { value: result.stdout };
}
}