Coder Social home page Coder Social logo

option-parser-js's Introduction

OptionParser - JavaScript Version

OptionParser is a library to help you parse command-line options, similar to how getopt works. An effort is made to make it POSIX compliant and easy for people to use. Features of many other implementations have been integrated in order to provide significant flexibility and to make it easier to use.

There is a sample parser in the examples directory.

npm version Build Status Dependencies Dev Dependencies

Features

  • -x (short options)
  • -xxxyxxz (combined and repeating short options)
  • --long (long option)
  • -x=Value, --long=Value (optional and required values)
  • -xValue --long Value (special format for required values)
  • -- (signify the end of options)
  • Nearly automatic help generation
  • Can stop on the first unparsed option
  • Can autocomplete long options
  • Returns unparsed options
  • Flexible option handling

How to use

First, create the parser object:

OptionParser = require('option-parser');
parser = new OptionParser();

Next, you add some options. I'll jump right in and add the standard "help" option, triggered with either "-h" or "--help".

parser.addOption('h', 'help', 'Display this help message')
    .action(parser.helpAction());

Finally, parse the command line options.

parser.parse();

How To Use Parameters

The whole point of the library is to make it really easy to handle the parsing of options to your program. Let's run through a few examples here:

Toggle a Flag With A Callback

Let's have this option only work with the short option "-f".

flagWasSet = false;

parser.addOption('f', null, 'Toggle a flag')
    .action(function () {
        flagWasSet = true;
    });

Pass a Required Value

Many options need a specific value, such as an input file to process. Here is another option that is specified by "-i" or "--input" that requires a filename of the input file. It uses a callback, just like the above example.

inputFile = '/dev/stdin';

parser.addOption('i', 'input', 'Specify an input file')
    .argument('FILE')  // You can name the argument anything you like
    .action(function (value) {
        inputFile = value;
    });

Optional Value and Parameter Object

Prefer to not use a lot of callbacks? One alternative would be to use the returned object from setting up the option on the parser. Here, we add a debug option that lets you set the debug level, but can default to 5 if you don't set one explicitly.

debugLevel = 0;

debugOption = parser.addOption(null, 'debug',
     'Sets the debug level; if set, default is 5')
    .argument('Level', false);  // See note below

// Don't forget to set up the other options here

parser.parse();

// Now use the debugOption object to set the debug value
if (debugOption->count()) {
    debugLevel = debugOption->value() || 5;  // Default to 5
}

The first parameter to OptionParameter.argument() is the name of the parameter, as seen in the generated help message. It doesn't affect the execution of the parser in any other way. The second parameter, false, makes the argument optional.

debugOption.count() returns the number of times the argument was specified. debugOption.value() returns the last value passed to the parameter. For detailed information, check out the documentation for OptionParameter.

Named Parameters

Keeping references to the objects can be tedious. Here is the above example altered to name the parameter and then use the named parameter. I'm naming the parameter "dddd" to help contrast against the previous code.

debugLevel = 0;

parser.addOption(null, 'debug',
     'Sets the debug level, default is 5', 'dddd')
    .argument('Level', false);

// Don't forget to set up the other options here

parser.parse();

if (parser.dddd.count()) {
    debugLevel = parser.dddd.value();
}

Getopt

Lastly, PHP has a unique format for handling command-line arguments using the built-in function getopt(). After setting up options and calling parser.parse(), you can get back an Object that mimics getopt() return value. It is ported over from the PHP version of this library to assist with testing.

// Set up options and then call parse()
parser.parse();

// Get back an Object of options like PHP's getopt()
options = parser.getopt();

Unparsed Options

If you plan on making a program that takes a list of files or needs to work on the options that were passed to the program but were not parsed by OptionParser, that's really simple:

unparsed = parser.parse();

This will contain an array of options, split out into individual options. If you passed "-abcd" to your program and it handled "-a", "-b", and "-c", then unparsed would be an array that only contains "-d".

More Reading

You can read the documentation for the individual classes to understand more about what they do and how they work.

Reference implementations are available in the examples directory in the repository.

Development

I would happily accept patches and suggestions.

Tests are always included. To get them running on your system, just make sure the submodules are checked out for the repository. If you don't have a test/ folder then run this command:

git submodule update --init

From there you can run the tests. Start in the root of this repository and run this command.

test/run-tests

(Using npm test also works well.)

option-parser-js's People

Contributors

fidian avatar

Stargazers

Mitsutoshi Nakano avatar  avatar Jimmy Huang avatar Brandon Burkeen avatar Will avatar LoreLLo avatar Christian Petersen avatar Jost Baron avatar node-migrator-bot avatar  avatar

Watchers

Yvo avatar  avatar Petr Saganov avatar James Cloos avatar Christopher Tetreault avatar

option-parser-js's Issues

Successding calls to value() return different results

I have the following example:

#! /usr/bin/node

const OptionParser = require ('option-parser');
const options = new OptionParser ();

const search_option = options
      .addOption ('s', 'search', 'Search')
      .argument ('JQL');

options.parse ();

var s1 = search_option.value();
var s2 = search_option.value();

console.log (s1 == s2);

When I run it, it displays false.

$ ./example -s xxx
false

How is this possible?

$ npm list
/home/szi
├─┬ [email protected]
│ ├── [email protected]
│ └── [email protected]
└── [email protected]
$ npm --version
6.14.8
$ node --version
v10.24.0
$ uname -a
Linux kallisto 4.19.0-18-amd64 #1 SMP Debian 4.19.208-1 (2021-09-29) x86_64 GNU/Linux

`npm` warning Unsupported engine

Is there something that we can do about the error ?

npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: '[email protected]',
npm WARN EBADENGINE   required: { node: '>=0.6', npm: '~1' },
npm WARN EBADENGINE   current: { node: 'v15.12.0', npm: '7.19.1' }
npm WARN EBADENGINE }

Getting values of an option occuring multiple times into an array

Hi,

This doesn't support getting values of an option that occurs multiple times (ideally into an array), e.g:

parser.addOption('f', 'filter', null, 'filter').argument('short');
var unparsed = parser.parse();
test = parser.filter.value(); // This will always return one of the values

// Using this (hack) actually works to return values in an array:
filters = parser.getopt().filter;
// however above fails if filter occurs once, understandable since it is a hack.

// Workaround:
// Special filters handling:
occurences = parser.filter.count();
filters = parser.getopt().filter;
if (occurences >= 2) {
// Hack to get array of filters with function meant for another purpose:
filters = parser.filter.getopt();
} else if (occurences == 1) {
// Put the single occurence as a value and into an array:
filters = [parser.filter.value()];
} else {
filters = []; // Empty array.
}

throwing errors uses "." concatenation instead of +

Is there a bunch of Perl devs on this project?! "." concatenation is a better operator anyhow but it isn't correct for javascript!

The file option-parser.js has a couple throws that use the incorrect syntax for concatenation. The statements are as follows:

throw new Error('No parameter named ' . name);
throw new Error('Value needed for -' . arg);

Just need to use them to use + instead so the error message can properly be caught higher up the chain.

Should be a super duper simple fix.

Thanks for your work on this project!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.