Skip to content

Commit

Permalink
Add support for a validate function to pre
Browse files Browse the repository at this point in the history
  • Loading branch information
extremeheat committed May 30, 2023
1 parent ce12d49 commit 4a2bf1c
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
3 changes: 2 additions & 1 deletion README.md
Expand Up @@ -81,7 +81,8 @@ const args = basicArg({
port: { type: Number, description: 'Port to listen on', default: 25565 },
online: { type: Boolean, description: 'Whether to run in online mode' },
path: { type: String, description: 'Path to the server directory', default: '.' }
}
},
// validate (args) { return true } /* optional fn to verify the args before returning them; non-true return value will print help screen */
})
// ...
```
Expand Down
7 changes: 5 additions & 2 deletions index.d.ts
Expand Up @@ -6,6 +6,7 @@ declare module "basic-cli" {
description?: string;
default?: any;
}
type Result = Record<string, boolean | string | number>
// The second argument is the custom arg array if any, otherwise default to `process.argv`
export default function(options: {
name: string,
Expand All @@ -14,6 +15,8 @@ declare module "basic-cli" {
throwOnError?: boolean, // Throw an error instead of calling process.exit() with help screen (default: false)
errorOnExtra?: boolean, // Throw an error if there are extra arguments (default: false)
helpCommand?: string, // The -- command for opening the built-in help screen (default: help)
options: Option[]
}, arguments?: string[])
options: Option[],
// Return true here if the result is ok, otherwise a string to raise to the user along with help screen
validate?: (args: Result) => void | string
}, arguments?: string[]): Result
}
9 changes: 8 additions & 1 deletion index.js
Expand Up @@ -106,7 +106,14 @@ function parse (options, args) {
return raise(`** Extraneous options: ${extra.join(', ')}`, options)
}

return Object.fromEntries(haves)
const result = Object.fromEntries(haves)

if (options.validate) {
const ret = options.validate(result)
if (ret !== true) raise(ret)
}

return result
}

module.exports = parse

0 comments on commit 4a2bf1c

Please sign in to comment.