GithubHelp home page GithubHelp logo

cmdparser's Introduction

Simple C++ command line parser

This project supplies a simple, single-header, command-line parser. It is very lightweight and relies on templates. The easiest way is to use it by adding it to your source code. The parser requires C++11 and works fine on gcc (v4.8.2 or later, some earlier versions should work as well), icc (v14 or later), clang and msvc (v18 or later).

Using the parser

Using the parser is straight forward. Only include the header (cmdparser.h) in your application source file, most likely the one that contains the main method. Pass the command line arguments to the parser:

int main(int argc, char** argv) {
	cli::Parser parser(argc, argv);
	/* ... */
}

In the following two sections we'll have a look at setting up the parser and using it.

Setup

Setting up the parser works using the following methods:

  • set_optional<T>(), to include an optional argument
  • set_required<T>(), to include a required argument

The third parameter for creating an optional argument is the default value. This value is used if nothing is provided by the user. Otherwise the optional and required methods are pretty similar:

  1. The shorthand (if the user uses a single slash) string
  2. The longhand (if the user uses two slashes) string
  3. The optional description.

The third parameter is the fourth parameter for optional arguments.

Let's look at an example:

void configure_parser(cli::Parser& parser) {
	parser.set_optional<std::string>("o", "output", "data", "Strings are naturally included.");
	parser.set_optional<int>("n", "number", 8, "Integers in all forms, e.g., unsigned int, long long, ..., are possible. Hexadecimal and Ocatl numbers parsed as well");
	parser.set_optional<cli::NumericalBase<int, 10>>("t", "temp", 0, "integer parsing restricted only to numerical base 10");
	parser.set_optional<double>("b", "beta", 11.0, "Also floating point values are possible.");
	parser.set_optional<bool>("a", "all", false, "Boolean arguments are simply switched when encountered, i.e. false to true if provided.");
	parser.set_required<std::vector<short>>("v", "values", "By using a vector it is possible to receive a multitude of inputs.");
}

Usually it makes sense to pack the Parser's setup in a function. But of course this is not required. The shorthand is not limited to a single character. It could also be the same as the longhand alternative.

Getting values

Getting values is possible via the get method. This is also a template. We need to specify the type of argument. This has to be the same type as defined earlier. It also has to be a valid argument (shorthand) name. At the moment only shorthands are considered here. For instance we could do the following:

//auto will be int
auto number = parser.get<int>("n");

//auto will be int, note specification of numerical base same as when set during parser configuration
auto number = parser.get<cli::NumericalBase<int, 10> >("t");

//auto will be std::string
auto output = parser.get<std::string>("o");

//auto will be bool
auto all = parser.get<bool>("a");

//auto will be std::vector<short>
auto values = parser.get<std::vector<short>>("v");

However, before we can access these values we also need to check if the provided user input was valid. On construction the Parser does not examine the input. The parser waits for setup and a potential call to the run method. The run method runs a boolean value to indicate if the provided command line arguments match the requirements.

What we usually want is something like:

void parse_and_exit(cli::Parser& parser) {
	if (parser.parse() == false) {
		exit(1);
	}
}

Writing this function seems to be redundant. Hence the parser includes it already:

parser.run_and_exit_if_error();

The only difference is that the run_and_exit_if_error method does not provide overloads for passing custom output and error streams. The parse method has overloads to support such scenarios. By default std::cout is used the regular output, e.g., the integrated help. Also std::cerr is used for displaying error messages.

Default Arguments

To set and get default arguments (that do not need a name), use the set_default and get_default methods.

parser.set_default<std::string>(false, "May be optional or required depending on the first parameter", "Default value");
const auto default_argument = parser.get_default<std::string>();

Integrated help

The parser comes with a pre-defined command that has the shorthand -h and the longhand --help. This is the integrated help, which appears if only a single command line argument is given, which happens to be either the shorthand or longhand form.

Finally our main method may look as follows:

int main(int argc, char** argv) {
	cli::Parser parser(argc, argv);
	configure_parser(parser);
	parser.run_and_exit_if_error();
	/* ... */
}

This passes the arguments to the parser, configures the parser and checks for potential errors. In case of any errors the program is exited immediately.

Contributions

This is not a huge project and the file should remain a small, single-header command-line parser, which may be useful for small to medium projects. Nevertheless, if you find any bugs, add small, yet useful, new features or improve the cross-compiler compatibility, then contributions are more than welcome.

License

The application is licensed under the MIT License (MIT).

Copyright (c) 2015 - 2016 Florian Rappl

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

cmdparser's People

Contributors

akshat-oke avatar benhenning avatar biroder avatar cngzhnp avatar emankov avatar farzonl avatar ferkulat avatar florianrappl avatar tlanc007 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cmdparser's Issues

Licensing is too restrictive

Hi Florian,
You have a nice command line parsing library here, but it's a bit too restrictive in its licensing (GPLv3: it's incompatible with and imposes upon several other licenses). Would you consider relicensing the library under Public Domain or the MIT license?

Thanks!
Divye

multiple arguments of the same flag

I am interested in essentially parse a vector of vector. One way I thought about doing it is to simply send in multiple values of the same flag. For example, something like
<my_binary> -v v0_0 v0_1 v0_2 -v v1_0 v1_1 v1_2
Is this possible using your parser? Thanks.

Backward compatibility

Hey that was nifty, thanks!

Working great with C++ 11 and above, I wonder how can this be used without C++11, and should backward compatibility be addressed?

I'd like to pick that up and give you a PR.

How to get a flag

Hi,

Sorry for bugging you, but I have a question. So I've been reading your code and it seams to me there is no way to handle flags. Could it be?? The behaviour I need is, every time i call -h of --help, all other options are not to be evaluated but the usage() ought to be printed. For that to work I would need to evaluate if the call to -h has been made but it seams there is no way to evaluate the flat , just if a parameter has been assigned to it or not, right? Could you maybe point me to the right direction on how to enable that (if I'm not seeing the option)

thnx

PS great library

PS
PS

I see that this question has been rased for --help option. I mean one can easily add something like:

bool help = false
...
if ( std::find(_arguments.begin(), _arguments.end(), "--help") != _arguments.end() ||
std::find(_arguments.begin(), _arguments.end(), "-h") != _arguments.end())
help = true;
...

if (command->required && !command->handled && help == false) ....

in run() function to quick "fix" the help behaviour.

but i see no flag handling solution so i guess the one does not exist. (This was not a negative critique, the library is really great. Thnx!! I am definitely gonn start using it from now on. plus if i manage to find some time before you I'll definitely integrate the set_flag() option )

Nice work ...

Hello Florian, this is a nice light-weight parser, for which many thanks. I've made a set of changes to allow it to handle Windows UNICODE. Are you interested in a PR?

Positional Arguments

Hi, is it possible to get positional arguments?

myapp --someflag -a2 FILE1 FILE2 FILE3...

For example.

Uninitialized scalar field

Minor bug concerning class CmdFunction final : public CmdBase

Coverity scan says line 100:

CID 281693 (#1 of 1): Uninitialized scalar field (UNINIT_CTOR)
2. uninit_member: Non-static class member value is not initialized in this constructor nor in any functions that it calls.

and line 118:

1. member_decl: Class member declaration for value.

but seems to me this member variable is set but never used.

Do you mind tagging a version?

Hello! This is a nice and small library and we'd like to use it in our product, but we need to specify a particular version in the product license attributions. Can you tag some recent stable version? Currently you only have v1.0 which is 4 years old and uses GPLv3 license. Thank you!

Parsing hex and octal numbers

Suggest (optional ?) modification of number parsers to the following (so it can also parse hex and octal numbers)

return std::stoi(elements[0]);
to
return std::stoi(elements[0], 0, 0);

Allow to specify general program description

Currently, it seems that the command line parser only deals with descriptions of command line parameters.

Most command line parsers allow to specify a general description of what the program does, which is usually displayed in the help text above the argument descriptions. This does not seem to be supported at the moment, although it should be easy to implement.

Adding Catch to the project?

Hello Florian,

I would like to contribute, but Catch is missing.
Maybe you installed it as package to your OS?
Would you mind to add the Catch header to the project?
Either by

  1. just download and commit or
  2. via git submodule?
  3. biicode (I don't know, if this would be possible)

In my projects I prefer case 1.

For cases 1. or 2. I could make a pull request for that. if you want.
For case 3. I don't know biicode enough yet.

Thank you in advance

Memory leak when disabling help

You only erase the command from the list, but don't delete it. Potential fix:

	void disable_help() {
		for (auto command = _commands.begin(); command != _commands.end(); ++command) {
			if ((*command)->name == "h" && (*command)->alternative == "--help") {
				delete  *command;
				_commands.erase(command);
				break;
			}
		}
	}

Sign conversion compilation warnings

Not a bug bust just warnings triggered when compiling with -Wsign-conversion option. You should replace int by size_t in two lines:

~Parser() { 
for (size_t i = 0, n = _commands.size(); i < n; ++i) { ...

and

bool run(std::ostream& output, std::ostream& error) { ...
for (size_t i = 0, n = _arguments.size(); i < n; ++i) {

Thanks for this lib !

handling of default argument -h

I just stumbled upon this library and wanted to try it out. I'm in a console application in Visual Studio 2015. I included the cmdparser.hpp file as is.
My code is simple:

cli::Parser parser(argc, argv);
parser.run();

I now call my .exe file with parameter -h and the output ends like so:

The parameter h has invalid arguments.
For more help use --help or -h.

What is happening here? How does h have invalid arguments?

In another situation I have one parser.set_required call. When I again call my .exe file with parameter -h the output looks like so:

The parameter i is required.
Name of input file.
For more help use --help or -h.

Why is argument i still required when -h is provided? Why does it not output the help - list of required arguments?

Detection of required arguments and the retrieval with the parser.get method works nicely.

Your sample in the README.md of this repo reads:

cmd.run_and_exit_if_error();

must be

  parser.run_and_exit_if_error();

Thank you for your work.

Tests broken: first `TEST_CASE("Parse help", "[help]")` calls `exit(0)`.

Currently, the tests cannot be run by invoking the test-executable.

This is because the very first test ( "Parse help", "[help]" ) leads to exit(0) being called inside a callback created in void enable_help(). After that, the test executable exits. The checks contained in that test are never executed. Also, no further tests are executed. This means that whenever ( "Parse help", "[help]" ) is included in the list of tests to be run, some or all of the tests will not be run at all, depending on the order of tests.

The callback looks like this:

void enable_help() {
    set_callback("h", "help", std::function<bool(CallbackArgs & )>([this](CallbackArgs &args) {
        args.output << this->usage();
#pragma warning(push)
#pragma warning(disable: 4702)
        exit(0);
        return false;
#pragma warning(pop)
    }), "", true);
}

It seems that this callback really should quit the program when used in user code. Hence, I don't know how to best solve this problem for the unit tests. Perhaps the problematic test case should be removed, especially since it doesn't actually test anything?

As an aside, perhaps the pragma warning modification (which are specific to MSVS compiler) to really be specific to that compiler, e.g., like this:

#if defined(_MSC_VER)
// pragma ...
#endif

Other compilers don't support this and the pragma sometimes becomes a warning in itself, as in "unknown pragma".

valgrind detects leaks with still reachable memory

Hi Florian ! I just discovered right now your lib ! Nice work ! It seems to Valgrind that there are missing calls to delete but memory can be released by the OS. I had no time for longer investigations but it seems to me:
1/ that exit() does not let class destructor to be called :( You have to create and call a release() method called by class destructor and to be called manually before your exit().
2/ disable_help() you call std::vector::erase() but you did not delete the command before.

help not displayed if required field has not been set

Hi there

Firstly, thank you for this very helpful library.

I found that help was not being outputted if a required argument was not specified on the cmd line. Is this the desired behaviour?

I personally did not want this behaviour so have changed it so that help is always displayed (if -h/--help is specified) but a required argument is not.

I would be happy to create a PR if you wish to view my changes. I just swapped the order in which you check for unhandled required arguments and parse the handled ones in "run". This may screw it up elsewhere as I have not run the tests, but it works for me!

Cheers

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.