argparse

repository·master·Indexed 19 days ago

https://github.com/nodeca/argparse

A Node.js CLI arguments parser and native port of Python's argparse module. It allows developers to define complex command-line interfaces with positional arguments, optional flags, and sub-commands. Version 3.0.0 requires the use of snake_case for methods, options, and action names.

Tokens
8.5K
Snippets
31
Records
50
Agent score
66%

What's inside argparse

  1. Use argparse for Node.js CLI argument parsing

    master

    argparse is a Node.js port of Python's argparse module, providing a robust way to parse command-line arguments, including support for sub-commands.

    Because this is a JavaScript port, note the following differences from the original Python implementation:

    • Options instead of keyword arguments: Pass configuration via an options object, e.g., new ArgumentParser({ description: 'example' }).
    • String-typed names for types: Since JS lacks Python's native types like int or float, use string literals for the type parameter, such as { type: 'int' }.
    • Format specifiers: The %r format specifier utilizes require('util').inspect() for representation.
    const { ArgumentParser } = require('argparse')
  2. Handle ArgumentError and stream output

    master

    Error Semantics

    ArgumentError.message contains the final formatted error message. Unlike Python, this implementation does not expose separate argument_name or raw message fields.

    Output Streams

    Methods like print_help(file), print_usage(file), and parser error outputs write to the provided file object.

    • The object must have a .write() method; otherwise, it is ignored.
    • Because Node.js streams report I/O failures via error events or write callbacks rather than throwing OSError, you must handle errors on the stream itself.
  3. Configure ArgumentParser using an options object

    master

    Unlike the Python version which uses keyword arguments, argparse in JavaScript requires all configuration parameters to be passed as a single options object to the ArgumentParser constructor.

    // keyword arguments are passed as a single `options` object
    const parser = argparse.ArgumentParser({ prog: 'PROG', usage: '%(prog)s [options]' });
  4. Pass argument names as separate parameters in v3

    master

    The v1 array signature for argument names is no longer accepted. You must pass argument names (like flags and long options) as individual, separate parameters to add_argument().

    // v2 compatibility API
    parser.add_argument([ '-f', '--foo' ], { help: 'foo' })
    
    // v3
    parser.add_argument('-f', '--foo', { help: 'foo' })
  5. Use snake_case for methods and options in v3

    master

    In v3, all automatically generated camelCase method aliases have been removed. Use snake_case for methods and configuration keys.

    Key changes:

    • Methods: Use add_argument() instead of addArgument() and parse_args() instead of parseArgs().
    • Configuration keys: Use add_help instead of addHelp, exit_on_error instead of exitOnError, default instead of defaultValue, and const instead of constant.
    • Help templates: Use %(default)s. The legacy %(defaultValue)s alias is no longer supported.
    // v2 compatibility API
    argparse.ArgumentParser({ addHelp: false, exitOnError: false })
    parser.add_argument('--foo', { defaultValue: 'x', constant: 'y' })
    
    // v3
    argparse.ArgumentParser({ add_help: false, exit_on_error: false })
    parser.add_argument('--foo', { default: 'x', const: 'y' })
  6. Migrate from v2 to v3: Remove v1 compatibility aliases

    master

    Version 3 removes the compatibility layer for the v1 API. You must update your code to use snake_case for method names, option names, and action names. Additionally, argument names must now be passed as separate parameters rather than in an array.

    // v2 compatibility API
    parser.addArgument('--foo')
    parser.parseArgs()
    
    // v3
    parser.add_argument('--foo')
    parser.parse_args()
  7. Convert identifiers from camelCase to snake_case

    master

    In v2, all options, methods, and action names use snake_case. While old names may still work via aliases with deprecation warnings, you should update them to ensure compatibility and avoid issues when extending classes.

    // Before (v1)
    argparse.ArgumentParser({ addHelp: false })
    parser.printHelp()
    parser.add_argument({ action: 'storeTrue' })
    
    // After (v2)
    argparse.ArgumentParser({ add_help: false })
    parser.print_help()
    parser.add_argument({ action: 'store_true' })
  8. Remove type: 'auto' in v3

    master

    The undocumented legacy type name 'auto' has been removed. Since 'auto' was equivalent to omitting the type option, simply remove the type key from your argument configuration.

    // v2
    parser.add_argument('--foo', { type: 'auto' })
    
    // v3
    parser.add_argument('--foo')
  9. Migrate argparse from v1 to v2

    master

    When upgrading from version 1 to version 2, follow these primary steps:

    1. Rename identifiers: Change all options, methods, and action names from camelCase to snake_case.
    2. Update property names:
      • Rename defaultValue to default.
      • Rename constValue to const.
    3. Update add_argument signature: Pass argument names as raw parameters instead of an array.
    4. Update Types: Rename the string type to str.
    5. Handle Constants: Move constants from argparse.Const.* to the top-level argparse.* namespace.
    6. Update Namespace access: Access Namespace values as plain JavaScript objects; methods like .isset, .set, .get, and .unset have been removed.
    7. Handle Null/Undefined: Note that an absence of value is now indicated by undefined instead of null.
  10. Replace deprecated `debug` option in ArgumentParser

    master

    The debug option in argparse.ArgumentParser is deprecated. To customize exit behavior, override the .exit() method in a subclass of argparse.ArgumentParser.

    const argparse = require('argparse')
    
    class MyArgumentParser extends argparse.ArgumentParser {
      exit() { console.log('no exiting today') }
    }
    
    const parser = new MyArgumentParser()
  11. Configure argument behavior using Action classes

    master

    In argparse, an Action object represents how a single argument is processed. When adding arguments, you can specify how values are stored or manipulated using different action types.

    Common Action Types

    • store (default): Stores the converted value in the destination attribute.
    • store_true / store_false: Sets the attribute to true or false respectively when the flag is present.
    • append: Appends the converted value to a list stored at the destination.
    • count: Increments an integer value (useful for flags like -v, -vv, -vvv).
    • BooleanOptionalAction: Automatically creates both a --flag and a --no-flag option.
    • version: Displays the program version and exits.
    • help: Displays the help message and exits.
    • parsers (_SubParsersAction): Used to create sub-commands (like git commit where commit is a sub-command).