-/* $Id$
-
-This file is part of libmspcore
-Copyright © 2006-2009, 2011 Mikko Rasa, Mikkosoft Productions
-Distributed under the LGPL
-*/
-
#include "getopt.h"
using namespace std;
namespace Msp {
+GetOpt::GetOpt():
+ help(false)
+{
+ add_option("help", help, NO_ARG).set_help("Displays this help");
+}
+
GetOpt::~GetOpt()
{
for(list<OptBase *>::iterator i=opts.begin(); i!=opts.end(); ++i)
for(list<OptBase *>::iterator i=opts.begin(); i!=opts.end(); ++i)
if((*i)->get_short()==s)
return **i;
- throw UsageError(string("Unknown option -")+s);
+ throw usage_error(string("Unknown option -")+s);
}
GetOpt::OptBase &GetOpt::get_option(const string &l)
for(list<OptBase *>::iterator i=opts.begin(); i!=opts.end(); ++i)
if((*i)->get_long()==l)
return **i;
- throw UsageError(string("Unknown option --")+l);
+ throw usage_error(string("Unknown option --")+l);
}
void GetOpt::operator()(unsigned argc, const char *const *argv)
{
- unsigned i = 1;
- for(; i<argc;)
+ try
{
- if(argv[i][0]=='-')
+ unsigned i = 1;
+ for(; i<argc;)
{
- if(argv[i][1]=='-')
+ if(argv[i][0]=='-')
{
- if(!argv[i][2])
- break;
-
- i += process_long(argv+i);
+ if(argv[i][1]=='-')
+ {
+ if(!argv[i][2])
+ break;
+
+ i += process_long(argv+i);
+ }
+ else
+ i += process_short(argv+i);
}
else
- i += process_short(argv+i);
+ args.push_back(argv[i++]);
}
- else
- args.push_back(argv[i++]);
+
+ for(; i<argc; ++i)
+ args.push_back(argv[i]);
}
-
- for(; i<argc; ++i)
- args.push_back(argv[i]);
+ catch(const usage_error &e)
+ {
+ throw usage_error(e.what(), "Usage: "+generate_usage(argv[0]));
+ }
+
+ if(help)
+ throw usage_error(string("Help for ")+argv[0]+":", generate_help());
}
unsigned GetOpt::process_long(const char *const *argp)
else if(opt.get_arg_type()==REQUIRED_ARG)
{
if(!argp[1])
- throw UsageError("Premature end of arguments");
+ throw usage_error("--"+string(arg)+" requires an argument");
// Process the next argument as option argument
opt.process(argp[1]);
else if(opt.get_arg_type()==REQUIRED_ARG)
{
if(!argp[1])
- throw UsageError("Premature end of arguments");
+ throw usage_error("-"+string(1, *arg)+" requires an argument");
// Use the next argument as option argument
opt.process(argp[1]);
void GetOpt::OptBase::process()
{
if(arg_type==REQUIRED_ARG)
- throw UsageError("--"+lng+" requires an argument");
+ throw usage_error("--"+lng+" requires an argument");
++seen_count;
store();
void GetOpt::OptBase::process(const string &arg)
{
if(arg_type==NO_ARG)
- throw UsageError("--"+lng+" takes no argument");
+ throw usage_error("--"+lng+" takes no argument");
++seen_count;
store(arg);