Qcommandlineparser (#199)

* Replaced getoptplusplus with QCommandLineParser. Fixes #39

* enabling C++11 if possible

* enabling C++11 if possible

* fixed gcc compilation issues

* fixed linux builds and improved os x build

* trying to fix dispmanx

* trying to fix dispmanx

* simplified travis build script

* fixed argumentparser default values

* rewrote validator system and made sure default arguments are processed correctly

* rewrote validator system and made sure default arguments are processed correctly

* fixed bool vs. regular options

* oops... removing debug code

* reverted screenshot api change
This commit is contained in:
Rick van Hattem
2016-08-28 15:10:43 +02:00
committed by redPanther
parent c13f2e20ec
commit 61db9f43b8
74 changed files with 1490 additions and 3911 deletions

View File

@@ -1,9 +0,0 @@
project(getoptPlusPlus)
include_directories(
../../include/getoptPlusPlus)
add_library(getoptPlusPlus
../../include/getoptPlusPlus/getoptpp.h
../../include/getoptPlusPlus/parameter.include.cc
getoptpp.cc)

View File

@@ -1,66 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.
“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.
The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
* a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
* b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
* a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
* b) Accompany the object code with a copy of the GNU GPL and this license document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
* a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
* b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
* c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
* d) Do one of the following:
o 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
o 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
* e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
* a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
* b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.

View File

@@ -1,16 +0,0 @@
SOURCES=getoptpp.cc test.cc
HEADERS=getoptpp.h
OBJECTS=$(SOURCES:.cc=.o)
LDFLAGS=
CXXFLAGS=-O0 -ggdb -Wall
CFLAGS=$(CXXFLAGS)
CC=g++
TARGET=getopt-test
all: $(TARGET)
$(TARGET): $(OBJECTS)
$(CXX) $(LDFLAGS) -o $(TARGET) $(OBJECTS)
$(SOURCES): $(HEADERS)
clean:
rm -rf $(TARGET) $(OBJECTS) *~

View File

@@ -1,8 +0,0 @@
A very small class library that replaces getopt() and
getopt_long()-functionality with a more C++-friendly approach.
Additionally, it does not rely on UNIX-specific code.
See test.cc for a sample application and COPYING for license information.

File diff suppressed because it is too large Load Diff

View File

@@ -1,357 +0,0 @@
/* (C) 2011 Viktor Lofgren
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "getoptpp.h"
#include <stdexcept>
#include <cassert>
#include <cstdio>
#include <string>
#include <sys/ioctl.h>
using namespace std;
namespace vlofgren {
/*
*
* Class OptionsParser
*
*
*/
OptionsParser::OptionsParser(const char* programDesc) : fprogramDesc(programDesc) {}
OptionsParser::~OptionsParser() {}
ParameterSet& OptionsParser::getParameters() {
return parameters;
}
void OptionsParser::parse(int argc, const char* argv[]) throw(runtime_error)
{
argv0 = argv[0];
if(argc == 1) return;
vector<string> v(&argv[1], &argv[argc]);
ParserState state(/* *this,*/ v);
for(; !state.end(); state.advance()) {
std::list<Parameter*>::iterator i;
for(i = parameters.parameters.begin();
i != parameters.parameters.end(); i++)
{
int n = 0;
try
{
n = (*i)->receive(state);
}
catch(Parameter::ExpectedArgument &)
{
throw Parameter::ExpectedArgument(state.get() + ": expected an argument");
}
catch(Parameter::UnexpectedArgument &)
{
throw Parameter::UnexpectedArgument(state.get() + ": did not expect an argument");
}
catch(Switchable::SwitchingError &)
{
throw Parameter::ParameterRejected(state.get() + ": parameter already set");
}
catch(Parameter::ParameterRejected & pr) {
std::string what = pr.what();
if(what.length())
{
throw Parameter::ParameterRejected(state.get() + ": " + what);
}
throw Parameter::ParameterRejected(state.get() + " (unspecified error)");
}
for (int j = 1; j < n; ++j)
{
state.advance();
}
if(n != 0)
{
break;
}
}
if(i == parameters.parameters.end()) {
std::string file = state.get();
if(file == "--") {
state.advance();
break;
}
else if(file.at(0) == '-')
throw Parameter::ParameterRejected(string("Bad parameter: ") + file);
else files.push_back(state.get());
}
}
if(!state.end()) for(; !state.end(); state.advance()) {
files.push_back(state.get());
}
}
void OptionsParser::usage() const {
cerr << fprogramDesc << endl;
cerr << "Build time: " << __DATE__ << " " << __TIME__ << endl << endl;
cerr << "Usage: " << programName() << " [OPTIONS]" << endl << endl;
cerr << "Parameters: " << endl;
int totalWidth = 80;
int usageWidth = 33;
// read total width from the terminal
struct winsize w;
if (ioctl(0, TIOCGWINSZ, &w) == 0)
{
if (w.ws_col > totalWidth)
totalWidth = w.ws_col;
}
std::list<Parameter*>::const_iterator i;
for(i = parameters.parameters.begin();
i != parameters.parameters.end(); i++)
{
cerr.width(usageWidth);
cerr << std::left << " " + (*i)->usageLine();
std::string description = (*i)->description();
while (int(description.length()) > (totalWidth - usageWidth))
{
size_t pos = description.find_last_of(' ', totalWidth - usageWidth);
cerr << description.substr(0, pos) << std::endl << std::string(usageWidth - 1, ' ');
description = description.substr(pos);
}
cerr << description << endl;
}
}
const vector<string>& OptionsParser::getFiles() const {
return files;
}
const string& OptionsParser::programName() const {
return argv0;
}
/*
* Parameter set
*
*
*/
ParameterSet::ParameterSet(const ParameterSet& ps) {
throw new runtime_error("ParameterSet not copyable");
}
ParameterSet::~ParameterSet() {
for(std::list<Parameter*>::iterator i = parameters.begin();
i != parameters.end(); i++)
{
delete *i;
}
}
/* The typical use case for command line arguments makes linear searching completely
* acceptable here.
*/
Parameter& ParameterSet::operator[](char c) const {
for(std::list<Parameter*>::const_iterator i = parameters.begin(); i!= parameters.end(); i++) {
if((*i)->shortOption() == c) return *(*i);
}
throw out_of_range("ParameterSet["+string(&c)+string("]"));
}
Parameter& ParameterSet::operator[](const string& param) const {
for(std::list<Parameter*>::const_iterator i = parameters.begin(); i!= parameters.end(); i++) {
if((*i)->longOption() == param) return *(*i);
}
throw out_of_range("ParameterSet["+param+"]");
}
/*
*
* Class ParserState
*
*
*/
ParserState::ParserState(/*OptionsParser &opts, */vector<string>& args) :
/*opts(opts),*/ arguments(args), iterator(args.begin())
{
}
const string ParserState::peek() const {
vector<string>::const_iterator next = iterator+1;
if(next != arguments.end()) return *next;
else return "";
}
const string ParserState::get() const {
if(!end()) return *iterator;
else return "";
}
void ParserState::advance() {
iterator++;
}
bool ParserState::end() const {
return iterator == arguments.end();
}
/*
*
* Class Parameter
*
*
*/
Parameter::Parameter(char shortOption, const std::string & longOption, const std::string & description) :
fshortOption(shortOption), flongOption(longOption), fdescription(description)
{
}
Parameter::~Parameter() {}
const string& Parameter::description() const { return fdescription; }
const string& Parameter::longOption() const { return flongOption; }
bool Parameter::hasShortOption() const { return fshortOption != 0x0; }
char Parameter::shortOption() const { assert(hasShortOption()); return fshortOption; }
/*
*
* Class Switchable
*
*
*/
bool Switchable::isSet() const { return fset; }
Switchable::~Switchable() {};
Switchable::Switchable() : fset(false) {}
void MultiSwitchable::set() throw (Switchable::SwitchingError) { fset = true; }
MultiSwitchable::~MultiSwitchable() {}
void UniquelySwitchable::set() throw (Switchable::SwitchingError) {
if(UniquelySwitchable::isSet()) throw Switchable::SwitchingError();
fset = true;
}
UniquelySwitchable::~UniquelySwitchable() {}
PresettableUniquelySwitchable::~PresettableUniquelySwitchable() {}
bool PresettableUniquelySwitchable::isSet() const {
return UniquelySwitchable::isSet() || fpreset.isSet();
}
void PresettableUniquelySwitchable::set() throw (Switchable::SwitchingError)
{
UniquelySwitchable::set();
}
void PresettableUniquelySwitchable::preset() {
fpreset.set();
}
/*
*
* PODParameter specializations
*
*
*
*/
template<>
PODParameter<string>::PODParameter(char shortOption, const char *longOption,
const char* description) : CommonParameter<PresettableUniquelySwitchable>(shortOption, longOption, description) {
}
template<>
int PODParameter<int>::validate(const string &s) throw(Parameter::ParameterRejected)
{
// This is sadly necessary for strto*-functions to operate on
// const char*. The function doesn't write to the memory, though,
// so it's quite safe.
char* cstr = const_cast<char*>(s.c_str());
if(*cstr == '\0') throw ParameterRejected("No argument given");
long l = strtol(cstr, &cstr, 10);
if(*cstr != '\0') throw ParameterRejected("Expected int");
if(l > INT_MAX || l < INT_MIN) {
throw ParameterRejected("Expected int");
}
return l;
}
template<>
long PODParameter<long>::validate(const string &s) throw(Parameter::ParameterRejected)
{
char* cstr = const_cast<char*>(s.c_str());
if(*cstr == '\0') throw ParameterRejected("No argument given");
long l = strtol(cstr, &cstr, 10);
if(*cstr != '\0') throw ParameterRejected("Expected long");
return l;
}
template<>
double PODParameter<double>::validate(const string &s) throw(Parameter::ParameterRejected)
{
char* cstr = const_cast<char*>(s.c_str());
if(*cstr == '\0') throw ParameterRejected("No argument given");
double d = strtod(cstr, &cstr);
if(*cstr != '\0') throw ParameterRejected("Expected double");
return d;
}
template<>
string PODParameter<string>::validate(const string &s) throw(Parameter::ParameterRejected)
{
return s;
}
} //namespace

View File

@@ -1,196 +0,0 @@
/* (C) 2011 Viktor Lofgren
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "getoptpp.h"
#include <cstdlib>
#include <cctype>
#include <iostream>
#include <algorithm>
using namespace std;
using namespace vlofgren;
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/*
*
* This is one way of adding new parameter types,
* inheriting existing types and adding new validation.
*
* In this case, StringParameter (which is a typedef of PODParameter<string> gets
* a new validator that only accepts strings with only letters.
*
*/
class AlphabeticParameter : public StringParameter {
public:
AlphabeticParameter(char shortName, const char* longName, const char* description) :
StringParameter(shortName, longName, description) {}
virtual ~AlphabeticParameter() {}
void receiveSwitch() throw(Parameter::ParameterRejected) {
throw Parameter::ParameterRejected();
}
/* isalpha may be a macro */
static bool isNotAlpha(char c) { return !isalpha(c); }
virtual string validate(const string& arg) throw(Parameter::ParameterRejected) {
int nonalpha = count_if(arg.begin(), arg.end(), isNotAlpha);
if(nonalpha) throw Parameter::ParameterRejected("I only want numbers");
else return arg;
}
};
/*
*
* The other way is to specialize the PODParameter class
*
*/
enum RockPaperScissor { ROCK, PAPER, SCISSOR } ;
namespace vlofgren {
// needs to live in the vlofgren namespace for whatever reason
template<> enum RockPaperScissor
PODParameter<enum RockPaperScissor>::validate(const string &s) throw(Parameter::ParameterRejected)
{
if(s == "rock")
return ROCK;
else if(s == "paper")
return PAPER;
else if(s == "scissor")
return SCISSOR;
else {
throw ParameterRejected("Invalid argument");
}
}
}
typedef PODParameter<enum RockPaperScissor> RockPaperScissorParameter;
/*
*
* Dummy program
*
*/
int main(int argc, const char* argv[]) {
// Create a parser
OptionsParser optp("An example program (that also runs some tests)");
ParameterSet& ps = optp.getParameters();
/* An alternative option is to simply extend the options parser and set all this up
* in the constructor.
*/
ps.add<SwitchParameter>('f', "foo", "Enable the foo system (no argument)");
ps.add<StringParameter>('b', "bar", "Enable the bar system (string argument)");
ps.add<PODParameter<double> >('z', "baz", "Enable the baz system (floating point argument");
PODParameter<int>& i = ps.add<PODParameter<int> >('i', "foobar", "Enable the foobar system (integer argument");
i.setDefault(15);
ps.add<AlphabeticParameter>('a', "alpha", "Custom parameter that requires a string of letters");
ps.add<RockPaperScissorParameter>('r', "rps", "Takes the values rock, paper or scissor");
ps.add<SwitchParameter>('h', "help", "Display help screen");
// Register the parameters with the parser
try {
// Parse argv
optp.parse(argc, argv);
// Test for the help flag
if(ps['h'].isSet()) {
optp.usage();
return EXIT_SUCCESS;
}
// Print out what values the parameters were given
cout << "The following parameters were set:" << endl;
cout << "foo: " << (ps['f'].isSet() ? "true" : "false") << endl;
cout << "bar: \"" << ps['b'].get<string>() << "\""<< endl;
cout << "baz: ";
if(ps['z'].isSet()) {
cout << ps['z'].get<double>() << endl;
} else {
cout << "not set" << endl;
}
/* You can also save the return value from ParserSet::add() if
* you feel the operator[].get<T>() stuff is a bit much */
cout << "foobar: ";
if(i.isSet()) {
cout << i.get<int>() << endl;
} else {
cout << "not set" << endl;
}
cout << "alpha: ";
if(ps["alpha"].isSet()) {
cout << ps["alpha"].get<string>() << endl;
} else {
cout << "not set" << endl;
}
cout << "rps: ";
if(ps["rps"].isSet()) {
cout << ps["rps"].get<enum RockPaperScissor>() << endl;
} else {
cout << "not set" << endl;
}
} catch(Parameter::ParameterRejected &p){
// This will happen if the user has fed some malformed parameter to the program
cerr << p.what() << endl;
optp.usage();
return EXIT_FAILURE;
} catch(runtime_error &e) {
// This will happen if you try to access a parameter that hasn't been set
cerr << e.what() << endl;
return EXIT_FAILURE;
}
// List what non-parameter options were given (typically files)
cout << "The following file arguments were given:" << endl;
vector<string> files = optp.getFiles();
for(vector<string>::iterator i = files.begin(); i != files.end(); i++) {
cout << "\t" << *i << endl;
}
return EXIT_SUCCESS;
}
#endif