(
argv: string[],
opts?: {
configFile?: string
},
)
| 358 | * that arguments are valid types and have values when required. |
| 359 | */ |
| 360 | export const parse = ( |
| 361 | argv: string[], |
| 362 | opts?: { |
| 363 | configFile?: string |
| 364 | }, |
| 365 | ): UserProvidedArgs => { |
| 366 | const error = (msg: string): Error => { |
| 367 | if (opts?.configFile) { |
| 368 | msg = `error reading ${opts.configFile}: ${msg}` |
| 369 | } |
| 370 | |
| 371 | return new Error(msg) |
| 372 | } |
| 373 | |
| 374 | const args: UserProvidedArgs = {} |
| 375 | let ended = false |
| 376 | |
| 377 | for (let i = 0; i < argv.length; ++i) { |
| 378 | const arg = argv[i] |
| 379 | |
| 380 | // -- signals the end of option parsing. |
| 381 | if (!ended && arg === "--") { |
| 382 | ended = true |
| 383 | continue |
| 384 | } |
| 385 | |
| 386 | // Options start with a dash and require a value if non-boolean. |
| 387 | if (!ended && arg.startsWith("-")) { |
| 388 | let key: keyof UserProvidedArgs | undefined |
| 389 | let value: string | undefined |
| 390 | if (arg.startsWith("--")) { |
| 391 | const split = splitOnFirstEquals(arg.replace(/^--/, "")) |
| 392 | key = split[0] as keyof UserProvidedArgs |
| 393 | value = split[1] |
| 394 | } else { |
| 395 | const short = arg.replace(/^-/, "") |
| 396 | const pair = Object.entries(options).find(([, v]) => v.short === short) |
| 397 | if (pair) { |
| 398 | key = pair[0] as keyof UserProvidedArgs |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | if (!key || !options[key]) { |
| 403 | throw error(`Unknown option ${arg}`) |
| 404 | } |
| 405 | |
| 406 | if (key === "password" && !opts?.configFile) { |
| 407 | throw new Error("--password can only be set in the config file or passed in via $PASSWORD") |
| 408 | } |
| 409 | |
| 410 | if (key === "hashed-password" && !opts?.configFile) { |
| 411 | throw new Error("--hashed-password can only be set in the config file or passed in via $HASHED_PASSWORD") |
| 412 | } |
| 413 | |
| 414 | if (key === "github-auth" && !opts?.configFile) { |
| 415 | throw new Error("--github-auth can only be set in the config file or passed in via $GITHUB_TOKEN") |
| 416 | } |
| 417 |
no test coverage detected