]> git.tdb.fi Git - libs/core.git/blobdiff - source/core/getopt.cpp
Allow seen_count to be bound to a variable for dealing with optional arguments
[libs/core.git] / source / core / getopt.cpp
index be1d151a3ee8e704af0b10b79ed42c7a8b787572..34e53172aeb194d1cebc29c7df4de8719add8c27 100644 (file)
-/* $Id$
-
-This file is part of libmspcore
-Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions
-Distributed under the LGPL
-*/
+#include <msp/strings/format.h>
 #include "getopt.h"
 
 using namespace std;
 
 namespace Msp {
 
-GetOpt::~GetOpt()
+GetOpt::GetOpt():
+       help(false)
 {
-       for(list<OptBase *>::iterator i=opts.begin(); i!=opts.end(); ++i)
-               delete *i;
-}
-
-/**
-Generates a single line that gives an overview about the known options.
-
-@param   argv0  The program name to be used in the usage string
-
-@return  The generated usage string
-*/
-string GetOpt::generate_usage(const string &argv0) const
-{
-       ostringstream line;
-       
-       line<<argv0;
-       for(list<OptBase *>::const_iterator i=opts.begin(); i!=opts.end(); ++i)
-       {
-               line<<" [";
-               if((*i)->get_short())
-               {
-                       line<<'-'<<(*i)->get_short();
-                       if(!(*i)->get_long().empty())
-                               line<<'|';
-                       else if((*i)->get_arg_type()==OPTIONAL_ARG)
-                               line<<'['<<(*i)->get_metavar()<<']';
-                       else if((*i)->get_arg_type()==REQUIRED_ARG)
-                               line<<' '<<(*i)->get_metavar();
-               }
-               if(!(*i)->get_long().empty())
-               {
-                       line<<"--"<<(*i)->get_long();
-
-                       if((*i)->get_arg_type()==OPTIONAL_ARG)
-                               line<<"[="<<(*i)->get_metavar()<<']';
-                       else if((*i)->get_arg_type()==REQUIRED_ARG)
-                               line<<'='<<(*i)->get_metavar();
-               }
-               line<<']';
-       }
-
-       return line.str();
+       add_option("help", help, NO_ARG).set_help("Displays this help");
 }
 
-/**
-Generates help for known options in tabular format, one option per line.
-The returned string will have a linefeed at the end.
-*/
-string GetOpt::generate_help() const
+GetOpt::~GetOpt()
 {
-       bool any_short=false;
-       for(list<OptBase *>::const_iterator i=opts.begin(); (!any_short && i!=opts.end()); ++i)
-               any_short=(*i)->get_short();
-
-       unsigned maxw=0;
-       list<string> switches;
-       for(list<OptBase *>::const_iterator i=opts.begin(); i!=opts.end(); ++i)
-       {
-               ostringstream swtch;
-               if((*i)->get_short())
-               {
-                       swtch<<'-'<<(*i)->get_short();
-                       if(!(*i)->get_long().empty())
-                               swtch<<", ";
-                       else if((*i)->get_arg_type()==OPTIONAL_ARG)
-                               swtch<<'['<<(*i)->get_metavar()<<']';
-                       else if((*i)->get_arg_type()==REQUIRED_ARG)
-                               swtch<<' '<<(*i)->get_metavar();
-               }
-               else if(any_short)
-                       swtch<<"    ";
-               if(!(*i)->get_long().empty())
-               {
-                       swtch<<"--"<<(*i)->get_long();
-
-                       if((*i)->get_arg_type()==OPTIONAL_ARG)
-                               swtch<<"[="<<(*i)->get_metavar()<<']';
-                       else if((*i)->get_arg_type()==REQUIRED_ARG)
-                               swtch<<'='<<(*i)->get_metavar();
-               }
-               switches.push_back(swtch.str());
-               maxw=max(maxw, switches.back().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';
-       }
-       
-       return result;
+       for(list<OptBase *>::iterator i=opts.begin(); i!=opts.end(); ++i)
+               delete *i;
 }
 
-void GetOpt::operator()(unsigned argc, const char *const *argv)
+GetOpt::OptBase &GetOpt::add_option(OptBase *opt)
 {
-       unsigned i=1;
-       for(; i<argc;)
+       for(list<OptBase *>::iterator i=opts.begin(); i!=opts.end(); )
        {
-               if(argv[i][0]=='-')
+               if((opt->get_short()!=0 && (*i)->get_short()==opt->get_short()) || (*i)->get_long()==opt->get_long())
                {
-                       if(argv[i][1]=='-')
-                       {
-                               if(!argv[i][2])
-                                       break;
-
-                               i+=process_long(argv+i);
-                       }
-                       else
-                               i+=process_short(argv+i);
+                       delete *i;
+                       opts.erase(i++);
                }
                else
-                       args.push_back(argv[i++]);
+                       ++i;
        }
-       
-       for(; i<argc; ++i)
-               args.push_back(argv[i]);
+
+       opts.push_back(opt);
+       return *opts.back();
 }
 
 GetOpt::OptBase &GetOpt::get_option(char s)
@@ -139,7 +39,7 @@ GetOpt::OptBase &GetOpt::get_option(char s)
        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)
@@ -147,26 +47,54 @@ 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);
 }
 
-/**
-Processes the given argument as a long option.
+void GetOpt::operator()(unsigned argc, const char *const *argv)
+{
+       try
+       {
+               unsigned i = 1;
+               for(; i<argc;)
+               {
+                       if(argv[i][0]=='-')
+                       {
+                               if(argv[i][1]=='-')
+                               {
+                                       if(!argv[i][2])
+                                               break;
+
+                                       i += process_long(argv+i);
+                               }
+                               else
+                                       i += process_short(argv+i);
+                       }
+                       else
+                               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]));
+       }
 
-@param   argp  Pointer to the argument
+       if(help)
+               throw usage_error(string("Help for ")+argv[0]+":", generate_help());
+}
 
-@return  The number of arguments eaten (1 or 2)
-*/
 unsigned GetOpt::process_long(const char *const *argp)
 {
        // Skip the --
-       const char *arg=argp[0]+2;
+       const char *arg = argp[0]+2;
 
        // See if the argument contains an =
-       unsigned equals=0;
+       unsigned equals = 0;
        for(; arg[equals] && arg[equals]!='='; ++equals) ;
        
-       OptBase &opt=get_option(string(arg, equals));
+       OptBase &opt = get_option(string(arg, equals));
        
        if(arg[equals])
                // Process the part after the = as option argument
@@ -174,7 +102,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]);
@@ -186,22 +114,15 @@ unsigned GetOpt::process_long(const char *const *argp)
        return 1;
 }
 
-/**
-Processes short options from the given argument.
-
-@param   argp  Pointer to the argument
-
-@return  The number of arguments eaten (1 or 2)
-*/
 unsigned GetOpt::process_short(const char *const *argp)
 {
        // Skip the -
-       const char *arg=argp[0]+1;
+       const char *arg = argp[0]+1;
 
        // Loop through all characters in the argument
        for(; *arg; ++arg)
        {
-               OptBase &opt=get_option(*arg);
+               OptBase &opt = get_option(*arg);
 
                if(arg[1] && opt.get_arg_type()!=NO_ARG)
                {
@@ -212,7 +133,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]);
@@ -225,33 +146,120 @@ unsigned GetOpt::process_short(const char *const *argp)
        return 1;
 }
 
+string GetOpt::generate_usage(const string &argv0) const
+{
+       string result = argv0;
+       for(list<OptBase *>::const_iterator i=opts.begin(); i!=opts.end(); ++i)
+       {
+               result += " [";
+               if((*i)->get_short())
+               {
+                       result += format("-%c", (*i)->get_short());
+                       if(!(*i)->get_long().empty())
+                               result += '|';
+                       else if((*i)->get_arg_type()==OPTIONAL_ARG)
+                               result += format("[%s]", (*i)->get_metavar());
+                       else if((*i)->get_arg_type()==REQUIRED_ARG)
+                               result += format(" %s", (*i)->get_metavar());
+               }
+               if(!(*i)->get_long().empty())
+               {
+                       result += format("--%s", (*i)->get_long());
+
+                       if((*i)->get_arg_type()==OPTIONAL_ARG)
+                               result += format("[=%s]", (*i)->get_metavar());
+                       else if((*i)->get_arg_type()==REQUIRED_ARG)
+                               result += format("=%s", (*i)->get_metavar());
+               }
+               result += ']';
+       }
+
+       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)
+               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)
+       {
+               string swtch;
+               if((*i)->get_short())
+               {
+                       swtch += format("-%c", (*i)->get_short());
+                       if(!(*i)->get_long().empty())
+                               swtch += ", ";
+                       else if((*i)->get_arg_type()==OPTIONAL_ARG)
+                               swtch += format("[%s]", (*i)->get_metavar());
+                       else if((*i)->get_arg_type()==REQUIRED_ARG)
+                               swtch += format(" %s", (*i)->get_metavar());
+               }
+               else if(any_short)
+                       swtch += "    ";
+               if(!(*i)->get_long().empty())
+               {
+                       swtch += format("--%s", (*i)->get_long());
+
+                       if((*i)->get_arg_type()==OPTIONAL_ARG)
+                               swtch += format("[=%s]", (*i)->get_metavar());
+                       else if((*i)->get_arg_type()==REQUIRED_ARG)
+                               swtch += format("=%s", (*i)->get_metavar());
+               }
+               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 += 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):
        shrt(s),
        lng(l),
        arg_type(a),
        seen_count(0),
+       ext_seen_count(0),
        metavar("ARG")
-{ }
+{
+       if(lng.empty())
+               throw invalid_argument("empty long option name");
+}
 
 GetOpt::OptBase &GetOpt::OptBase::set_help(const string &h)
 {
-       help=h;
+       help = h;
        return *this;
 }
 
 GetOpt::OptBase &GetOpt::OptBase::set_help(const string &h, const string &m)
 {
-       help=h;
-       metavar=m;
+       help = h;
+       metavar = m;
+       return *this;
+}
+
+GetOpt::OptBase &GetOpt::OptBase::bind_seen_count(unsigned &c)
+{
+       ext_seen_count = &c;
        return *this;
 }
 
 void GetOpt::OptBase::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();
 }
@@ -259,8 +267,10 @@ void GetOpt::OptBase::process()
 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;
+       if(ext_seen_count)
+               *ext_seen_count = seen_count;
 
        store(arg);
 }