argufy

Parses Command Line Arguments To Node.JS CLI Programs, Keeps Them In Arguments.xml File To Paste Into README Documentation And Generate Google Closure Compatible Exports.

Usage no npm install needed!

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

README

argufy

npm version

yarn add argufy

Argufy Parses Command Line Arguments to Node.JS CLI Programs. It also allows to manage arguments by keeping their definitions in the XML file, so that they can then be embedded into documentation quickly without manual copy-paste. Finally, it produces JavaScript code to extract arguments that is compatible with Google Closure Compiler.

Table Of Contents

CLI

The best way to use Argufy is to create an arguments.xml file and place all definitions in it. For example, Argufy defines the following CLI arguments:

Arguments.xml File (view source)
<arguments>
  <arg command multiple name="inputs" default="types/arguments.xml">
    The locations of `arguments.xml` files.
  </arg>
  <arg name="output" short="o">
    The destination where to save output.
    If not passed, prints to stdout.
  </arg>
  <arg boolean name="help" short="h">
    Print the help information and exit.
  </arg>
  <arg boolean name="version" short="v">
    Show the version's number and exit.
  </arg>
</arguments>

When run from the CLI, Argufy will then generate the get-args.js file that will parse process.argv using the API, and export them as ES6 named exports:

Closure-Compatible Arguments
import argufy from 'argufy'

export const argsConfig = {
  'inputs': {
    description: 'The locations of `arguments.xml` files.',
    command: true,
    multiple: true,
    default: 'types/arguments.xml',
  },
  'output': {
    description: 'The destination where to save output.\nIf not passed, prints to stdout.',
    short: 'o',
  },
  'help': {
    description: 'Print the help information and exit.',
    boolean: true,
    short: 'h',
  },
  'version': {
    description: 'Show the version\'s number and exit.',
    boolean: true,
    short: 'v',
  },
}

const args = argufy(argsConfig)

/**
 * The locations of `arguments.xml` files. Default `types/arguments.xml`.
 */
export const _inputs = /** @type {!Array<string>} */ (args['inputs'] || ['types/arguments.xml'])

/**
 * The destination where to save output.
    If not passed, prints to stdout.
 */
export const _output = /** @type {string} */ (args['output'])

/**
 * Print the help information and exit.
 */
export const _help = /** @type {boolean} */ (args['help'])

/**
 * Show the version's number and exit.
 */
export const _version = /** @type {boolean} */ (args['version'])

/**
 * The additional arguments passed to the program.
 */
export const _argv = /** @type {!Array<string>} */ (args._argv)

It also exports the configuration object which can be then used to pass to Usually — the help generator for CLI programs:

Usually Integration (view source)
import usually from 'usually'
import { reduceUsage } from 'argufy'
import { _help, _output, _input, _version,
  argsConfig } from '../src/get-args'

if (_help) {
  const usage = reduceUsage(argsConfig)
  console.log(usually({
    usage,
    description: `Generates the JavaScript file that exports all arguments
based on the configuration found in the arguments.xml file.`,
    line: 'argufy input [-o output] [-hv]',
    example: 'argufy types/arguments.xml -o src/bin/get-args.js',
  }))
  process.exit()
}

// program
When run as node example -h, the following output will be shown to the user to indicate how to use the program:
Generates the JavaScript file that exports all arguments
based on the configuration found in the arguments.xml file.

  argufy input [-o output] [-hv]

    inputs       	The locations of `arguments.xml` files.
                    Default: types/arguments.xml.
    --output, -o 	The destination where to save output.
                    If not passed, prints to stdout.
    --help, -h   	Print the help information and exit.
    --version, -v	Show the version's number and exit.

  Example:

    argufy types/arguments.xml -o src/bin/get-args.js

The CLI is essentially an abstraction over the API, in which the Argufy config must be written and maintained manually. The main advantage of it is that the types can then be embedded into documentation when it is compiled with the Documentary package. An example of the table and arguments for Argufy usage are shown below.

Argufy Arguments

Argument Short Description
inputs The locations of arguments.xml files. Default types/arguments.xml.
--output -o The destination where to save output. If not passed, prints to stdout.
--help -h Print the help information and exit.
--version -v Show the version's number and exit.

Multiple Input Files

Sometimes it might be desired to keep the arguments in multiple files, e.g., to split the program's arguments by different operations that it can perform. Argufy is capable of reading multiple files and generating a single get-args file where each property arguments configuration is reduced in turns, so that the _argv is exhausted at the end. To enable this functionality, the name attribute should be set on the root arguments element of all xml files after the first one. The exported configs will have the name in form of argsConfig{name}.

For example, it is possible to join these 2 types together:

1.xml, anonymous2.xml, Bundle
<arguments>
  <arg command name="source">
    The path to the source code.
  </arg>
</arguments>
<arguments name="Bundle">
  <arg boolean name="bundle">
    Whether to bundle the source.
  </arg>
</arguments>
$ argufy example/multiple/1.xml example/multiple/2.xml
import argufy from 'argufy'

export const argsConfig = {
  'source': {
    description: 'The path to the source code.',
    command: true,
  },
}

export const argsConfigBundle = {
  'bundle': {
    description: 'Whether to bundle the source.',
    boolean: true,
  },
}

const args = argufy({ ...argsConfig, ...argsConfigBundle })

/**
 * The path to the source code.
 */
export const _source = /** @type {string} */ (args['source'])

/**
 * Whether to bundle the source.
 */
export const _bundle = /** @type {boolean} */ (args['bundle'])

/**
 * The additional arguments passed to the program.
 */
export const _argv = /** @type {!Array<string>} */ (args._argv)

Reusing Shorts

It's possible to set the same short for multiple commands. In this case, both commands will be assigned the relevant value.

1.xml, original2.xml, additional
<arguments>
  <arg name="source" short="s">
    The path to the source code.
  </arg>
</arguments>
<arguments name="Additional">
  <arg name="snapshot" short="s">
    The name of the snapshot.
  </arg>
</arguments>
$ program -s test
import { _snapshot, _source } from './get-args'

console.log(_snapshot, _source)
test test

API

The package is available by importing its default and named functions:

import argufy, { reduceUsage } from 'argufy'

The types and externs for Google Closure Compiler via Depack are defined in the _argufy namespace.

argufy(
  config: !Config,
  argv=: !Array<string>,
): !Object

The flags from the arguments will be extracted according to the configuration object and the arguments array. If arguments array is not passed, process.argv is used to find arguments.

  • config* !Config: The config.
  • argv !Array<string> (optional): The argv to parse, by default will be looked up in the process.

The package assumes that the arguments begin from the 3rd position, i.e., standard Node.JS use such as node example.js --title "Hello World", or example --title "Hello World" if the program has a shebang and/or is run via the bin package.json property.

import argufy from 'argufy'

const config = {
  title: { short: 't', command: true },
  list: { short: 'l', boolean: true },
  app: 'a',
  delay: 'y',
  file: 'f',
  wait: { short: 'w', number: true },
  'no-empty': 'e',
  resize: 'z',
  colors: 'c',
  dir: 'D',
}

const res = argufy(config, process.argv)
console.log(JSON.stringify(res, null, 2))
node example.js --title "Hello World" -w 10 -l --app Argufy
# or
node example.js HelloWorld -w 10 -l --app Argufy
{
  "title": "HelloWorld",
  "list": true,
  "app": "Argufy",
  "wait": 10,
  "_argv": []
}

The configuration for each flag can either be a shorthand string, or an object of the Flag type. The types are shown below. The special _argv property will be assigned to contain all unmatched arguments. For example, it can be used to pass any additional parameters through to other program.

Object<string, (string | !Flag)> Config: The configuration for parsing, where each key is a flag name and values are either strings, or objects with possible properties:

Flag: The flag passed to the program.

Name Type Description Default
short string Shorthand for this argument, usually one letter. -
boolean boolean Whether the flag is a boolean and does not require a value. false
number boolean Specifies whether the flag should be parsed as a number. false
command boolean If set to true, the value is read from the first argument passed to the CLI command (e.g., $ cli command). false
multiple boolean When using the command property, will parse the commands as an array. false
default string The default value for the argument. Does not actually set the value, only used in reducing the usage info (argufy bin on the other hand will set the default). -
description string The description to be used by usually. -

reduceUsage(
  config: !Config,
): !Object

Given the Argufy config, creates an object that can be passed to Usually. Can be used to reduce the config auto-generated and exported from the JavaScript file with the CLI.

import { reduceUsage } from 'argufy'
import { argsConfig } from '../src/get-args'

console.log(reduceUsage(argsConfig))
{ inputs: 'The locations of `arguments.xml` files.\nDefault: types/arguments.xml.',
  '--output, -o': 'The destination where to save output.\nIf not passed, prints to stdout.',
  '--help, -h': 'Print the help information and exit.',
  '--version, -v': 'Show the version\'s number and exit.' }

Copyright

Art Deco © Art Deco 2019 Tech Nation Visa Tech Nation Visa Sucks