-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.js
167 lines (155 loc) · 4.56 KB
/
cli.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
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/*
* cli.js
* CLI and environment handling service
*/
import { existsSync } from "fs";
import { readFile } from "fs/promises";
/**
* Statuses expected for the "status" CLI option
*/
const statuses = ["active", "verified", "false_p", "duplicate", "out_of_scope",
"risk_accepted", "under_review", "is_mitigated"];
/**
* Options expected by the tool
* (from the command line or environment variables)
*/
const expectedOptions = [
{
name: "url",
env: "DEFECTDOJO_URL",
description: "Root URL to DefectDojo",
pattern: /^https?:\/\/.+$/
},
{
name: "token",
env: "DEFECTDOJO_TOKEN",
description: "API V2 authentication token",
pattern: /^\w{40}$/
},
{
name: "product",
env: "DEFECTDOJO_PRODUCT",
description: "Product name(s) on DefectDojo, comma separated",
pattern: /^([\w/.-]+(,|$))+$/,
csv: true
},
{
name: "engagement",
env: "DEFECTDOJO_ENGAGEMENT",
description: "Engagement name on DefectDojo (optional)",
pattern: /^[\w/.-]+$/,
default: null
},
{
name: "status",
env: "DEFECTDOJO_STATUS",
description: "Finding status(es) to include or !exclude, comma separated (default: active)",
pattern: `^((${statuses.map(s => "!?" + s).join("|")})(,|$))+$`,
csv: true,
default: "active"
},
{
name: "output",
env: "SECDEBT_OUTPUT",
description: "Path to the output file, without extension (default: ./Security-Debt[_{product}])",
pattern: /.+/,
default: null
},
{
name: "format",
env: "SECDEBT_FORMAT",
description: "File format(s) to export, comma separated (default: csv,html,json)",
pattern: /^((csv|html|json)(,|$))+$/,
csv: true,
default: "csv,html,json"
},
{
name: "config",
env: "SECDEBT_CONFIG",
description: "Path to the configuration customization JSON file (optional)",
pattern: /^.+$/,
file: true,
default: null
}
];
/**
* Extract and validate provided arguments
* using the command line or environment variables.
*
* @returns {Promise<*>} Program options
* @throws {CliError} When the program must exit.
*/
export async function parseArgs() {
// Read package metadata from package.json
const npmPackageUrl = new URL("../package.json", import.meta.url);
const npmPackage = JSON.parse(await readFile(npmPackageUrl, { encoding: "utf8" }));
// Show the help message
if (process.argv.some(a => a.match(/^--?h(elp)?$/))) {
console.log(`Usage: ${npmPackage.name} [options]\n`
+ `\n${npmPackage.description}\n`
+ "\nOptions:"
+ "\n CLI Environnement Description\n"
+ expectedOptions
.map(a => ` --${a.name.padEnd(11)} ${a.env.padEnd(22)} ${a.description}`)
.join("\n")
+ "\n -h, --help Show the help message"
+ "\n -v, --version Show the version number");
throw new CliError(0);
}
// Show the version number
if (process.argv.some(a => a.match(/^--?v(ersion)?$/))) {
console.log(npmPackage.version);
throw new CliError(0);
}
const opts = {};
// Extract options
for (const opt of expectedOptions) {
// From the command line
const i = process.argv.findIndex(a => a == `--${opt.name}`);
let value = undefined;
if (i >= 0 && i + 1 < process.argv.length) {
value = process.argv[i + 1];
}
// From environment variables
if (!value) {
value = process.env[opt.env];
}
// Validate the value
if (!value && opt.default === undefined) {
console.error(`[error] Argument '${opt.name}' is required`);
throw new CliError(1);
} else if (value && !(new RegExp(opt.pattern)).test(value)) {
console.error(`[error] Invalid argument '${opt.name}'`);
throw new CliError(1);
}
// Validate the file path
if (value && opt.file && !existsSync(value)) {
console.error(`[error] Argument '${opt.name}' must be a path to an existing file`);
throw new CliError(1);
}
// Take the default value into account
value = value || opt.default;
// Parse variadic options
if (value && opt.csv) {
value = value.split(",").map(v => v.trim()).filter(v => v);
}
opts[opt.name] = value;
}
return opts;
}
/**
* An error thrown during arguments parsing.
*/
export class CliError extends Error {
/**
* Initialize a CLI error.
*
* @param {number} exitCode Process exit code
* @param {string} message Error message
* @param {...any} args Other arguments
*/
constructor(exitCode = 1, message = "", ...args) {
super(message, ...args);
this.exitCode = exitCode;
}
}