1 // ANNA - Anna is Not Nothingness Anymore
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
5 // http://redmine.teslayout.com/projects/anna-suite
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
11 // * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 // * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
17 // * Neither the name of the copyright holder nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 // Authors: eduardo.ramos.testillano@gmail.com
34 // cisco.tierra@gmail.com
37 #ifndef anna_core_util_CommandLine_hpp
38 #define anna_core_util_CommandLine_hpp
44 #include <anna/core/functions.hpp>
45 #include <anna/core/Singleton.hpp>
49 class RuntimeException;
57 Command line parser helper for our application. It's close to GNU-style, supporting
58 single letter (single hyphen) and long argument names (double hyphen). No bare hyphen
59 or double-dash end of parsing separator are supported. No positional arguments are supported.
61 class CommandLine : public Singleton <CommandLine> {
63 /* returns first no-leading hyphen position; -1 is error */
64 static int removeLeadingHyphens(std::string &argv) throw();
68 Define los tipos de argumento
71 struct Argument { enum Type { Mandatory = 0, Optional}; };
75 @return la lista de cadenas indicadas en la linea de comandos al ejecutar este programa.
76 Mientras que no invoquemos al metodo #initialize devolvera NULL.
78 const char** getArgv() const throw() { return a_argv; }
81 @return El numero de parametros indicados en la linea de comandos al ejecutar este programa.
83 int getArgc() const throw() { return a_argc; }
89 Establece la informacion necesaria para analizar la linea de comandos
90 indicada por el usuario. Debe invocarse antes que cualquier otro metodo
91 relacionado con la obtencion/comprobacion de valor de la linea de comandos.
93 Recibe una copia de los parametros que los recibidos por el metodo 'main'.
95 @param argv Conjunto de cadenas que se reciben de la linea de comandos.
96 @param argc Numero de cadenas recibidas.
98 void initialize(const char** argv, const int argc) throw() {
105 Register an argument name in our application
107 @param argumentExpression Argument name, or comma-separated set with both short and long argument names. For example 'v,version', 'h,help', or simply 'f' or 'file'. If both,
108 provided, one of them shall be a single letter and the other will be a word. In other case, nothing will be registered. Command line arguments stands for -<single letter option>
109 and --<word option> when proceed. If NULL provided, nothing is done.
110 @param type Argument type. See Variable#Type.
111 @param comment Argument explanation.
112 @param needValue If our argument has an additional associated value, this will be true. False in other case (flags).
114 void add(const char* argumentExpression, Argument::Type type, const char* comment, const bool needValue = true) throw();
117 Obtiene el valor asociado al argumento recibido como parametro.
118 El valor devuelto puede ser NULL en caso de que el argumento no sea
119 obligatorio y no este en la linea de comandos.
120 Si el argumento es obligatorio y no este en la linea de comandos o
121 no tiene valor asociado la ejecucion del programa TERMINA inmediatamente.
123 @param argumentExpression You should look for the registered expression (#add), internally tokenized if needed.
124 @param exitOnFault Indica el funcionamiento del metodo en caso de que el
125 argumento solicitado no halla sido indicado. Si el parametro no existe
126 si vale @em true la aplicacion terminara, si vale @em false devolvera NULL.
128 @return Valor asociadoal argumento recibido como parametro. Puede ser NULL.
130 const char* getValue(const char* argumentExpression, const bool exitOnFault = true) throw();
133 Obtiene el valor asociado al argumento recibido, pero convirtiendo a
134 numero el valor obtenido por #getValue.
136 @param argumentExpression You should look for the registered expression (#add), internally tokenized if needed.
138 @return Valor numerico del valor devuelto por #getValue.
140 int getIntegerValue(const char* argumentExpression) throw() { return atoi(getValue(argumentExpression)); }
143 Comprueba si el argumento recibido como parametro estña presente en la linea de
146 @param argumentExpression You should look for the registered expression (#add), internally tokenized if needed.
148 @return true si el argumento esta en la linea de comandos y false en otro caso.
150 bool exists(const char* argumentExpression) throw() { return (getValue(argumentExpression, false) != NULL) ? true : false; }
153 Comprueba la linea de comandos del programa para verificar que coincide con los argumentos
154 registrados por nuestra aplicacion:
156 @li Verifica que los parametros obligatorios estan en la linea de comandos.
157 @li Verifica que los valores de los argumento son correctos de forma que si un parametro
158 debe llevar un valor asociado este esta presente y que si no debe llevarlo no esta.
159 El orden en que aparezcan los argumento en la linea de comandos es indiferente a la hora de
160 hacer las comprobacion.
162 Si hay algun fallo en la linea de comandos establecida al ejecutar el programa visualiza un
163 resumen con los parametros soportados y la ejecucion del programa finaliza.
165 void verify() throw(RuntimeException);
169 Class string representation
170 \return String with relevant information for this instance.
172 std::string asString() const throw();
175 Class xml representation
176 \param parent Parent XML node on which hold this instance information.
177 \return XML document with relevant information for this instance.
179 xml::Node* asXML(xml::Node* parent) const throw();
188 Variable(const std::string &name1, const std::string &name2, const Argument::Type type, const char* comment, const bool needValue = true) :
189 a_name1(name1), a_name2(name2), a_type(type), a_comment(comment), a_needValue(needValue), a_isOn(false), a_value(NULL) {
191 virtual ~Variable() { if(a_value) free(a_value); }
194 const std::string& getName1() const throw() { return a_name1; }
195 const std::string& getName2() const throw() { return a_name2; }
196 std::string getHelpExpression() const throw();
197 const char* getValue() const throw() { return a_value; }
198 const char* getComment() const throw() { return a_comment; }
199 bool getNeedValue() const throw() { return a_needValue; }
200 bool getIsOn() const throw() { return a_isOn; }
201 Argument::Type getType() const throw() { return a_type; }
204 void setValue(const char* value) throw() { a_value = (value == NULL) ? NULL : strdup(value); }
205 void setIsOn(const bool isOn) throw() { a_isOn = isOn; }
208 std::string asString() const throw();
211 std::string a_name1, a_name2;
212 const char* a_comment;
214 Argument::Type a_type;
222 std::vector <Variable*> a_arguments;
224 CommandLine() : a_argv(NULL), a_argc(0) {;}
226 bool analize() throw();
227 const Variable* search(const char *argumentExpression) const throw();
228 void printUsage() const throw();
230 friend class Singleton <CommandLine>;