ArgParser.ts
1class ArgParser {
2 private args: string[];
3
4 constructor(args: string[]) {
5 this.args = args;
6 }
7
8 public parse(): any[] {
9 const parsedArgs: any[] = [];
10
11 for (let i = 0; i < this.args.length; i++) {
12 if (this.args[i].startsWith('--')) {
13 const argName = this.args[i].substring(2);
14 const argIndex = parsedArgs.findIndex((arg) => arg.name === argName);
15
16 if (argIndex !== -1) {
17 throw new Error(
18 `You have provided the argument ${argName} more than once.`,
19 );
20 }
21
22 let argValue: any = true;
23
24 if (this.args[i + 1] && !this.args[i + 1].startsWith('--')) {
25 argValue = this.args[i + 1];
26 i++;
27 }
28
29 parsedArgs.push({
30 name: argName,
31 value: argValue,
32 });
33 }
34 }
35
36 return parsedArgs;
37 }
38
39 public getArgValue(argName: string): any {
40 for (const arg of this.parse()) {
41 if (arg.name === argName) {
42 return arg.value;
43 }
44 }
45
46 return null;
47 }
48
49 public getArgs(): string[] {
50 return this.args;
51 }
52}
53
54interface Arg {
55 name: string;
56 value: any;
57}
58
59export { ArgParser, Arg };
60