GNU-style for command line. No positional arguments accepted. Supported single/double...
[anna.git] / include / anna / core / util / CommandLine.hpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // http://redmine.teslayout.com/projects/anna-suite
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
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
16 // distribution.
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.
20 //
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.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #ifndef anna_core_util_CommandLine_hpp
38 #define anna_core_util_CommandLine_hpp
39
40 #include <stdlib.h>
41
42 #include <vector>
43
44 #include <anna/core/functions.hpp>
45 #include <anna/core/Singleton.hpp>
46
47 namespace anna {
48
49 class RuntimeException;
50
51 namespace xml {
52 class Node;
53 }
54
55
56 /**
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.
60 */
61 class CommandLine : public Singleton <CommandLine> {
62
63   /* returns first no-leading hyphen position; -1 is error */
64   static int removeLeadingHyphens(std::string &argv) throw();
65
66 public:
67   /**
68      Define los tipos de argumento
69
70   */
71   struct Argument { enum Type { Mandatory = 0, Optional};  };
72
73   // Accesores
74   /**
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.
77   */
78   const char** getArgv() const throw() { return a_argv; }
79
80   /**
81      @return El numero de parametros indicados en la linea de comandos al ejecutar este programa.
82   */
83   int getArgc() const throw() { return a_argc; }
84
85   //
86   // Metodos
87   //
88   /**
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.
92
93      Recibe una copia de los parametros que los recibidos por el metodo 'main'.
94
95      @param argv Conjunto de cadenas que se reciben de la linea de comandos.
96      @param argc Numero de cadenas recibidas.
97   */
98   void initialize(const char** argv, const int argc) throw() {
99     a_argv = argv;
100     a_argc = argc;
101     a_wasParsed = false;
102   }
103
104   /**
105      Register an argument name in our application
106
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).
113    */
114   void add(const char* argumentExpression, Argument::Type type, const char* comment, const bool needValue = true) throw();
115
116   /**
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.
122
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.
127
128      @return Valor asociadoal argumento recibido como parametro. Puede ser NULL.
129   */
130   const char* getValue(const char* argumentExpression, const bool exitOnFault = true) throw();
131
132   /**
133      Obtiene el valor asociado al argumento recibido, pero convirtiendo a
134      numero el valor obtenido por #getValue.
135
136      @param argumentExpression You should look for the registered expression (#add), internally tokenized if needed.
137
138      @return Valor numerico del valor devuelto por #getValue.
139   */
140   int getIntegerValue(const char* argumentExpression) throw() { return atoi(getValue(argumentExpression)); }
141
142   /**
143      Comprueba si el argumento recibido como parametro estña presente en la linea de
144      comandos.
145
146      @param argumentExpression You should look for the registered expression (#add), internally tokenized if needed.
147
148      @return true si el argumento esta en la linea de comandos y false en otro caso.
149    */
150   bool exists(const char* argumentExpression) throw() { return (getValue(argumentExpression, false) != NULL) ? true : false; }
151
152   /**
153     Comprueba la linea de comandos del programa para verificar que coincide con los argumentos
154     registrados por nuestra aplicacion:
155
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.
161
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.
164   */
165   void verify() throw(RuntimeException);
166
167
168   /**
169      Class string representation
170      \return String with relevant information for this instance.
171   */
172   std::string asString() const throw();
173
174   /**
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.
178   */
179   xml::Node* asXML(xml::Node* parent) const throw();
180
181
182 private:
183   Mutex a_mutex;
184
185   class Variable {
186   public:
187     // Constructors
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) {
190     }
191     virtual ~Variable() { if(a_value) free(a_value); }
192
193     // Accesores
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; }
202
203     // Modificadores
204     void setValue(const char* value) throw() { a_value = (value == NULL) ? NULL : strdup(value); }
205     void setIsOn(const bool isOn) throw() { a_isOn = isOn; }
206
207     // Metodos
208     std::string asString() const throw();
209
210   protected:
211     std::string a_name1, a_name2;
212     const char* a_comment;
213     char* a_value;
214     Argument::Type a_type;
215     bool a_needValue;
216     bool a_isOn;
217   };
218
219   const char **a_argv;
220   int a_argc;
221   bool a_wasParsed;
222   std::vector <Variable*> a_arguments;
223
224   CommandLine() : a_argv(NULL), a_argc(0)  {;}
225
226   bool analize() throw();
227   const Variable* search(const char *argumentExpression) const throw();
228   void printUsage() const throw();
229
230   friend class Singleton <CommandLine>;
231 };
232
233 }
234
235 #endif
236