Skip to content

Commit

Permalink
Merge pull request #6 from hildjj/choices
Browse files Browse the repository at this point in the history
Add choices.  Update linewrap to get bugfix.
  • Loading branch information
hildjj committed Jun 8, 2023
2 parents 41f9d0e + 682d211 commit 28cfc7d
Show file tree
Hide file tree
Showing 5 changed files with 234 additions and 88 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ parseArgsWithHelp({
type: 'string',
argumentName: 'encoding',
description: 'encoding for files read or written',
choices: ["utf8", "base64"]
},
},
}, { width: 80 })
Expand All @@ -50,7 +51,8 @@ Arguments:
files the files to be processed
Options:
--encoding <encoding> encoding for files read or written
--encoding <encoding> encoding for files read or written (choices: "utf8",
"base64") Default: "utf8"
-h,--help display help for command
```

Expand Down
110 changes: 55 additions & 55 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@
"license": "MIT",
"repository": "hildjj/minus-h",
"dependencies": {
"@cto.af/linewrap": "1.0.0"
"@cto.af/linewrap": "1.0.1"
},
"devDependencies": {
"@cto.af/eslint-config": "1.1.2",
"@types/node": "20.2.5",
"@typescript-eslint/eslint-plugin": "5.59.8",
"@typescript-eslint/parser": "5.59.8",
"@typescript-eslint/eslint-plugin": "5.59.9",
"@typescript-eslint/parser": "5.59.9",
"c8": "7.14.0",
"eslint": "8.41.0",
"eslint": "8.42.0",
"mocha": "10.2.0",
"typescript": "5.0.4"
},
Expand Down
69 changes: 64 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { parseArgs } from 'util'
import type { Writable } from 'stream'

type LineWrapOptions = ConstructorParameters<typeof LineWrap>[0]
const DEFAULT_ARG_NAME = 'value'

// This is copied in from
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e858f398c44ef759a64dd49854fd3470e6b65731/types/node/util.d.ts#L1254
Expand Down Expand Up @@ -47,6 +48,12 @@ interface ParseArgsOptionConfig {
* @since minus-h
*/
argumentName?: string | undefined;
/**
* If type is string, and choices is specified, the value must be one of
* these choices.
* @since minus-h
*/
choices?: string[] | undefined;
}
interface ParseArgsOptionsConfig {
[longOption: string]: ParseArgsOptionConfig;
Expand Down Expand Up @@ -95,6 +102,12 @@ export interface ParseArgsConfig {
* @since minus-h
*/
argumentDescription?: string | undefined;
/**
* The name of the script. Defaults to process.argv[1].
*
* @since minus-h
*/
scriptName?: string | undefined;
/**
* Where to output help? Useful for testing. Defaults to stderr.
*/
Expand Down Expand Up @@ -134,7 +147,7 @@ function *generateHelp<T extends ParseArgsConfig>(
...opts,
})

const { name } = path.parse(process.argv[1])
const { name } = path.parse(config.scriptName ?? process.argv[1])
let usg = `Usage: ${name}`
let max = -Infinity
if (cfg.options) {
Expand All @@ -145,7 +158,7 @@ function *generateHelp<T extends ParseArgsConfig>(
len += 3 // ,-s
}
if (info.type === 'string') {
const argName = info.argumentName ?? 'string'
const argName = info.argumentName ?? DEFAULT_ARG_NAME
len += argName.length + 3
}
max = Math.max(len, max)
Expand Down Expand Up @@ -196,11 +209,19 @@ function *generateHelp<T extends ParseArgsConfig>(
param = `-${info.short},${param}`
}
if (info.type === 'string') {
const argName = info.argumentName ?? 'string'
const argName = info.argumentName ?? DEFAULT_ARG_NAME
param += ` <${argName}>`
}
param = ` ${param}`
let desc = info.description ?? ''
if (info.choices && (info.choices.length > 0)) {
if (desc) {
desc += ' '
}
desc += '(choices: '
desc += info.choices.map(c => JSON.stringify(c)).join(', ')
desc += ')'
}
if (info.default != null) {
if (desc) {
desc += ' '
Expand Down Expand Up @@ -230,14 +251,52 @@ export function usage<T extends ParseArgsConfig>(
cfg.exit?.(64)
}

interface CodeError extends Error {
code: string;
}

function isCodeError(e: any): e is CodeError {
return (e instanceof Error) && (e.hasOwnProperty('code'))
}

const USAGE_ERRORS = [
'ERR_PARSE_ARGS_INVALID_OPTION_VALUE',
'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL',
'ERR_PARSE_ARGS_UNKNOWN_OPTION',
]

export function parseArgsWithHelp<T extends ParseArgsConfig>(
config?: T,
options?: LineWrapOptions
): ParsedResults<T> {
const cfg = normalizeOptions(config)
const results = parseArgs(cfg)
if ((results.values as HelpResult).help) {
let results: ParsedResults<T> | null = null
try {
results = parseArgs(cfg)
} catch (e) {
if (isCodeError(e) && USAGE_ERRORS.includes(e.code)) {
cfg.outputStream?.write(e.message)
cfg.outputStream?.write(EOL)
cfg.outputStream?.write(EOL)
usage(cfg, options)
}
throw e
}
if ((results?.values as HelpResult)?.help) {
usage(cfg, options)
}
if (cfg.options) {
for (const [long, info] of Object.entries(cfg.options)) {
if (info.choices) {
const val = (results.values as { [key: string]: boolean | string })[long]
if ((typeof val === 'string') && !info.choices.includes(val)) {
cfg.outputStream?.write(`Option '--${long} <${info.argumentName ?? DEFAULT_ARG_NAME}>' argument must be one of ${JSON.stringify(info.choices)}`)
cfg.outputStream?.write(EOL)
cfg.outputStream?.write(EOL)
usage(cfg, options)
}
}
}
}
return results
}

0 comments on commit 28cfc7d

Please sign in to comment.