Hydra 0.20
|
00001 00002 /* 00003 * Copyright (c) 2009 Aleksander B. Demko 00004 * This source code is distributed under the MIT license. 00005 * See the accompanying file LICENSE.MIT.txt for details. 00006 */ 00007 00008 #ifndef INCLUDED_HYDRA_ARGUMENTPARSER_H__ 00009 #define INCLUDED_HYDRA_ARGUMENTPARSER_H__ 00010 00011 #include <QCoreApplication> 00012 #include <QStringList> 00013 00014 namespace hydra 00015 { 00016 class ArgumentParser; 00017 } 00018 00019 /** 00020 * Parses command line arguments ("parameters") in a QDirIterator-like manner. 00021 * 00022 * The first parameter is always the program name itself. You can remove 00023 * it by calling next() immediatly. 00024 * 00025 * Typically, you repeadedly call next() in a while(hasNext()) loop. 00026 * You can also has* methods 00027 * to forward-inspect the stream. 00028 * 00029 * @author Aleksander Demko 00030 */ 00031 class hydra::ArgumentParser 00032 { 00033 public: 00034 class Exception : public std::exception 00035 { 00036 public: 00037 virtual const char* what(void) const throw(); 00038 }; 00039 class ErrorException : public Exception { 00040 public: 00041 ErrorException(const QString &errormsg); 00042 virtual ~ErrorException() throw () { } 00043 virtual const char* what(void) const throw(); 00044 private: 00045 QByteArray dm_msg; 00046 }; 00047 //class BadParamException 00048 class HelpException : public Exception { }; 00049 00050 public: 00051 /** 00052 * Initializes the parser with the given argument list. 00053 * It uses the QCoreApplication arguments by default. 00054 * 00055 * @author Aleksander Demko 00056 */ 00057 ArgumentParser(const QStringList &args = QCoreApplication::arguments()); 00058 00059 /** 00060 * Is there a switch or a parameter available? 00061 * A switch begins with a - or --, everything else is a parameter. 00062 * Note the the program name is the first parameter, always. 00063 * 00064 * @author Aleksander Demko 00065 */ 00066 bool hasNext(void) const; 00067 /** 00068 * Is there a parameter available? 00069 * 00070 * @author Aleksander Demko 00071 */ 00072 bool hasNextParam(void) const; 00073 00074 /** 00075 * Returns the next switch or parameter. 00076 * Examples "-s", "--switch", "blah". Switches are returned verbatem, 00077 * hyphens and all. 00078 * 00079 * Throws ArgsEmptyException on error. You can pre-test via hasNext 00080 * 00081 * @author Aleksander Demko 00082 */ 00083 QString next(bool *isswitch = 0); 00084 00085 /** 00086 * Gets the next param, throws if empty. 00087 * 00088 * @param switchName is only used for exception generation purposes 00089 * @author Aleksander Demko 00090 */ 00091 QString nextParam(const QString &switchName = 0); 00092 00093 private: 00094 void parse(const QStringList &args); 00095 void pushSwitches(const QString &s); 00096 00097 private: 00098 QStringList dm_args; 00099 QList<bool> dm_isswitch; 00100 }; 00101 00102 #endif 00103