-
Notifications
You must be signed in to change notification settings - Fork 0
/
PSCommand.js
63 lines (56 loc) · 1.87 KB
/
PSCommand.js
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
const { convertToPSParam } = require('./utils');
const {
PS_ARG_MISS_ERROR,
PS_ARG_TYPE_ERROR,
} = require('./errors');
class PSCommand {
constructor(command) {
if(!command) {
throw new PS_ARG_MISS_ERROR('Command is missing');
}
if(typeof command !== 'string') {
throw new PS_ARG_TYPE_ERROR('Command must be a string');
}
this.command = command;
}
addArgument(argument) {
if(!argument) {
throw new PS_ARG_MISS_ERROR('Argument is missing');
}
if(typeof argument !== 'string') {
throw new PS_ARG_TYPE_ERROR('Argument must be a string');
}
return new this.constructor(`${this.command} ${argument}`);
}
addParameter(parameter) {
if(!parameter) {
throw new PS_ARG_MISS_ERROR('Parameter is missing');
}
if(typeof parameter !== 'object' || Object.keys(parameter).length === 0) {
throw new PS_ARG_TYPE_ERROR('Parameter must be an object containing at least one key');
}
// calc param structure
const paramKeys = Object.keys(parameter);
let paramKey;
let paramValue;
if(paramKeys.length === 1) {
// param is {name: value}
[paramKey] = paramKeys;
paramValue = parameter[paramKey];
} else if(paramKeys.length === 2 && paramKeys[0] === 'name' && paramKeys[1] === 'value') {
// param is {name: '', value: ''}
paramKey = parameter.name;
paramValue = parameter.value;
} else {
throw new PS_ARG_TYPE_ERROR('All params must be in either {name: value} or {name: "", value: ""} structure');
}
// cast a parameter value from JS data types to PowerShell data types.
paramValue = convertToPSParam(paramValue);
paramValue = paramValue ? ` ${paramValue}` : '';
return new this.constructor(`${this.command} -${paramKey}${paramValue}`);
}
clone() {
return new this.constructor(this.command);
}
}
module.exports = PSCommand;