Skip to content

Commit 2c8fbaa

Browse files
committed
[command-executor] adds optional timeout value
1 parent 3ef92d1 commit 2c8fbaa

1 file changed

Lines changed: 32 additions & 2 deletions

File tree

src/app/services/powershell/powershell-command-executor.ts

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,18 @@
11
import Shell from 'node-powershell';
2+
import { GlobalUtils } from '../global-utils';
3+
4+
5+
6+
7+
export class CommandTimeoutError extends Error {
8+
constructor(message?: string) {
9+
super(message);
10+
// see: typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html
11+
Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
12+
this.name = 'CommandTimeoutError'; // stack traces display correctly now
13+
}
14+
}
15+
216

317
export class PsCommandExecutor {
418
private static _ps: Shell;
@@ -9,19 +23,35 @@ export class PsCommandExecutor {
923
});
1024
}
1125

12-
public static executeCommand(command: string): Promise<string> {
26+
/**
27+
* executes a powershell command and returns the output.
28+
* @param command the command to execute
29+
* @param timeout (optional) specify the max time in seconds that this command should run
30+
*/
31+
public static executeCommand(command: string, timeout?:number): Promise<string> {
1332
//#region Mock Result
1433
if (this.MOCK) return Promise.resolve(this.MOCK_RESULT(command));
1534
//#endregion Mock Result
1635
if (!this._ps) this._initShell();
1736

18-
return this._ps.addCommand(command)
37+
const commandPromise: Promise<string> = this._ps.addCommand(command)
1938
.then(() => this._ps.invoke())
2039
.catch(e => {
2140
console.error(e);
2241
this._initShell();
2342
return '';
2443
});
44+
45+
if (!timeout) return commandPromise;
46+
else {
47+
const timeoutPromise: Promise<string> = GlobalUtils.timeoutPromise((timeout*1000))
48+
.then(() => {
49+
this._initShell();
50+
throw new CommandTimeoutError();
51+
});
52+
53+
return Promise.race([commandPromise, timeoutPromise]);
54+
}
2555
}
2656

2757
//#region MOCK

0 commit comments

Comments
 (0)