decarg

decorator based cli arguments parser

Usage no npm install needed!

<script type="module">
  import decarg from 'https://cdn.skypack.dev/decarg';
</script>

README

decarg

decorator based cli arguments parser

🔧 Install · 🧩 Example · 📜 API docs · 🔥 Releases · 💪🏼 Contribute · 🖐️ Help


Install

$ npm i decarg

Example

import { arg, decarg } from 'decarg'

class Options {
  @arg('<file> [<file>, ...]', 'Files to process')
  file!: string[]

  @arg('--', '[...rest]', 'The rest of the arguments')
  passArgs = []

  @arg('-f', '--flag', 'Flag about something')
  flag = false

  @arg('-c', '--count', 'How many times')
  count = 42

  @arg('-C', 'Choose color', ['blue', 'red', 'yellow'])
  color = 'blue'

  @arg('-s', '--string', 'Some string')
  string = 'hmm'

  @arg('--meh', 'Meh')
  meh: string[] = []

  static examples = {
    '-f foo': 'Convert foo by force',
    '-f foo -s': 'Convert foo by force smoothly',
  }
}

const options = decarg(new Options())

API

Table of Contents

decarg

src/index.ts:17-31

Process an options object and handle errors.

Parameters

  • target T The decorated options object.

  • argv Arguments values. (optional, default process.argv.slice(1))

  • overrides Object (optional, default {})

    • overrides.exit The exit function to use. (optional, default process.exit)
    • overrides.log The log function to use. (optional, default console.error)

Returns any The populated options object when successful, otherwise prints help and exits.

parse

src/parse.ts:17-81

Process an options object and throw errors so that they can be managed manually.

Parameters

  • target T The decorated options object.
  • argv Arguments values. (optional, default process.argv.slice(1))

Returns any The populated options object when successful, otherwise throws.

Errors

OptionValidationError

src/errors.ts:8-13

Extends Error

OptionValidationError.

Thrown when the arguments input was somehow invalid.

Parameters

OptionExpectedValueError

src/errors.ts:20-27

Extends OptionValidationError

OptionExpectedValueError.

Thrown when an argument expects a value and it was not given.

Parameters

OptionInvalidValueError

src/errors.ts:35-42

Extends OptionValidationError

OptionInvalidValueError.

Thrown when an invalid option was passed, i.e not in choices when a multiple choices argument or not a number when a Number argument.

Parameters

OptionHelpRequested

src/errors.ts:49-54

Extends Error

OptionHelpRequested.

Not an error per se, but thrown anyway when --help is passed in the arguments.

Parameters
  • options Options<T>

Notes

Decorators must be enabled in your TypeScript configuration:

...
  "compilerOptions": {
    ...
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    ...
  }
...

Contribute

Fork or edit and submit a PR.

All contributions are welcome!

License

MIT © 2021 stagas