lemon/arg_parser.h
changeset 842 c2ff0a365245
parent 440 88ed40ad0d4f
child 877 141f9c0db4a3
     1.1 --- a/lemon/arg_parser.h	Fri Feb 12 22:24:26 2010 +0100
     1.2 +++ b/lemon/arg_parser.h	Sun Feb 14 19:23:55 2010 +0100
     1.3 @@ -34,6 +34,44 @@
     1.4  
     1.5  namespace lemon {
     1.6  
     1.7 +  ///Exception used by ArgParser
     1.8 +  class ArgParserException : public Exception {
     1.9 +  public:
    1.10 +    enum Reason {
    1.11 +      HELP,         /// <tt>--help</tt> option was given
    1.12 +      UNKNOWN_OPT,  /// Unknown option was given
    1.13 +      INVALID_OPT   /// Invalid combination of options
    1.14 +    };
    1.15 +    
    1.16 +  private:
    1.17 +    Reason _reason;
    1.18 +    
    1.19 +  public:
    1.20 +    ///Constructor
    1.21 +    ArgParserException(Reason r) throw() : _reason(r) {}
    1.22 +    ///Virtual destructor
    1.23 +    virtual ~ArgParserException() throw() {}
    1.24 +    ///A short description of the exception
    1.25 +    virtual const char* what() const throw() {
    1.26 +      switch(_reason)
    1.27 +        {
    1.28 +        case HELP:
    1.29 +          return "lemon::ArgParseException: ask for help";
    1.30 +          break;
    1.31 +        case UNKNOWN_OPT:
    1.32 +          return "lemon::ArgParseException: unknown option";
    1.33 +          break;
    1.34 +        case INVALID_OPT:
    1.35 +          return "lemon::ArgParseException: invalid combination of options";
    1.36 +          break;
    1.37 +        }
    1.38 +      return "";
    1.39 +    }
    1.40 +    ///Return the reason for the failure
    1.41 +    Reason reason() const {return _reason; }
    1.42 +  };
    1.43 +
    1.44 +
    1.45    ///Command line arguments parser
    1.46  
    1.47    ///\ingroup misc
    1.48 @@ -103,7 +141,7 @@
    1.49      std::vector<std::string> _file_args;
    1.50      std::string _command_name;
    1.51  
    1.52 -
    1.53 +    
    1.54    private:
    1.55      //Bind a function to an option.
    1.56  
    1.57 @@ -116,6 +154,10 @@
    1.58                      const std::string &help,
    1.59                      void (*func)(void *),void *data);
    1.60  
    1.61 +    bool _exit_on_problems;
    1.62 +    
    1.63 +    void _terminate(ArgParserException::Reason reason) const;
    1.64 +
    1.65    public:
    1.66  
    1.67      ///Constructor
    1.68 @@ -380,6 +422,11 @@
    1.69      ///not starting with a '-' character.
    1.70      const std::vector<std::string> &files() const { return _file_args; }
    1.71  
    1.72 +    ///Throw instead of exit in case of problems
    1.73 +    void throwOnProblems() 
    1.74 +    {
    1.75 +      _exit_on_problems=false;
    1.76 +    }
    1.77    };
    1.78  }
    1.79