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
39 #include <anna/config/defines.hpp>
40 #include <anna/core/RuntimeException.hpp>
41 #include <anna/xml/xml.hpp>
43 #include <anna/core/util/CommandLine.hpp>
44 #include <anna/core/util/Tokenizer.hpp>
49 //--------------------------------------------------------------------------------
50 // Notifica al Parser que la opcion 'argumentExpression' es soportada
52 // (1) Verifica que la opcion no haya sido registrada previamente.
53 //--------------------------------------------------------------------------------
54 void CommandLine::add(const char* argumentExpression, Argument::Type type, const char* comment, const bool needValue)
56 Guard guard(a_mutex, "CommandLine::add");
58 std::string arg1 = "", arg2 = "";
59 if (!argumentExpression) { std::cerr << "Invalid argument expression: cannot register NULL literal on command-line" << std::endl; return; }
61 anna::Tokenizer expression;
62 expression.apply (argumentExpression, ",");
63 if (expression.size() > 2) { std::cerr << "Invalid argument expression '" << argumentExpression << "': only '<letter>[,<word>]' or '<word>[,<letter>]' are supported for command-line registration" << std::endl; return; }
65 anna::Tokenizer::const_iterator tok_it = expression.begin();
66 arg1 = anna::Tokenizer::data(tok_it);
67 // No leading hyphens in the name:
68 if (arg1[0] == '-') { std::cerr << "Invalid argument expression '" << argumentExpression << "': no leading hyphens allowed in argument names for command-line registration" << std::endl; return; }
71 if (tok_it != expression.end()) {
72 arg2 = anna::Tokenizer::data(tok_it);
73 // No hyphens in the name:
74 if (arg2[0] == '-') { std::cerr << "Invalid argument expression '" << argumentExpression << "': no leading hyphens allowed in argument names for command-line registration" << std::endl; return; }
77 // swap to have first non empty:
78 if (arg1 == "") { arg1 = arg2; arg2 = ""; }
80 // If both provided, one will be single letter and the other, a word:
84 if ((s1 + s2) == 2) { std::cerr << "Invalid argument expression '" << argumentExpression << "': only '<letter>[,<word>]' or '<word>[,<letter>]' are supported for command-line registration (provided two letters !)" << std::endl; return; }
85 if ((s1 != 1) && (s2 != 1)) { std::cerr << "Invalid argument expression '" << argumentExpression << "': only '<letter>[,<word>]' or '<word>[,<letter>]' are supported for command-line registration (provided two words !)" << std::endl; return; }
89 a_arguments.push_back(new Variable(arg1, arg2, type, comment, needValue));
92 void CommandLine::initialize(const char** argv, const int argc, int positionalArguments)
93 throw(RuntimeException) {
94 if (argc < 1) throw RuntimeException("Provided argc < 1 as command-line argv size !", ANNA_FILE_LOCATION);
95 if (positionalArguments < 0) throw RuntimeException("Provided negative number of positional arguments as command-line initializer", ANNA_FILE_LOCATION);
96 if (positionalArguments > (argc-1)) throw RuntimeException("Provided positional arguments > (argc - 1) as command-line initializer", ANNA_FILE_LOCATION);
97 a_positionalArguments = positionalArguments;
103 //--------------------------------------------------------------------------------
104 // Verifica que todos los argumentos declarados como obligatorios estan en la
105 // linea de comandos.
106 //--------------------------------------------------------------------------------
107 void CommandLine::verify()
108 throw(RuntimeException) {
110 throw RuntimeException("CommandLine was not initialized", ANNA_FILE_LOCATION);
112 for(int i = 0, maxi = a_arguments.size(); i < maxi; i ++) {
113 if(a_arguments [i]->getType() == Argument::Mandatory)
114 getValue(a_arguments [i]->getName1().c_str()); // exit program if not found (exitOnFault = true by default)
118 //--------------------------------------------------------------------------------
119 // Obtiene el valor para opcion 'argumentExpression'.
121 // (1) Realiza el analisis de la linea de comandos.
122 // (2) Verifica que la opcion recibida existe en la lista de opciones registradas.
123 // (3) Si la opcion 'argumentExpression' existe en la linea de comandos ...
124 // (3.1) Si el argumentExpression debe ir seguido por un valor/valores y no existe
126 // (3.2) Si el argumentExpression no necesita valor, simplemente, le asigna una cadena
127 // que contiene 'true', en otro caso devolvera NULL.
129 // (4) Si no existe en la linea de comandos y es un argumentExpression obligatorio => error.
131 // Si el arguemento solicitado no esta en la LC y es opcional devolvera NULL.
132 //--------------------------------------------------------------------------------
133 const char* CommandLine::getValue(const char* argumentExpression, const bool exitOnFault)
135 const char* result = NULL;
136 const Variable* argument = NULL;
140 if((analized = analize()) == true) { // (1)
141 if((argument = search(argumentExpression)) != NULL) { // (2)
143 result = argument->getValue();
145 if(argument->getIsOn() == true) { // (3)
146 if(argument->getNeedValue() == true && result == NULL) // (3.1)
148 else if(argument->getNeedValue() == false) {
154 } else if(argument->getType() == Argument::Mandatory) // (4)
159 if(analized == false) {
162 } else if(error == true && exitOnFault == true) {
163 cout << "Variable: '" << argumentExpression << "' is not valid" << endl << endl;
171 // Auxiliary function:
172 // Returns first no-leading hyphen position
173 int removeLeadingHyphens(std::string &argv) throw() {
175 // Move until no hyphen:
176 for (int i=0; i < argv.size(); i++)
177 if (argv[i] != '-') { startPos = i; argv = argv.substr(i); break; }
180 if (startPos == -1) return -1;
184 if (argv.size() != 1) return -1;
188 if (argv.size() == 1) return -1;
191 if (startPos > 2) return -1;
196 //--------------------------------------------------------------------------------
197 // Analize command line to store the arguments
198 //--------------------------------------------------------------------------------
199 bool CommandLine::analize()
203 int i = a_positionalArguments + 1;
206 if(a_wasParsed == true) // already analyzed
209 Guard guard(a_mutex, "CommandLine::analyze");
211 if(a_wasParsed == true)
215 while(i < a_argc && result == true) {
218 if (::removeLeadingHyphens(aux) == -1) {
222 if((variable = const_cast <Variable*>(search(aux.c_str()))) != NULL) {
223 variable->setIsOn(true);
224 if (variable->getNeedValue()) {
226 if (i < a_argc) { variable->setValue(a_argv[i]); }
227 else { result = false ; break; }
231 cout << "Variable: " << aux << " unreconized" << endl;
239 return (a_wasParsed = result);
242 const CommandLine::Variable* CommandLine::search(const char *argumentExpression) const
244 if (!argumentExpression) return NULL;
245 std::string name1, name2, arg;
247 vector <Variable*>::const_iterator arg_min(a_arguments.begin()), arg_max(a_arguments.end()), arg_it;
250 anna::Tokenizer expression;
251 expression.apply (argumentExpression, ",");
252 if (expression.size() > 2) return NULL;
254 anna::Tokenizer::const_iterator tok_it;
255 for (tok_it = expression.begin(); tok_it != expression.end(); tok_it++) { // one or two
256 arg = anna::Tokenizer::data(tok_it);
257 for(arg_it = arg_min; arg_it != arg_max; arg_it++) {
258 name1 = (*arg_it)->getName1();
259 name2 = (*arg_it)->getName2();
260 if ((name1 != "") && (name1 == arg)) return *arg_it;
261 if ((name2 != "") && (name2 == arg)) return *arg_it;
268 string CommandLine::Variable::getHelpExpression() const
270 std::string long_name, short_name, result = "";
272 int s1 = a_name1.size();
273 int s2 = a_name2.size();
274 if ((s1 + s2) > 2) { // both provided
275 if (s1 > 1) { short_name = a_name2; long_name = a_name1; }
276 else { short_name = a_name1; long_name = a_name2; }
277 if (short_name != "") {
279 result += short_name;
282 if (long_name != "") {
289 if (s1 > 1) result = "-";
296 void CommandLine::printUsage() const
298 int i, maxi(a_arguments.size());
299 cout << "Use: " << a_argv [0] << " ";
301 for(i = 0; i < maxi; i ++)
302 cout << a_arguments [i]->asString() << " ";
304 cout << endl << "Where: " << endl;
306 for(i = 0; i < maxi; i ++) {
307 cout << " " << a_arguments [i]->getHelpExpression() << ": " << endl;
308 cout << " " << a_arguments [i]->getComment() << endl;
312 string CommandLine::Variable::asString() const
315 result = ((a_type == Argument::Optional) ? "[ " : "");
316 result += getHelpExpression();
317 if(a_needValue == true) result += " <value>"; // result += " <value_"; result += a_name; result += ">";
318 if(a_type == Argument::Optional) result += " ]";
323 string CommandLine::asString() const
325 string result = "Provided command-line parameters:\n\n";
326 vector <Variable*>::const_iterator ii, maxii;
329 for(int pos = 1; pos <= a_positionalArguments; pos++)
330 result += anna::functions::asString("Positional argument [%d]: %s\n", pos, getPositional(pos));
332 for(ii = a_arguments.begin(), maxii = a_arguments.end(); ii != maxii; ii ++) {
333 value = (*ii)->getValue();
336 result += (*ii)->getHelpExpression();
346 xml::Node* CommandLine::asXML(xml::Node* parent) const throw() {
347 xml::Node* result = parent->createChild("CommandLine");
348 vector <Variable*>::const_iterator ii, maxii;
351 for(int pos = 1; pos <= a_positionalArguments; pos++)
352 result->createAttribute(anna::functions::asString("PositionalArgument_%d", pos).c_str(), getPositional(pos));
354 for(ii = a_arguments.begin(), maxii = a_arguments.end(); ii != maxii; ii ++) {
355 value = (*ii)->getValue();
358 result->createAttribute((*ii)->getHelpExpression().c_str(), value);