Initial commit

This commit is contained in:
Mattéo Delabre 2019-08-08 19:54:29 +02:00
commit aa3e05a917
Signed by: matteo
GPG Key ID: AE3FBD02DC583ABB
7 changed files with 451 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
build

24
LICENSE Normal file
View File

@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org>

20
Makefile Normal file
View File

@ -0,0 +1,20 @@
CXXFLAGS += -std=c++17 -Wall -Wextra -Wdocumentation
BUILD = build
$(info $(shell mkdir -p $(BUILD)))
$(BUILD)/%: %.cpp
$(CXX) $(CXXFLAGS) $< -o $@
.PHONY: main test
# Build demonstration application
main: $(BUILD)/main
# Run unit tests
test: $(BUILD)/tests
./$(BUILD)/tests
valgrind $(BUILD)/tests
$(BUILD)/main: main.cpp options.hpp
$(BUILD)/tests: tests.cpp options.hpp

111
README.md Normal file
View File

@ -0,0 +1,111 @@
# Options
Minimalist header-only C++17 command line parsing function.
## Background
A C++ program can access the command line with which it was invoked through the `argv` argument of the `main` function, which contains an array of whitespace-separated tokens.
Most programs offer a richer interface than a simple list of values separated by whitespace: a common kind of interface consists in providing the user with a set of options that can be toggled or configured.
Users expect programs to accept those options in a standard formatthe GNU/Unix formataccording to which the command line is to be parsed.
Parsing the command line is a common task for which many libraries have been created, most notably [getopt](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getopt.html), specified by the POSIX standard and available on most systems, and [Boost.Program\_options](https://www.boost.org/doc/libs/release/doc/html/program_options.html).
Nearly all of these libraries provide developers with a similar interface: you need to first precisely define the list of options that should be accepted by your program, specifying short and long names, accepted format and multiplicity for each one along with a description, then trigger the parsing and get the result inside a special structure.
Those libraries can feel too complex for simple projects and too rigid for quick experimentations, which is what the [Argh!](https://github.com/adishavit/argh) library addresses: its philosophy is to simply provide the developers with direct access to the set of options that were passed, without any kind of prior specification.
## Goal
This library follows the same philosophy as _Argh!_ but with a much lighter implementation, providing developers with a function that directly parses the command line into a dictionary of options in less than 100 lines of code.
## Usage
### Installation
Copy the [options.hpp](options.hpp) header into your project and include it where appropriate.
### Documentation
```cpp
template<typename Iterator>
auto options::parse(Iterator start, Iterator end)
```
**Synopsis:** Parse a list of command line arguments into a set of program options.
This implementation strives to follow (in decreasing precedence) the guidelines laid out in Chapter 12 of the POSIX.1-2017 specification (see <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html>); the conventions of Chapter 10 in “The Art of Unix Programming” by Eric S. Raymond; and the author's personal habits.
**Arguments:**
* `start`: Iterator to the initial argument.
* `end`: Past-the-end iterator to signal the argument lists end.
**Return value:** Dictionary containing, for each option present on the command line, a key-value pair with the options name as the key and the list of option-arguments associated to that option, following the order of the command line, as the value. If an option is has no associated option-arguments (i.e. is a flag), the value in the dictionary is an empty list. Operands are grouped in a special item using `options::operands` as its key and also follow the order of the command line.
### Example
This simple program prints all options that are passed to it on the command line.
```cpp
#include "options.hpp"
#include <iostream>
int main(int argc, char** argv)
{
auto opts = options::parse(argv + 1, argv + argc);
for (const auto& [name, args] : opts)
{
if (name == options::operands)
{
std::cerr << "Operands: ";
}
else
{
std::cerr << '"' << name << "\": ";
}
if (args.empty())
{
std::cerr << "(no arguments)";
}
else
{
for (
auto value_it = std::cbegin(args);
value_it != std::cend(args);
++value_it
)
{
std::cerr << '"' << *value_it << '"';
if (std::next(value_it) != std::cend(args))
{
std::cerr << ", ";
}
}
}
std::cerr << '\n';
}
}
```
## Other libraries
* [Argh!](https://github.com/adishavit/argh)
* [args](https://github.com/Taywee/args)
* [Argument\_helper](http://graphics.stanford.edu/~drussel/Argument_helper/)
* [Boost.Program\_options](https://www.boost.org/doc/libs/release/doc/html/program_options.html)
* [CLI](https://www.codesynthesis.com/projects/cli/)
* [CmdLine](http://www.bradapp.com/ftp/src/libs/C++/CmdLine.html)
* [cv::CommandLineParser](https://docs.opencv.org/4.1.1/d0/d2e/classcv_1_1CommandLineParser.html)
* [cxxopts](https://github.com/jarro2783/cxxopts)
* [docopt](https://github.com/docopt/docopt.cpp)
* [getoptpp](https://code.google.com/archive/p/getoptpp/)
* [gflags](https://github.com/gflags/gflags)
* [optionparser](http://optionparser.sourceforge.net/)
* [QCommandLineParser](https://doc.qt.io/qt-5/qcommandlineparser.html)
* [TCLAP](http://tclap.sourceforge.net/)
## License
This library is released into the public domain. See [the license file](LICENSE) for more information.

42
main.cpp Normal file
View File

@ -0,0 +1,42 @@
#include "options.hpp"
#include <iostream>
int main(int argc, char** argv)
{
auto opts = options::parse(argv + 1, argv + argc);
for (const auto& [name, args] : opts)
{
if (name == options::operands)
{
std::cerr << "Operands: ";
}
else
{
std::cerr << '"' << name << "\": ";
}
if (args.empty())
{
std::cerr << "(no arguments)";
}
else
{
for (
auto value_it = std::cbegin(args);
value_it != std::cend(args);
++value_it
)
{
std::cerr << '"' << *value_it << '"';
if (std::next(value_it) != std::cend(args))
{
std::cerr << ", ";
}
}
}
std::cerr << '\n';
}
}

116
options.hpp Normal file
View File

@ -0,0 +1,116 @@
#ifndef OPTIONS_HPP
#define OPTIONS_HPP
#include <string>
#include <map>
#include <vector>
namespace options
{
using Key = std::string;
using Value = std::string;
using Values = std::vector<Value>;
using Dictionary = std::map<Key, Values>;
/**
* @var Dictionary key under which operands (i.e. arguments that are neither
* option nor options-arguments) are stored.
*/
constexpr auto operands = "";
/**
* Parse a list of command line arguments into a set of program options.
*
* This implementation strives to follow (in decreasing precedence) the
* guidelines laid out in Chapter 12 of the POSIX.1-2017 specification (see
* <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html>);
* the conventions of Chapter 10 in The Art of Unix Programming by Eric S.
* Raymond; and the author's personal habits.
*
* @param start Iterator to the initial argument.
* @param end Past-the-end iterator to signal the argument lists end.
* @return Dictionary containing, for each option present on the command line,
* a key-value pair with the options name as the key and the list of
* option-arguments associated to that option, following the order of the
* command line, as the value. If an option is has no associated
* option-arguments (i.e. is a flag), the value in the dictionary is an empty
* list. Operands are grouped in a special item using `options::operands` as
* its key and also follow the order of the command line.
*/
template<typename Iterator>
auto parse(Iterator start, Iterator end)
{
Dictionary opts;
// Signals whether a “--” argument was encountered, which implies that
// all further arguments are to be treated as operands
bool operands_only = false;
// Dictionary item into which the next value should be pushed
auto [item, _] = opts.emplace(operands, Values{});
// Dictionary item into which all operands are pushed
const auto operands_item = item;
for (; start != end; ++start)
{
const auto current = *start;
if (current[0] == '-' && current[1] != '\0' && !operands_only)
{
if (current[1] == '-')
{
if (current[2] == '\0')
{
operands_only = true;
item = operands_item;
}
else
{
// GNU-style long option. The option's argument can either
// be inside the same argument, separated by an “=”
// character, or inside the following argument (therefore
// simply separated by whitespace)
const char* key_end = current + 2;
while (*key_end != '\0' && *key_end != '=') ++key_end;
std::tie(item, _) = opts.emplace(
std::string(current + 2, key_end - current - 2),
Values{}
);
if (*key_end == '=')
{
item->second.emplace_back(key_end + 1);
item = operands_item;
}
}
}
else
{
// Unix-style single-character option. Several short options
// can be grouped together inside the same argument; in this
// case, only the last option can have an option-argument
const char* letter = current + 1;
while (*letter != '\0')
{
std::tie(item, _) = opts.emplace(Key{*letter}, Values{});
++letter;
}
}
}
else
{
// Either an option-argument or an operand
item->second.emplace_back(current);
item = operands_item;
}
}
return opts;
}
}
#endif // OPTIONS_HPP

137
tests.cpp Normal file
View File

@ -0,0 +1,137 @@
#include "options.hpp"
#include <cassert>
int main()
{
/* Skeleton.
{
std::array args{};
auto opts = options::parse(std::cbegin(args), std::cend(args));
assert((opts == options::Dictionary{
{options::operands, {}},
}));
}
*/
/* Operands. */
{
std::array args{"all", "these", "are", "operands"};
auto opts = options::parse(std::cbegin(args), std::cend(args));
assert((opts == options::Dictionary{
{options::operands, {
"all", "these", "are", "operands"
}}
}));
}
/* Short Unix options. */
{
std::array args{"-a", "-b", "-c"};
auto opts = options::parse(std::cbegin(args), std::cend(args));
assert((opts == options::Dictionary{
{options::operands, {}},
{"a", {}},
{"b", {}},
{"c", {}}
}));
}
/* Short Unix options with arguments. */
{
std::array args{"-v", "value", "not-a-value", "-w", "-v", "other"};
auto opts = options::parse(std::cbegin(args), std::cend(args));
assert((opts == options::Dictionary{
{options::operands, {"not-a-value"}},
{"v", {"value", "other"}},
{"w", {}}
}));
}
/* Short Unix options shorthand. */
{
std::array args{"-abcdef", "value", "not-a-value"};
auto opts = options::parse(std::cbegin(args), std::cend(args));
assert((opts == options::Dictionary{
{options::operands, {"not-a-value"}},
{"a", {}},
{"b", {}},
{"c", {}},
{"d", {}},
{"e", {}},
{"f", {"value"}}
}));
}
/* Long GNU options. */
{
std::array args{"--long", "--option"};
auto opts = options::parse(std::cbegin(args), std::cend(args));
assert((opts == options::Dictionary{
{options::operands, {}},
{"long", {}},
{"option", {}}
}));
}
/* Long GNU options with arguments. */
{
std::array args{"--value", "v", "--value", "-v", "value", "--value"};
auto opts = options::parse(std::cbegin(args), std::cend(args));
assert((opts == options::Dictionary{
{options::operands, {}},
{"v", {"value"}},
{"value", {"v"}}
}));
}
/* Single dash as option-argument. */
{
std::array args{"--output", "-", "--input", "-", "-"};
auto opts = options::parse(std::cbegin(args), std::cend(args));
assert((opts == options::Dictionary{
{options::operands, {"-"}},
{"output", {"-"}},
{"input", {"-"}}
}));
}
/* Long, short and shorthand options mixed. */
{
std::array args{"-abc", "content", "--long", "-short", "tree", "out"};
auto opts = options::parse(std::cbegin(args), std::cend(args));
assert((opts == options::Dictionary{
{options::operands, {"out"}},
{"a", {}},
{"b", {}},
{"c", {"content"}},
{"long", {}},
{"s", {}},
{"h", {}},
{"o", {}},
{"r", {}},
{"t", {"tree"}}
}));
}
/* Operand separator. */
{
std::array args{"--option", "--", "--not-option"};
auto opts = options::parse(std::cbegin(args), std::cend(args));
assert((opts == options::Dictionary{
{options::operands, {"--not-option"}},
{"option", {}}
}));
}
}