]> git.tdb.fi Git - libs/core.git/blobdiff - source/core/getopt.cpp
Restore the check that list options must take an argument
[libs/core.git] / source / core / getopt.cpp
index 74f14761c8636c19c7612cd27972ae5ac683832d..fdeb2f8827b2a48075068d153d1cea2597f6ccb1 100644 (file)
@@ -1,61 +1,93 @@
-/* $Id$
-
-This file is part of libmspcore
-Copyright © 2006-2009, 2011 Mikko Rasa, Mikkosoft Productions
-Distributed under the LGPL
-*/
-
+#include <msp/strings/format.h>
 #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(OptionList::iterator i=opts.begin(); i!=opts.end(); ++i)
                delete *i;
 }
 
-GetOpt::OptBase &GetOpt::get_option(char s)
+GetOpt::OptionImpl &GetOpt::add_option(char s, const string &l, const Store &t, ArgType a)
 {
-       for(list<OptBase *>::iterator i=opts.begin(); i!=opts.end(); ++i)
+       if(l.empty())
+               throw invalid_argument("GetOpt::add_option");
+       if(t.is_list() && a!=REQUIRED_ARG)
+               throw invalid_argument("GetOpt::add_option");
+
+       for(OptionList::iterator i=opts.begin(); i!=opts.end(); )
+       {
+               if((s!=0 && (*i)->get_short()==s) || (*i)->get_long()==l)
+               {
+                       delete *i;
+                       opts.erase(i++);
+               }
+               else
+                       ++i;
+       }
+
+       opts.push_back(new OptionImpl(s, l, t, a));
+       return *opts.back();
+}
+
+GetOpt::OptionImpl &GetOpt::get_option(char s)
+{
+       for(OptionList::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)
+GetOpt::OptionImpl &GetOpt::get_option(const string &l)
 {
-       for(list<OptBase *>::iterator i=opts.begin(); i!=opts.end(); ++i)
+       for(OptionList::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)
@@ -67,7 +99,7 @@ unsigned GetOpt::process_long(const char *const *argp)
        unsigned equals = 0;
        for(; arg[equals] && arg[equals]!='='; ++equals) ;
        
-       OptBase &opt = get_option(string(arg, equals));
+       OptionImpl &opt = get_option(string(arg, equals));
        
        if(arg[equals])
                // Process the part after the = as option argument
@@ -75,7 +107,7 @@ 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]);
@@ -95,7 +127,7 @@ unsigned GetOpt::process_short(const char *const *argp)
        // Loop through all characters in the argument
        for(; *arg; ++arg)
        {
-               OptBase &opt = get_option(*arg);
+               OptionImpl &opt = get_option(*arg);
 
                if(arg[1] && opt.get_arg_type()!=NO_ARG)
                {
@@ -106,7 +138,7 @@ unsigned GetOpt::process_short(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(1, *arg)+" requires an argument");
                        
                        // Use the next argument as option argument
                        opt.process(argp[1]);
@@ -121,124 +153,150 @@ unsigned GetOpt::process_short(const char *const *argp)
 
 string GetOpt::generate_usage(const string &argv0) const
 {
-       ostringstream line;
-       
-       line<<argv0;
-       for(list<OptBase *>::const_iterator i=opts.begin(); i!=opts.end(); ++i)
+       string result = argv0;
+       for(OptionList::const_iterator i=opts.begin(); i!=opts.end(); ++i)
        {
-               line<<" [";
+               result += " [";
                if((*i)->get_short())
                {
-                       line<<'-'<<(*i)->get_short();
+                       result += format("-%c", (*i)->get_short());
                        if(!(*i)->get_long().empty())
-                               line<<'|';
+                               result += '|';
                        else if((*i)->get_arg_type()==OPTIONAL_ARG)
-                               line<<'['<<(*i)->get_metavar()<<']';
+                               result += format("[%s]", (*i)->get_metavar());
                        else if((*i)->get_arg_type()==REQUIRED_ARG)
-                               line<<' '<<(*i)->get_metavar();
+                               result += format(" %s", (*i)->get_metavar());
                }
                if(!(*i)->get_long().empty())
                {
-                       line<<"--"<<(*i)->get_long();
+                       result += format("--%s", (*i)->get_long());
 
                        if((*i)->get_arg_type()==OPTIONAL_ARG)
-                               line<<"[="<<(*i)->get_metavar()<<']';
+                               result += format("[=%s]", (*i)->get_metavar());
                        else if((*i)->get_arg_type()==REQUIRED_ARG)
-                               line<<'='<<(*i)->get_metavar();
+                               result += format("=%s", (*i)->get_metavar());
                }
-               line<<']';
+               result += ']';
        }
 
-       return line.str();
+       return result;
 }
 
 string GetOpt::generate_help() const
 {
        bool any_short = false;
-       for(list<OptBase *>::const_iterator i=opts.begin(); (!any_short && i!=opts.end()); ++i)
+       for(OptionList::const_iterator i=opts.begin(); (!any_short && i!=opts.end()); ++i)
                any_short = (*i)->get_short();
 
        string::size_type maxw = 0;
        list<string> switches;
-       for(list<OptBase *>::const_iterator i=opts.begin(); i!=opts.end(); ++i)
+       for(OptionList::const_iterator i=opts.begin(); i!=opts.end(); ++i)
        {
-               ostringstream swtch;
+               string swtch;
                if((*i)->get_short())
                {
-                       swtch<<'-'<<(*i)->get_short();
+                       swtch += format("-%c", (*i)->get_short());
                        if(!(*i)->get_long().empty())
-                               swtch<<", ";
+                               swtch += ", ";
                        else if((*i)->get_arg_type()==OPTIONAL_ARG)
-                               swtch<<'['<<(*i)->get_metavar()<<']';
+                               swtch += format("[%s]", (*i)->get_metavar());
                        else if((*i)->get_arg_type()==REQUIRED_ARG)
-                               swtch<<' '<<(*i)->get_metavar();
+                               swtch += format(" %s", (*i)->get_metavar());
                }
                else if(any_short)
-                       swtch<<"    ";
+                       swtch += "    ";
                if(!(*i)->get_long().empty())
                {
-                       swtch<<"--"<<(*i)->get_long();
+                       swtch += format("--%s", (*i)->get_long());
 
                        if((*i)->get_arg_type()==OPTIONAL_ARG)
-                               swtch<<"[="<<(*i)->get_metavar()<<']';
+                               swtch += format("[=%s]", (*i)->get_metavar());
                        else if((*i)->get_arg_type()==REQUIRED_ARG)
-                               swtch<<'='<<(*i)->get_metavar();
+                               swtch += format("=%s", (*i)->get_metavar());
                }
-               switches.push_back(swtch.str());
-               maxw = max(maxw, switches.back().size());
+               switches.push_back(swtch);
+               maxw = max(maxw, swtch.size());
        }
 
        string result;
        list<string>::const_iterator j = switches.begin();
-       for(list<OptBase *>::const_iterator i=opts.begin(); i!=opts.end(); ++i, ++j)
-       {
-               result += "  "+*j;
-               result += string(maxw+2-j->size(), ' ');
-               result += (*i)->get_help();
-               result += '\n';
-       }
+       for(OptionList::const_iterator i=opts.begin(); i!=opts.end(); ++i, ++j)
+               result += format("  %s%s%s\n", *j, string(maxw+2-j->size(), ' '), (*i)->get_help());
        
        return result;
 }
 
 
-GetOpt::OptBase::OptBase(char s, const std::string &l, ArgType a):
+GetOpt::OptionImpl::OptionImpl(char s, const std::string &l, const Store &t, ArgType a):
        shrt(s),
        lng(l),
        arg_type(a),
        seen_count(0),
-       metavar("ARG")
+       ext_seen_count(0),
+       metavar("ARG"),
+       store(t.clone())
 { }
 
-GetOpt::OptBase &GetOpt::OptBase::set_help(const string &h)
+GetOpt::OptionImpl::~OptionImpl()
+{
+       delete store;
+}
+
+GetOpt::OptionImpl &GetOpt::OptionImpl::set_help(const string &h)
 {
        help = h;
        return *this;
 }
 
-GetOpt::OptBase &GetOpt::OptBase::set_help(const string &h, const string &m)
+GetOpt::OptionImpl &GetOpt::OptionImpl::set_help(const string &h, const string &m)
 {
        help = h;
        metavar = m;
        return *this;
 }
 
-void GetOpt::OptBase::process()
+GetOpt::OptionImpl &GetOpt::OptionImpl::bind_seen_count(unsigned &c)
+{
+       ext_seen_count = &c;
+       return *this;
+}
+
+void GetOpt::OptionImpl::process()
 {
        if(arg_type==REQUIRED_ARG)
-               throw UsageError("--"+lng+" requires an argument");
+               throw usage_error("--"+lng+" requires an argument");
+
        ++seen_count;
+       if(ext_seen_count)
+               *ext_seen_count = seen_count;
 
-       store();
+       try
+       {
+               store->store();
+       }
+       catch(const exception &e)
+       {
+               throw usage_error("Invalid argument for --"+lng+" ("+e.what()+")");
+       }
 }
 
-void GetOpt::OptBase::process(const string &arg)
+void GetOpt::OptionImpl::process(const string &arg)
 {
        if(arg_type==NO_ARG)
-               throw UsageError("--"+lng+" takes no argument");
+               throw usage_error("--"+lng+" takes no argument");
+
        ++seen_count;
+       if(ext_seen_count)
+               *ext_seen_count = seen_count;
 
-       store(arg);
+       try
+       {
+               store->store(arg);
+       }
+       catch(const exception &e)
+       {
+               throw usage_error("Invalid argument for --"+lng+" ("+e.what()+")");
+       }
 }
 
 } // namespace Msp