-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.ts
122 lines (103 loc) · 2.95 KB
/
parser.ts
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import { Command } from "./command";
export interface CommandFlagRule {
short: string|undefined,
long: string,
value: boolean,
info: string
}
export type CommandArgsRules = Array<CommandFlagRule>
export interface CommandFlag {
name:string,
value:string,
shortcutUsed:boolean
}
export interface CommandArgs {
flags: Array<CommandFlag>,
args:Array<string>
}
export function parseArgs(input:string, com:Command):CommandArgs|string {
var input_spl = splitQuotes(input)
var rules = com.flags
var a:CommandArgs = {
args: [],
flags: []
}
var activeFlag:CommandFlag|null = null;
for (const o of input_spl) {
if (activeFlag != null){
activeFlag.value = o
a.flags.push(activeFlag)
activeFlag = null
continue
}
if (o.startsWith("--")){
var flag_long = o.slice(2)
var flag = rules.find((f) => f.long == flag_long.toLowerCase())
if (!flag){
return `flag unknown: ${flag_long}`
}
if (flag.value) {
activeFlag = {
name: flag.long,
shortcutUsed: false,
value: null
}
} else {
a.flags.push({
name: flag.long,
shortcutUsed: false,
value: null
})
}
continue
}
if (o.startsWith("-")){
var flag_short = o.slice(1)
var flag = rules.find((f) => f.short == flag_short.toLowerCase())
if (!flag){
return `flag unknown: ${flag_short}`
}
if (flag.value) {
activeFlag = {
name: flag.long,
shortcutUsed: true,
value: null
}
} else {
a.flags.push({
name: flag.long,
shortcutUsed: true,
value: null
})
}
continue
}
a.args.push(o)
}
return a;
}
export function splitQuotes(input:string):Array<string> {
var quotes:string = "\"'"
var cquotes:string|null = null
var cbuffer = ""
var spl:Array<string> = []
for (let i = 0; i < input.length; i++) {
const char = input.charAt(i);
if (char == " " && (cquotes == null)){
spl.push(cbuffer)
cbuffer = ""
continue
}
if (cquotes == char){
quotes = null;
continue
}
if (quotes.indexOf(char) != -1) {
cquotes = char;
continue
}
cbuffer += char
}
if (cbuffer.length != 0) spl.push(cbuffer)
return spl
}