first check-in of feisty meow codebase. many things broken still due to recent
[feisty_meow.git] / core / library / application / command_line.cpp
1 /*****************************************************************************\
2 *                                                                             *
3 *  Name   : command_line                                                      *
4 *  Author : Chris Koeritz                                                     *
5 *                                                                             *
6 *******************************************************************************
7 * Copyright (c) 1992-$now By Author.  This program is free software; you can  *
8 * redistribute it and/or modify it under the terms of the GNU General Public  *
9 * License as published by the Free Software Foundation; either version 2 of   *
10 * the License or (at your option) any later version.  This is online at:      *
11 *     http://www.fsf.org/copyleft/gpl.html                                    *
12 * Please send any updates to: fred@gruntose.com                               *
13 \*****************************************************************************/
14
15 #include "command_line.h"
16
17 #include <basis/functions.h>
18 #include <basis/astring.h>
19 #include <basis/mutex.h>
20 #include <configuration/application_configuration.h>
21 #include <filesystem/directory.h>
22 #include <filesystem/filename.h>
23 #include <structures/static_memory_gremlin.h>
24 #include <structures/string_array.h>
25 #include <textual/parser_bits.h>
26 #include <loggers/program_wide_logger.h>
27
28 #undef LOG
29 #define LOG(s) CLASS_EMERGENCY_LOG(program_wide_logger::get(), s)
30
31 using namespace basis;
32 using namespace configuration;
33 using namespace filesystem;
34 using namespace loggers;
35 using namespace structures;
36 using namespace textual;
37
38 namespace application {
39
40 DEFINE_ARGC_AND_ARGV;
41
42 command_parameter::command_parameter(parameter_types type)
43 : _type(type), _text(new astring) {}
44
45 command_parameter::command_parameter(parameter_types type, const astring &text)
46 : _type(type), _text(new astring(text)) {}
47
48 command_parameter::command_parameter(const command_parameter &to_copy)
49 : _type(VALUE), _text(new astring)
50 { *this = to_copy; }
51
52 command_parameter::~command_parameter() { WHACK(_text); }
53
54 const astring &command_parameter::text() const { return *_text; }
55
56 void command_parameter::text(const astring &new_text) { *_text = new_text; }
57
58 command_parameter &command_parameter::operator =
59     (const command_parameter &to_copy)
60 {
61   if (this == &to_copy) return *this;
62   _type = to_copy._type;
63   *_text = *to_copy._text;
64   return *this;
65 }
66
67 //////////////
68
69 // option_prefixes: the list of valid prefixes for options on a command line.
70 // these are the characters that precede command line arguments.  For Unix,
71 // the default is a dash (-), while for DOS most programs use forward-slash
72 // (/).  Adding more characters is trivial; just add a character to the list
73 // before the sentinel of '\0'.
74 #if defined(_MSC_VER) || defined(__MINGW32__)
75   static char option_prefixes[] = { '-', '/', '\0' };
76 #elif defined(__UNIX__)
77   static char option_prefixes[] = { '-', '\0' };
78 #else
79   #error "I don't know what kind of operating system this is."
80 #endif
81
82 bool it_is_a_prefix_char(char to_test)
83 {
84   for (int i = 0; option_prefixes[i]; i++)
85     if (to_test == option_prefixes[i]) return true;
86   return false;
87 }
88
89 //////////////
90
91 class internal_cmd_line_array_of_parms : public array<command_parameter> {};
92
93 //////////////
94
95 SAFE_STATIC_CONST(command_parameter, command_line::cmdline_blank_parm, )
96   // our default return for erroneous indices.
97
98 command_line::command_line(int argc, char *argv[])
99 : _implementation(new internal_cmd_line_array_of_parms),
100   _program_name(new filename(directory::absolute_path(argv[0])))
101 {
102   argv++;  // skip command name in argv.
103
104   // loop over the rest of the fields and examine them.
105   string_array string_list;  // accumulated below.
106   while (--argc > 0) {
107     astring to_store = argv[0];  // retrieve the current string.
108     string_list += to_store;  // put the string in our list.
109     argv++;  // next string.
110   }
111   parse_string_array(string_list);
112 }
113
114 command_line::command_line(const astring &full_line)
115 : _implementation(new internal_cmd_line_array_of_parms),
116   _program_name(new filename)
117 {
118   astring accumulator;
119   string_array string_list;
120   bool in_quote = false;
121 //hmmm: this is not quote right yet.
122 //      use the separate command line method, but get it to run iteratively
123 //      so we can keep pulling them apart?  maybe it already does!
124 //      separate is better because it handles escaped quotes.
125   for (int i = 0; i < full_line.length(); i++) {
126     char to_examine = full_line.get(i);
127     if (to_examine == '"') {
128       // it's a quote character, so maybe we can start eating spaces.
129       if (!in_quote) {
130         in_quote = true;
131         continue;  // eat the quote character but change modes.
132       }
133       // nope, we're closing a quote.  we assume that the quotes are
134       // around the whole argument.  that's the best win32 can do at least.
135       in_quote = false;
136       to_examine = ' ';  // trick parser into logging the accumulated string.
137       // intentional fall-through to space case.
138     }
139
140     if (parser_bits::white_space(to_examine)) {
141       // if this is a white space, then we start a new string.
142       if (!in_quote && accumulator.t()) {
143         // only grab the accumulator if there are some contents.
144         string_list += accumulator;
145         accumulator = "";
146       } else if (in_quote) {
147         // we're stuffing the spaces into the string since we're quoted.
148         accumulator += to_examine;
149       }
150     } else {
151       // not white space, so save it in the accumulator.
152       accumulator += to_examine;
153     }
154   }
155   if (accumulator.t()) string_list += accumulator;
156     // that partial string wasn't snarfed during the loop.
157   // grab the program name off the list so the parsing occurs as expected.
158   *_program_name = directory::absolute_path(string_list[0]);
159   string_list.zap(0, 0);
160   parse_string_array(string_list);
161 }
162
163 command_line::~command_line()
164 {
165   WHACK(_program_name);
166   WHACK(_implementation);
167 }
168
169 int command_line::entries() const { return _implementation->length(); }
170
171 filename command_line::program_name() const { return *_program_name; }
172
173 const command_parameter &command_line::get(int field) const
174 {
175   bounds_return(field, 0, entries() - 1, cmdline_blank_parm());
176   return _implementation->get(field);
177 }
178
179 void command_line::separate_command_line(const astring &cmd_line,
180     astring &app, astring &parms)
181 {
182   char to_find = ' ';  // the command separator.
183   if (cmd_line[0] == '\"') to_find = '\"';
184     // if the first character is a quote, then we are seeing a quoted phrase
185     // and need to look for its completing quote.  otherwise, we'll just look
186     // for the next space.
187
188   int seek_posn = 1;  // skip the first character.  we have accounted for it.
189   // skim down the string, looking for the ending of the first phrase.
190   while (seek_posn < cmd_line.length()) {
191     // look for our parameter separator.  this will signify the end of the
192     // first phrase / chunk.  if we don't find it, then it should just mean
193     // there was only one item on the command line.
194     int indy = cmd_line.find(to_find, seek_posn);
195     if (negative(indy)) {
196       // yep, there wasn't a matching separator, so we think this is just
197       // one chunk--the app name.
198       app = cmd_line;
199       break;
200     } else {
201       // now that we know where our separator is, we need to find the right
202       // two parts (app and parms) based on the separator character in use.
203       if (to_find == '\"') {
204         // we are looking for a quote character to complete the app name.
205         if (cmd_line[indy - 1] == '\\') {
206           // we have a backslash escaping this quote!  keep seeking.
207           seek_posn = indy + 1;
208           continue;
209         }
210         app = cmd_line.substring(0, indy);
211         parms = cmd_line.substring(indy + 2, cmd_line.end());
212           // skip the quote and the obligatory space character after it.
213         break;
214       } else {
215         // simple space handling here; no escapes to worry about.
216         app = cmd_line.substring(0, indy - 1);
217         parms = cmd_line.substring(indy + 1, cmd_line.end());
218         break;
219       }
220     }
221   }
222 }
223
224 bool command_line::zap(int field)
225 {
226   bounds_return(field, 0, entries() - 1, false);
227   _implementation->zap(field, field);
228   return true;
229 }
230
231 // makes a complaint about a failure and sets the hidden commands to have a
232 // bogus entry so they aren't queried again.
233 #define COMPLAIN_CMDS(s) \
234   listo_cmds += "unknown"; \
235   COMPLAIN(s)
236
237 string_array command_line::get_command_line()
238 {
239 //  FUNCDEF("get_command_line");
240   string_array listo_cmds;
241   // the temporary string below can be given a flat formatting of the commands
242   // and it will be popped out into a list of arguments.
243   astring temporary;
244 #ifdef __UNIX__
245   if (!_global_argc || !_global_argv) {
246     // our global parameters have not been set, so we must calculate them.
247     temporary = application_configuration::get_cmdline_from_proc();
248   } else {
249     // we have easy access to command line arguments supposedly, so use them.
250     for (int i = 0; i < _global_argc; i++) {
251       // add a string entry for each argument.
252       listo_cmds += _global_argv[i];
253     }
254     // we don't need a long string to be parsed; the list is ready.
255     return listo_cmds;
256   }
257 #elif defined(__WIN32__)
258   // we have easy access to the original list of commands.
259   for (int i = 0; i < _global_argc; i++) {
260     // add a string entry for each argument.
261     listo_cmds += _global_argv[i];
262   }
263   return listo_cmds;
264 #else
265   COMPLAIN_CMDS("this OS doesn't support getting the command line.");
266   return listo_cmds;
267 #endif
268
269   // now that we have our best guess at a flat representation of the command
270   // line arguments, we'll chop it up.
271
272 //hmmm: this algorithm doesn't support spaces in filenames currently.
273 //hmmm: for windows, we can parse the quotes that should be around cmd name.
274 //hmmm: but for unix, the ps command doesn't support spaces either.  how to
275 //      get around that to support programs with spaces in the name?
276   int posn = 0;
277   int last_posn = -1;
278   while (posn < temporary.length()) {
279     posn = temporary.find(' ', posn);
280     if (non_negative(posn)) {
281       // found another space to turn into a portion of the command line.
282       listo_cmds += temporary.substring(last_posn + 1, posn - 1);
283         // grab the piece of string between the point just beyond where we
284         // last saw a space and the position just before the space.
285       last_posn = posn;  // save the last space position.
286       posn++;  // push the pointer past the space.
287     } else {
288       // no more spaces in the string.  grab what we can from the last bit
289       // of the string that we see.
290       if (last_posn < temporary.length() - 1) {
291         // there's something worthwhile grabbing after the last place we
292         // saw a space.
293         listo_cmds += temporary.substring(last_posn + 1,
294             temporary.length() - 1);
295       }
296       break;  // we're done finding spaces.
297     }
298   }
299
300   return listo_cmds;
301 }
302
303 astring command_line::text_form() const
304 {
305   astring to_return;
306   const astring EOL = parser_bits::platform_eol_to_chars();
307   for (int i = 0; i < entries(); i++) {
308     const command_parameter &curr = get(i);
309     to_return += a_sprintf("%d: ", i + 1);
310     switch (curr.type()) {
311       case command_parameter::CHAR_FLAG:
312         to_return += astring("<char flag> ") + curr.text() + EOL;
313         break;
314       case command_parameter::STRING_FLAG:
315         to_return += astring("<string flag> ") + curr.text() + EOL;
316         break;
317       case command_parameter::VALUE:  // pass through to default.
318       default:
319         to_return += astring("<value> ") + curr.text() + EOL;
320         break;
321     }
322   }
323   return to_return;
324 }
325
326 bool command_line::find(char option_character, int &index,
327     bool case_sense) const
328 {
329   astring opt(option_character, 1);  // convert to a string once here.
330   if (!case_sense) opt.to_lower();  // no case-sensitivity.
331   for (int i = index; i < entries(); i++) {
332 //hmmm: optimize this too.
333     if (get(i).type() == command_parameter::CHAR_FLAG) {
334       bool success = (!case_sense && get(i).text().iequals(opt))
335           || (case_sense && (get(i).text() == opt));
336       if (success) {
337         // the type is appropriate and the value is correct as well...
338         index = i;
339         return true;
340       }
341     }
342   }
343   return false;
344 }
345
346 bool command_line::find(const astring &option_string, int &index,
347     bool case_sense) const
348 {
349   FUNCDEF("find");
350 if (option_string.length() && (option_string[0] == '-') )
351 LOG(astring("found option string with dash!  string is: ") + option_string);
352
353   for (int i = index; i < entries(); i++) {
354     if (get(i).type() == command_parameter::STRING_FLAG) {
355       bool success = (!case_sense && get(i).text().iequals(option_string))
356           || (case_sense && (get(i).text() == option_string));
357       if (success) {
358         // the type is appropriate and the value is correct as well...
359         index = i;
360         return true;
361       }
362     }
363   }
364   return false;
365 }
366
367 bool command_line::get_value(char option_character, astring &value,
368     bool case_sense) const
369 {
370   value = "";
371   int posn = 0;  // where we find the flag.
372   if (!find(option_character, posn, case_sense)) return false;
373
374   // get the value after the flag, if there is such.
375   posn++;  // this is where we think our flag's value lives.
376   if (posn >= entries()) return false;
377
378   // there's still an entry after where we found our flag; grab it.
379   command_parameter cp = get(posn);
380   if (cp.type() != command_parameter::VALUE) return false;
381
382   // finally; we've found an appropriate text value.
383   value = cp.text();
384   return true;
385 }
386
387 bool command_line::get_value(const astring &option_string, astring &value,
388     bool case_sense) const
389 {
390   FUNCDEF("get_value");
391 if (option_string.length() && (option_string[0] == '-') )
392 LOG(astring("found option string with dash!  string is: ") + option_string);
393
394   value = "";
395   int posn = 0;  // where we find the flag.
396   if (!find(option_string, posn, case_sense)) return false;
397
398   // get the value after the flag, if there is such.
399   posn++;  // this is where we think our flag's value lives.
400   if (posn >= entries()) return false;
401
402   // there's still an entry after where we found our flag; grab it.
403   command_parameter cp = get(posn);
404   if (cp.type() != command_parameter::VALUE) return false;
405
406   // finally; we've found an appropriate text value.
407   value = cp.text();
408   return true;
409 }
410
411 void command_line::parse_string_array(const string_array &to_parse)
412 {
413   bool still_looking_for_flags = true;  // goes to false when only values left.
414   // loop over the fields and examine them.
415   for (int i = 0; i < to_parse.length(); i++) {
416     // retrieve a character from the current string.
417     int index = 0;
418     char c = to_parse[i].get(index++);
419     // we check whether it's a prefix character, and if so, what kind.
420     if (still_looking_for_flags && it_is_a_prefix_char(c)) {
421       // at least one prefix is there, so treat this as a flag.
422       bool gnu_type_of_flag = false;
423       if (it_is_a_prefix_char(to_parse[i].get(index))) {
424         // there's a special GNU double flag beginner.
425         index++;  // skip that extra one.
426         if ( (index >= to_parse[i].length())
427             || parser_bits::white_space(to_parse[i].get(index))) {
428           // special case of '--' (or '//' i suppose) with white space or
429           // nothing else afterwards; indicates that the rest of the items
430           // should just be values, not flags.
431           still_looking_for_flags = false;
432           continue;  // we ate that item.
433         }
434         gnu_type_of_flag = true;
435       }
436       // everything after the prefixes is considered part of the flag; they're
437       // either individual flag characters (on a single prefix) or they're the
438       // full name for the flag (gnu style).
439       c = 1;  // reset to a true bool value.
440       astring gnu_accumulator;  // if processing a gnu flag, it arrives here.
441       while (c) {
442         if (!gnu_type_of_flag) {
443           // add as many flag parameters as possible.
444           c = to_parse[i].get(index++);
445             // c will be zero once we hit the end of the string.
446           if (c) {
447             command_parameter to_add(command_parameter::CHAR_FLAG, astring(c, 1));
448             *_implementation += to_add;
449           }
450         } else {
451           // the gnu flag name is added to here.
452           c = to_parse[i].get(index++);  // zero at end of string.
453           if (c)
454             gnu_accumulator += c;  // one more character.
455         }
456       }
457       if (gnu_accumulator.t()) {
458         // we've accumulated a gnu flag, so store it.
459         command_parameter to_add(command_parameter::STRING_FLAG,
460             gnu_accumulator);
461         *_implementation += to_add;
462       }
463     } else {
464       // add a value type of command_parameter.
465       astring found = to_parse[i];
466       command_parameter to_add(command_parameter::VALUE, found);
467       *_implementation += to_add;
468     }
469   }
470 }
471
472 astring command_line::gather(int &index) const
473 {
474   astring to_return;
475   for (int i = index; i < entries(); i++) {
476     if (get(i).type() == command_parameter::CHAR_FLAG) {
477       index = i;
478       return to_return;
479     } else to_return += get(i).text();
480   }
481   index = entries() - 1;
482   return to_return;
483 }
484
485 } //namespace.
486