/
common.ts
184 lines (163 loc) · 5.41 KB
/
common.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
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import { parseArgs } from "./parse/args"
import { parseConfig } from "./parse/config"
import { parseEnv } from "./parse/env"
/** Global parser parameters */
export interface Cfg {
/** Options which are supposed to be parsed from environment variables will have this prefix */
envPrefix?: string
/** directory from which to start search for config file. default: `.` */
configDir?: string
/** File name of the config file without extension. Default: don't look for the config */
configFile?: string
/** Description of the program displayed in the help message */
help?: string
}
/** Option definitions */
export interface Opts {
[opt: string]: Opt
}
/** Single option definition */
export interface Opt {
/** Option value type */
type: keyof Types
/** Require option to be set or otherwise throw exception */
required?: boolean
/** One character version of the option name, used in the command line */
short?: string
/** Description of the option shown in help message */
help?: string
}
/** For testing purposes only */
export interface Mock {
env?: { [opt: string]: string }
args?: string[]
config?: object
}
/** Type name mappings to actual TypeScript types */
export interface Types {
string: string
number: number
boolean: boolean
list: Array<string>
map: Record<string, string>
}
export type Val = Types[keyof Types]
/** Extra value representing positional command line arguments provided by user */
export interface Rest {
_: string[]
}
/** Parsed values */
export type Vals<O extends Opts> = {
[K in keyof O]: O[K]["required"] extends true
? Types[O[K]["type"]]
: Types[O[K]["type"]] | undefined
}
export const unreachable = (thing: string, value: never): never => {
throw Error(`Invalid ${thing}: ${String(value)}`)
}
const TRUTHY_VALS = ["1", "on", "true"]
const FALSY_VALS = ["", "0", "off", "false"]
export function parseValue(type: keyof Types, str: string): Val {
switch (type) {
case "string": {
return str
}
case "number": {
const num = parseFloat(str)
if (str.match(/[^-0-9.]/u) != null || Number.isNaN(num)) throw Error(`Not a valid number`)
return num
}
case "boolean": {
if (TRUTHY_VALS.includes(str.toLowerCase())) return true
if (FALSY_VALS.includes(str.toLowerCase())) return false
throw Error(`Not a valid boolean`)
}
case "list": {
return str.split(/[,;]\s*/u)
}
case "map": {
const map: { [key: string]: string } = {}
const pairs = str
.split(/[,;]\s*/u)
.filter(pair => pair.match(/\S/u))
.map(pair => pair.split("=", 2))
for (const [key, val] of pairs) {
if (val == null) throw Error(`Missing value for '${key}' key`)
map[key] = val
}
return map
}
default: {
return unreachable("type", type)
}
}
}
/**
* Parse options from config files, environment variables and command line arguments
* @param cfg The options object
* @return Parsed options as key-value map + rest arguments from command line as special `_` option
*/
export function parseAll<O extends Opts>(cfg: Cfg, opts: O, mock: Mock = {}): Vals<O> & Rest {
for (const optName of Object.keys(opts)) {
if (optName.match(/[^A-Z_]/u) != null) throw Error(`Option name '${optName}' is invalid`)
}
const results: { [option: string]: Val } = {
...(parseConfig(cfg, opts, mock.config) as {}),
...(parseEnv(cfg, opts, mock.env) as {}),
...(parseArgs(opts, mock.args) as {}),
}
for (const [optName, opt] of Object.entries(opts)) {
if (results[optName] == null) {
if (opt.required ?? false) throw Error(`Option ${optName} (${opt.type}) is required`)
}
}
return results as any
}
/** Help message format */
export type Format = "markdown" | "text"
export function printHelp<O extends Opts>(cfg: Cfg, opts: O, format: Format = "text"): void {
if (cfg.help != null) console.log(cfg.help.replace(/^[ \t]*/gmu, ""))
if (format === "markdown") console.log(`\n**Options:**\n`)
else console.log(`\nOptions:\n`)
for (const [opt, { type, short, required, help }] of Object.entries(opts)) {
const config = opt.toLowerCase()
const arg = config.replace("_", "-")
console.log(
[
format === "markdown" ? "* " : "",
format === "markdown" ? "`" : "",
type === "boolean"
? short != null
? `--(no-)${arg}/-${short}`
: `--(no-)${arg}`
: short != null
? `--${arg}/-${short}`
: `--${arg}`,
type === "map"
? ` key=string`
: type === "list"
? " string"
: type !== "boolean"
? ` ${type}`
: "",
type === "list" || type === "map" ? " ..." : "",
format === "markdown" ? "`" : "",
`, `,
format === "markdown" ? "`" : "",
`${cfg.envPrefix ?? ""}${opt}=`,
type === "map" ? "key=string,..." : type === "list" ? "string,..." : `${type}`,
format === "markdown" ? "`" : "",
required ?? false ? (format === "markdown" ? ` **(required)**` : ` (required)`) : "",
format === "markdown" ? " - " : "",
].join("")
)
if (help != null) console.log(help.replace(/^\s*/gmu, " "), "\n")
}
if (cfg.configFile != null) {
console.log(
`Options can be provided via \`${cfg.configFile}.json\` ` +
`or \`${cfg.configFile}.toml\` config file.`
)
console.log(`Key names should be in lower_snake_case.`)
}
}