GRASS GIS 7 Programmer's Manual  7.2.0(2016)-exported
parser.c
Go to the documentation of this file.
1 /*!
2  * \file lib/gis/parser.c
3  *
4  * \brief GIS Library - Argument parsing functions.
5  *
6  * Parses the command line provided through argc and argv. Example:
7  * Assume the previous calls:
8  *
9  \code
10  opt1 = G_define_option() ;
11  opt1->key = "map",
12  opt1->type = TYPE_STRING,
13  opt1->required = YES,
14  opt1->checker = sub,
15  opt1->description= "Name of an existing raster map" ;
16 
17  opt2 = G_define_option() ;
18  opt2->key = "color",
19  opt2->type = TYPE_STRING,
20  opt2->required = NO,
21  opt2->answer = "white",
22  opt2->options = "red,orange,blue,white,black",
23  opt2->description= "Color used to display the map" ;
24 
25  opt3 = G_define_option() ;
26  opt3->key = "number",
27  opt3->type = TYPE_DOUBLE,
28  opt3->required = NO,
29  opt3->answer = "12345.67",
30  opt3->options = "0-99999",
31  opt3->description= "Number to test parser" ;
32  \endcode
33  *
34  * G_parser() will respond to the following command lines as described:
35  *
36  \verbatim
37  command (No command line arguments)
38  \endverbatim
39  * Parser enters interactive mode.
40  *
41  \verbatim
42  command map=map.name
43  \endverbatim
44  * Parser will accept this line. Map will be set to "map.name", the
45  * 'a' and 'b' flags will remain off and the num option will be set
46  * to the default of 5.
47  *
48  \verbatim
49  command -ab map=map.name num=9
50  command -a -b map=map.name num=9
51  command -ab map.name num=9
52  command map.name num=9 -ab
53  command num=9 -a map=map.name -b
54  \endverbatim
55  * These are all treated as acceptable and identical. Both flags are
56  * set to on, the map option is "map.name" and the num option is "9".
57  * Note that the "map=" may be omitted from the command line if it
58  * is part of the first option (flags do not count).
59  *
60  \verbatim
61  command num=12
62  \endverbatim
63  * This command line is in error in two ways. The user will be told
64  * that the "map" option is required and also that the number 12 is
65  * out of range. The acceptable range (or list) will be printed.
66  *
67  * Overview table: <a href="parser_standard_options.html">Parser standard options</a>
68  *
69  * (C) 2001-2015 by the GRASS Development Team
70  *
71  * This program is free software under the GNU General Public License
72  * (>=v2). Read the file COPYING that comes with GRASS for details.
73  *
74  * \author Original author CERL
75  * \author Soeren Gebbert added Dec. 2009 WPS process_description document
76  */
77 
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <string.h>
81 #include <unistd.h>
82 
83 #include <grass/gis.h>
84 #include <grass/spawn.h>
85 #include <grass/glocale.h>
86 
87 #include "parser_local_proto.h"
88 
89 enum opt_error {
93  AMBIGUOUS = 4,
95 };
96 
97 #define KEYLENGTH 64
98 
99 #define MAX_MATCHES 50
100 
101 /* initialize the global struct */
102 struct state state;
103 struct state *st = &state;
104 
105 /* local prototypes */
106 static void set_flag(int);
107 static int contains(const char *, int);
108 static int valid_option_name(const char *);
109 static int is_option(const char *);
110 static int match_option_1(const char *, const char *);
111 static int match_option(const char *, const char *);
112 static void set_option(const char *);
113 static void check_opts(void);
114 static void check_an_opt(const char *, int, const char *, const char **, char **);
115 static int check_int(const char *, const char **);
116 static int check_double(const char *, const char **);
117 static int check_string(const char *, const char **, int *);
118 static void check_required(void);
119 static void split_opts(void);
120 static void check_multiple_opts(void);
121 static int check_overwrite(void);
122 static void define_keywords(void);
123 static void split_gisprompt(const char *, char *, char *, char *);
124 static int module_gui_wx(void);
125 static void append_error(const char *);
126 static const char *get_renamed_option(const char *);
127 
128 /*!
129  * \brief Disables the ability of the parser to operate interactively.
130  *
131  * When a user calls a command with no arguments on the command line,
132  * the parser will enter its own standardized interactive session in
133  * which all flags and options are presented to the user for input. A
134  * call to G_disable_interactive() disables the parser's interactive
135  * prompting.
136  *
137  */
138 
140 {
141  st->no_interactive = 1;
142 }
143 
144 /*!
145  * \brief Initializes a Flag struct.
146  *
147  * Allocates memory for the Flag structure and returns a pointer to
148  * this memory.
149  *
150  * Flags are always represented by single letters. A user "turns them
151  * on" at the command line using a minus sign followed by the
152  * character representing the flag.
153  *
154  * \return Pointer to a Flag struct
155  */
156 struct Flag *G_define_flag(void)
157 {
158  struct Flag *flag;
159  struct Item *item;
160 
161  /* Allocate memory if not the first flag */
162 
163  if (st->n_flags) {
164  flag = G_malloc(sizeof(struct Flag));
165  st->current_flag->next_flag = flag;
166  }
167  else
168  flag = &st->first_flag;
169 
170  /* Zero structure */
171 
172  G_zero(flag, sizeof(struct Flag));
173 
174  st->current_flag = flag;
175  st->n_flags++;
176 
177  if (st->n_items) {
178  item = G_malloc(sizeof(struct Item));
179  st->current_item->next_item = item;
180  }
181  else
182  item = &st->first_item;
183 
184  G_zero(item, sizeof(struct Item));
185 
186  item->flag = flag;
187  item->option = NULL;
188 
189  st->current_item = item;
190  st->n_items++;
191 
192  return (flag);
193 }
194 
195 /*!
196  * \brief Initializes an Option struct.
197  *
198  * Allocates memory for the Option structure and returns a pointer to
199  * this memory.
200  *
201  * Options are provided by user on command line using the standard
202  * format: <i>key=value</i>. Options identified as REQUIRED must be
203  * specified by user on command line. The option string can either
204  * specify a range of values (e.g. "10-100") or a list of acceptable
205  * values (e.g. "red,orange,yellow"). Unless the option string is
206  * NULL, user provided input will be evaluated against this string.
207  *
208  * \return pointer to an Option struct
209  */
210 struct Option *G_define_option(void)
211 {
212  struct Option *opt;
213  struct Item *item;
214 
215  /* Allocate memory if not the first option */
216 
217  if (st->n_opts) {
218  opt = G_malloc(sizeof(struct Option));
219  st->current_option->next_opt = opt;
220  }
221  else
222  opt = &st->first_option;
223 
224  /* Zero structure */
225  G_zero(opt, sizeof(struct Option));
226 
227  opt->required = NO;
228  opt->multiple = NO;
229 
230  st->current_option = opt;
231  st->n_opts++;
232 
233  if (st->n_items) {
234  item = G_malloc(sizeof(struct Item));
235  st->current_item->next_item = item;
236  }
237  else
238  item = &st->first_item;
239 
240  G_zero(item, sizeof(struct Item));
241 
242  item->option = opt;
243 
244  st->current_item = item;
245  st->n_items++;
246 
247  return (opt);
248 }
249 
250 /*!
251  * \brief Initializes a new module.
252  *
253  * \return pointer to a GModule struct
254  */
255 struct GModule *G_define_module(void)
256 {
257  struct GModule *module;
258 
259  /* Allocate memory */
260  module = &st->module_info;
261 
262  /* Zero structure */
263  G_zero(module, sizeof(struct GModule));
264 
265  /* Allocate keywords array */
266  define_keywords();
267 
268  return (module);
269 }
270 
271 /*!
272  * \brief Parse command line.
273  *
274  * The command line parameters <i>argv</i> and the number of
275  * parameters <i>argc</i> from the main() routine are passed directly
276  * to G_parser(). G_parser() accepts the command line input entered by
277  * the user, and parses this input according to the input options
278  * and/or flags that were defined by the programmer.
279  *
280  * <b>Note:</b> The only functions which can legitimately be called
281  * before G_parser() are:
282  *
283  * - G_gisinit()
284  * - G_no_gisinit()
285  * - G_define_module()
286  * - G_define_flag()
287  * - G_define_option()
288  * - G_define_standard_flag()
289  * - G_define_standard_option()
290  * - G_disable_interactive()
291  * - G_option_exclusive()
292  * - G_option_required()
293  * - G_option_requires()
294  * - G_option_requires_all()
295  * - G_option_excludes()
296  * - G_option_collective()
297  *
298  * The usual order a module calls functions is:
299  *
300  * 1. G_gisinit()
301  * 2. G_define_module()
302  * 3. G_define_standard_flag()
303  * 4. G_define_standard_option()
304  * 5. G_define_flag()
305  * 6. G_define_option()
306  * 7. G_option_exclusive()
307  * 8. G_option_required()
308  * 9. G_option_requires()
309  * 10. G_option_requires_all()
310  * 11. G_option_excludes()
311  * 12. G_option_collective()
312  * 13. G_parser()
313  *
314  * \param argc number of arguments
315  * \param argv argument list
316  *
317  * \return 0 on success
318  * \return -1 on error and calls G_usage()
319  */
320 int G_parser(int argc, char **argv)
321 {
322  int need_first_opt;
323  int opt_checked = 0;
324  const char *gui_envvar;
325  char *ptr, *tmp_name, *err;
326  int i;
327  struct Option *opt;
328  char force_gui = FALSE;
329 
330  err = NULL;
331  need_first_opt = 1;
332  tmp_name = G_store(argv[0]);
333  st->pgm_path = tmp_name;
334  st->n_errors = 0;
335  st->error = NULL;
336  st->module_info.verbose = G_verbose_std();
337  i = strlen(tmp_name);
338  while (--i >= 0) {
339  if (G_is_dirsep(tmp_name[i])) {
340  tmp_name += i + 1;
341  break;
342  }
343  }
344  G_basename(tmp_name, "exe");
345  st->pgm_name = tmp_name;
346 
347  /* Stash default answers */
348 
349  opt = &st->first_option;
350  while (st->n_opts && opt) {
351  if (opt->required)
352  st->has_required = 1;
353 
354  if (!valid_option_name(opt->key))
355  G_warning(_("BUG in option name, '%s' is not valid"), opt->key);
356 
357  /* Parse options */
358  if (opt->options) {
359  int cnt = 0;
360  char **tokens, delm[2];
361 
362  delm[0] = ',';
363  delm[1] = '\0';
364  tokens = G_tokenize(opt->options, delm);
365 
366  i = 0;
367  while (tokens[i]) {
368  G_chop(tokens[i]);
369  cnt++;
370  i++;
371  }
372 
373  opt->opts = G_calloc(cnt + 1, sizeof(const char *));
374 
375  i = 0;
376  while (tokens[i]) {
377  opt->opts[i] = G_store(tokens[i]);
378  i++;
379  }
380  G_free_tokens(tokens);
381 
382  if (opt->descriptions) {
383  delm[0] = ';';
384 
385  opt->descs = G_calloc(cnt + 1, sizeof(const char *));
386  tokens = G_tokenize(opt->descriptions, delm);
387 
388  i = 0;
389  while (tokens[i]) {
390  int j, found;
391 
392  if (!tokens[i + 1])
393  break;
394 
395  G_chop(tokens[i]);
396 
397  j = 0;
398  found = 0;
399  while (opt->opts[j]) {
400  if (strcmp(opt->opts[j], tokens[i]) == 0) {
401  found = 1;
402  break;
403  }
404  j++;
405  }
406  if (!found) {
407  G_warning(_("BUG in descriptions, option '%s' in <%s> does not exist"),
408  tokens[i], opt->key);
409  }
410  else {
411  opt->descs[j] = G_store(tokens[i + 1]);
412  }
413 
414  i += 2;
415  }
416  G_free_tokens(tokens);
417  }
418  }
419 
420  /* Copy answer */
421  if (opt->multiple && opt->answers && opt->answers[0]) {
422  opt->answer = G_malloc(strlen(opt->answers[0]) + 1);
423  strcpy(opt->answer, opt->answers[0]);
424  for (i = 1; opt->answers[i]; i++) {
425  opt->answer = G_realloc(opt->answer,
426  strlen(opt->answer) +
427  strlen(opt->answers[i]) + 2);
428  strcat(opt->answer, ",");
429  strcat(opt->answer, opt->answers[i]);
430  }
431  }
432  opt->def = opt->answer;
433  opt = opt->next_opt;
434  }
435 
436  /* If there are NO arguments, go interactive */
437  gui_envvar = G_getenv_nofatal("GUI");
438  if (argc < 2 && (st->has_required || G__has_required_rule())
439  && !st->no_interactive && isatty(0) &&
440  (gui_envvar && G_strcasecmp(gui_envvar, "text") != 0)) {
441  if (module_gui_wx() == 0)
442  return -1;
443  }
444 
445  if (argc < 2 && st->has_required && isatty(0)) {
446  G_usage();
447  return -1;
448  }
449  else if (argc >= 2) {
450 
451  /* If first arg is "help" give a usage/syntax message */
452  if (strcmp(argv[1], "help") == 0 ||
453  strcmp(argv[1], "-help") == 0 || strcmp(argv[1], "--help") == 0) {
454  G_usage();
455  exit(EXIT_SUCCESS);
456  }
457 
458  /* If first arg is "--help-text" give a usage/syntax message
459  * with machine-readable sentinels */
460  if (strcmp(argv[1], "--help-text") == 0) {
461  G__usage_text();
462  exit(EXIT_SUCCESS);
463  }
464 
465  /* If first arg is "--interface-description" then print out
466  * a xml description of the task */
467  if (strcmp(argv[1], "--interface-description") == 0) {
468  G__usage_xml();
469  exit(EXIT_SUCCESS);
470  }
471 
472  /* If first arg is "--html-description" then print out
473  * a html description of the task */
474  if (strcmp(argv[1], "--html-description") == 0) {
475  G__usage_html();
476  exit(EXIT_SUCCESS);
477  }
478 
479  /* If first arg is "--rst-description" then print out
480  * a reStructuredText description of the task */
481  if (strcmp(argv[1], "--rst-description") == 0) {
482  G__usage_rest();
483  exit(EXIT_SUCCESS);
484  }
485 
486  /* If first arg is "--wps-process-description" then print out
487  * the wps process description of the task */
488  if (strcmp(argv[1], "--wps-process-description") == 0) {
490  exit(EXIT_SUCCESS);
491  }
492 
493  /* If first arg is "--script" then then generate
494  * g.parser boilerplate */
495  if (strcmp(argv[1], "--script") == 0) {
496  G__script();
497  exit(EXIT_SUCCESS);
498  }
499 
500  /* Loop through all command line arguments */
501 
502  while (--argc) {
503  ptr = *(++argv);
504 
505  if (strcmp(ptr, "help") == 0 || strcmp(ptr, "--h") == 0 ||
506  strcmp(ptr, "-help") == 0 || strcmp(ptr, "--help") == 0) {
507  G_usage();
508  exit(EXIT_SUCCESS);
509  }
510 
511  /* Overwrite option */
512  if (strcmp(ptr, "--o") == 0 || strcmp(ptr, "--overwrite") == 0) {
513  st->overwrite = 1;
514  }
515 
516  /* Verbose option */
517  else if (strcmp(ptr, "--v") == 0 || strcmp(ptr, "--verbose") == 0) {
518  char buff[32];
519 
520  /* print everything: max verbosity level */
521  st->module_info.verbose = G_verbose_max();
522  sprintf(buff, "GRASS_VERBOSE=%d", G_verbose_max());
523  putenv(G_store(buff));
524  if (st->quiet == 1) {
525  G_warning(_("Use either --quiet or --verbose flag, not both. Assuming --verbose."));
526  }
527  st->quiet = -1;
528  }
529 
530  /* Quiet option */
531  else if (strcmp(ptr, "--q") == 0 || strcmp(ptr, "--quiet") == 0) {
532  char buff[32];
533 
534  /* print nothing, but errors and warnings */
535  st->module_info.verbose = G_verbose_min();
536  sprintf(buff, "GRASS_VERBOSE=%d", G_verbose_min());
537  putenv(G_store(buff));
538  if (st->quiet == -1) {
539  G_warning(_("Use either --quiet or --verbose flag, not both. Assuming --quiet."));
540  }
541  st->quiet = 1; /* for passing to gui init */
542  }
543 
544  /* Super quiet option */
545  else if (strcmp(ptr, "--qq") == 0 ) {
546  char buff[32];
547 
548  /* print nothing, but errors */
549  st->module_info.verbose = G_verbose_min();
550  sprintf(buff, "GRASS_VERBOSE=%d", G_verbose_min());
551  putenv(G_store(buff));
553  if (st->quiet == -1) {
554  G_warning(_("Use either --qq or --verbose flag, not both. Assuming --qq."));
555  }
556  st->quiet = 1; /* for passing to gui init */
557  }
558 
559  /* Force gui to come up */
560  else if (strcmp(ptr, "--ui") == 0) {
561  force_gui = TRUE;
562  }
563 
564  /* If we see a flag */
565  else if (*ptr == '-') {
566  while (*(++ptr))
567  set_flag(*ptr);
568 
569  }
570  /* If we see standard option format (option=val) */
571  else if (is_option(ptr)) {
572  set_option(ptr);
573  need_first_opt = 0;
574  }
575 
576  /* If we see the first option with no equal sign */
577  else if (need_first_opt && st->n_opts) {
578  st->first_option.answer = G_store(ptr);
579  st->first_option.count++;
580  need_first_opt = 0;
581  }
582 
583  /* If we see the non valid argument (no "=", just argument) */
584  else {
585  G_asprintf(&err, _("Sorry <%s> is not a valid option"), ptr);
586  append_error(err);
587  }
588 
589  }
590  }
591 
592  /* Split options where multiple answers are OK */
593  split_opts();
594 
595  /* Run the gui if it was specifically requested */
596  if (force_gui) {
597  if (module_gui_wx() != 0)
598  G_fatal_error(_("Your installation doesn't include GUI, exiting."));
599  return -1;
600  }
601 
602  /* Check multiple options */
603  check_multiple_opts();
604 
605  /* Check answers against options and check subroutines */
606  if (!opt_checked)
607  check_opts();
608 
609  /* Make sure all required options are set */
610  if (!st->suppress_required)
611  check_required();
612 
614 
615  if (st->n_errors > 0) {
616  if (G_verbose() > -1) {
617  if (G_verbose() > G_verbose_min())
618  G_usage();
619  fprintf(stderr, "\n");
620  for (i = 0; i < st->n_errors; i++) {
621  fprintf(stderr, "%s: %s\n", _("ERROR"), st->error[i]);
622  }
623  }
624  return -1;
625  }
626 
627  if (check_overwrite())
628  return -1;
629 
630  return 0;
631 }
632 
633 /*!
634  * \brief Creates command to run non-interactive.
635  *
636  * Creates a command-line that runs the current command completely
637  * non-interactive.
638  *
639  * \param original_path TRUE if original path should be used, FALSE for
640  * stripped and clean name of the module
641  * \return pointer to a char string
642  */
643 char *recreate_command(int original_path)
644 {
645  char *buff;
646  char flg[4];
647  char *cur;
648  const char *tmp;
649  struct Flag *flag;
650  struct Option *opt;
651  int n, len, slen;
652  int nalloced = 0;
653 
654  G_debug(3, "G_recreate_command()");
655 
656  /* Flag is not valid if there are no flags to set */
657 
658  buff = G_calloc(1024, sizeof(char));
659  nalloced += 1024;
660  if (original_path)
661  tmp = G_original_program_name();
662  else
663  tmp = G_program_name();
664  len = strlen(tmp);
665  if (len >= nalloced) {
666  nalloced += (1024 > len) ? 1024 : len + 1;
667  buff = G_realloc(buff, nalloced);
668  }
669  cur = buff;
670  strcpy(cur, tmp);
671  cur += len;
672 
673  if (st->overwrite) {
674  slen = strlen(" --overwrite");
675  if (len + slen >= nalloced) {
676  nalloced += (1024 > len) ? 1024 : len + 1;
677  buff = G_realloc(buff, nalloced);
678  }
679  strcpy(cur, " --overwrite");
680  cur += slen;
681  len += slen;
682  }
683 
684  if (st->module_info.verbose != G_verbose_std()) {
685  char *sflg;
686  if (st->module_info.verbose == G_verbose_max())
687  sflg = " --verbose";
688  else
689  sflg = " --quiet";
690 
691  slen = strlen(sflg);
692  if (len + slen >= nalloced) {
693  nalloced += (1024 > len) ? 1024 : len + 1;
694  buff = G_realloc(buff, nalloced);
695  }
696  strcpy(cur, sflg);
697  cur += slen;
698  len += slen;
699  }
700 
701  if (st->n_flags) {
702  flag = &st->first_flag;
703  while (flag) {
704  if (flag->answer == 1) {
705  flg[0] = ' ';
706  flg[1] = '-';
707  flg[2] = flag->key;
708  flg[3] = '\0';
709  slen = strlen(flg);
710  if (len + slen >= nalloced) {
711  nalloced +=
712  (nalloced + 1024 > len + slen) ? 1024 : slen + 1;
713  buff = G_realloc(buff, nalloced);
714  cur = buff + len;
715  }
716  strcpy(cur, flg);
717  cur += slen;
718  len += slen;
719  }
720  flag = flag->next_flag;
721  }
722  }
723 
724  opt = &st->first_option;
725  while (st->n_opts && opt) {
726  if (opt->answer && opt->answer[0] == '\0') { /* answer = "" */
727  slen = strlen(opt->key) + 4; /* +4 for: ' ' = " " */
728  if (len + slen >= nalloced) {
729  nalloced += (nalloced + 1024 > len + slen) ? 1024 : slen + 1;
730  buff = G_realloc(buff, nalloced);
731  cur = buff + len;
732  }
733  strcpy(cur, " ");
734  cur++;
735  strcpy(cur, opt->key);
736  cur = strchr(cur, '\0');
737  strcpy(cur, "=");
738  cur++;
739  if (opt->type == TYPE_STRING) {
740  strcpy(cur, "\"\"");
741  cur += 2;
742  }
743  len = cur - buff;
744  } else if (opt->answer && opt->answers && opt->answers[0]) {
745  slen = strlen(opt->key) + strlen(opt->answers[0]) + 4; /* +4 for: ' ' = " " */
746  if (len + slen >= nalloced) {
747  nalloced += (nalloced + 1024 > len + slen) ? 1024 : slen + 1;
748  buff = G_realloc(buff, nalloced);
749  cur = buff + len;
750  }
751  strcpy(cur, " ");
752  cur++;
753  strcpy(cur, opt->key);
754  cur = strchr(cur, '\0');
755  strcpy(cur, "=");
756  cur++;
757  if (opt->type == TYPE_STRING) {
758  strcpy(cur, "\"");
759  cur++;
760  }
761  strcpy(cur, opt->answers[0]);
762  cur = strchr(cur, '\0');
763  len = cur - buff;
764  for (n = 1; opt->answers[n]; n++) {
765  if (!opt->answers[n])
766  break;
767  slen = strlen(opt->answers[n]) + 2; /* +2 for , " */
768  if (len + slen >= nalloced) {
769  nalloced +=
770  (nalloced + 1024 > len + slen) ? 1024 : slen + 1;
771  buff = G_realloc(buff, nalloced);
772  cur = buff + len;
773  }
774  strcpy(cur, ",");
775  cur++;
776  strcpy(cur, opt->answers[n]);
777  cur = strchr(cur, '\0');
778  len = cur - buff;
779  }
780  if (opt->type == TYPE_STRING) {
781  strcpy(cur, "\"");
782  cur++;
783  len = cur - buff;
784  }
785  }
786  opt = opt->next_opt;
787  }
788 
789  return buff;
790 }
791 
792 /*!
793  * \brief Creates command to run non-interactive.
794  *
795  * Creates a command-line that runs the current command completely
796  * non-interactive.
797  *
798  * \return pointer to a char string
799  */
801 {
802  return recreate_command(FALSE);
803 }
804 
805 /* TODO: update to docs of these 3 functions to whatever general purpose
806  * they have now. */
807 /*!
808  * \brief Creates command to run non-interactive.
809  *
810  * Creates a command-line that runs the current command completely
811  * non-interactive.
812  *
813  * This gives the same as G_recreate_command() but the original path
814  * from the command line is used instead of the module name only.
815  *
816  * \return pointer to a char string
817  */
819 {
820  return recreate_command(TRUE);
821 }
822 
823 /*!
824  \brief Add keyword to the list
825 
826  \param keyword keyword string
827 */
828 void G_add_keyword(const char *keyword)
829 {
830  if (st->n_keys >= st->n_keys_alloc) {
831  st->n_keys_alloc += 10;
832  st->module_info.keywords = G_realloc(st->module_info.keywords,
833  st->n_keys_alloc * sizeof(char *));
834  }
835 
836  st->module_info.keywords[st->n_keys++] = G_store(keyword);
837 }
838 
839 /*!
840  \brief Set keywords from the string
841 
842  \param keywords keywords separated by commas
843 */
844 void G_set_keywords(const char *keywords)
845 {
846  char **tokens = G_tokenize(keywords, ",");
847  st->module_info.keywords = (const char **)tokens;
848  st->n_keys = st->n_keys_alloc = G_number_of_tokens(tokens);
849 }
850 
851 
853 {
854  struct Option *opt;
855  char age[KEYLENGTH];
856  char element[KEYLENGTH];
857  char desc[KEYLENGTH];
858 
859  if (st->module_info.overwrite)
860  return 1;
861 
862  /* figure out if any of the options use a "new" gisprompt */
863  /* This is to see if we should spit out the --o flag */
864  if (st->n_opts) {
865  opt = &st->first_option;
866  while (opt) {
867  if (opt->gisprompt) {
868  split_gisprompt(opt->gisprompt, age, element, desc);
869  if (strcmp(age, "new") == 0)
870  return 1;
871  }
872  opt = opt->next_opt;
873  }
874  }
875 
876  return 0;
877 }
878 
879 /*!
880  \brief Print list of keywords (internal use only)
881 
882  If <em>format</em> function is NULL than list of keywords is printed
883  comma-separated.
884 
885  \param[out] fd file where to print
886  \param format pointer to print function
887 */
888 void G__print_keywords(FILE *fd, void (*format)(FILE *, const char *))
889 {
890  int i;
891 
892  for(i = 0; i < st->n_keys; i++) {
893  if (!format) {
894  fprintf(fd, "%s", st->module_info.keywords[i]);
895  }
896  else {
897  format(fd, st->module_info.keywords[i]);
898  }
899  if (i < st->n_keys - 1)
900  fprintf(fd, ", ");
901  }
902 
903  fflush(fd);
904 }
905 
906 /*!
907  \brief Get overwrite value
908 
909  \return 1 overwrite enabled
910  \return 0 overwrite disabled
911 */
913 {
914  return st->overwrite;
915 }
916 
917 void define_keywords(void)
918 {
919  st->n_keys = 0;
920  st->n_keys_alloc = 0;
921 }
922 
923 /**************************************************************************
924  *
925  * The remaining routines are all local (static) routines used to support
926  * the parsing process.
927  *
928  **************************************************************************/
929 
930 /*!
931  \brief Invoke GUI dialog
932 */
933 int module_gui_wx(void)
934 {
935  char script[GPATH_MAX];
936 
937  /* TODO: the 4 following lines seems useless */
938  if (!st->pgm_path)
939  st->pgm_path = G_program_name();
940  if (!st->pgm_path)
941  G_fatal_error(_("Unable to determine program name"));
942 
943  sprintf(script, "%s/gui/wxpython/gui_core/forms.py",
944  getenv("GISBASE"));
945  if (access(script, F_OK) != -1)
946  G_spawn(getenv("GRASS_PYTHON"), getenv("GRASS_PYTHON"),
948  else
949  return -1;
950 
951  return 0;
952 }
953 
954 void set_flag(int f)
955 {
956  struct Flag *flag;
957  char *err;
958 
959  err = NULL;
960 
961  /* Flag is not valid if there are no flags to set */
962  if (!st->n_flags) {
963  G_asprintf(&err, _("%s: Sorry, <%c> is not a valid flag"), G_program_name(), f);
964  append_error(err);
965  return;
966  }
967 
968  /* Find flag with corrrect keyword */
969  flag = &st->first_flag;
970  while (flag) {
971  if (flag->key == f) {
972  flag->answer = 1;
973  if (flag->suppress_required)
974  st->suppress_required = 1;
975  return;
976  }
977  flag = flag->next_flag;
978  }
979 
980  G_asprintf(&err, _("%s: Sorry, <%c> is not a valid flag"), G_program_name(), f);
981  append_error(err);
982 }
983 
984 /* contents() is used to find things strings with characters like commas and
985  * dashes.
986  */
987 int contains(const char *s, int c)
988 {
989  while (*s) {
990  if (*s == c)
991  return TRUE;
992  s++;
993  }
994  return FALSE;
995 }
996 
997 int valid_option_name(const char *string)
998 {
999  int m = strlen(string);
1000  int n = strspn(string, "abcdefghijklmnopqrstuvwxyz0123456789_");
1001 
1002  if (!m)
1003  return 0;
1004 
1005  if (m != n)
1006  return 0;
1007 
1008  if (string[m-1] == '_')
1009  return 0;
1010 
1011  return 1;
1012 }
1013 
1014 int is_option(const char *string)
1015 {
1016  int n = strspn(string, "abcdefghijklmnopqrstuvwxyz0123456789_");
1017 
1018  return n > 0 && string[n] == '=' && string[0] != '_' && string[n-1] != '_';
1019 }
1020 
1021 int match_option_1(const char *string, const char *option)
1022 {
1023  const char *next;
1024 
1025  if (*string == '\0')
1026  return 1;
1027 
1028  if (*option == '\0')
1029  return 0;
1030 
1031  if (*string == *option && match_option_1(string + 1, option + 1))
1032  return 1;
1033 
1034  if (*option == '_' && match_option_1(string, option + 1))
1035  return 1;
1036 
1037  next = strchr(option, '_');
1038  if (!next)
1039  return 0;
1040 
1041  if (*string == '_')
1042  return match_option_1(string + 1, next + 1);
1043 
1044  return match_option_1(string, next + 1);
1045 }
1046 
1047 int match_option(const char *string, const char *option)
1048 {
1049  return (*string == *option)
1050  && match_option_1(string + 1, option + 1);
1051 }
1052 
1053 void set_option(const char *string)
1054 {
1055  struct Option *at_opt = NULL;
1056  struct Option *opt = NULL;
1057  size_t key_len;
1058  char the_key[KEYLENGTH];
1059  char *ptr, *err;
1060  struct Option *matches[MAX_MATCHES];
1061  int found = 0;
1062 
1063  err = NULL;
1064 
1065  for (ptr = the_key; *string != '='; ptr++, string++)
1066  *ptr = *string;
1067  *ptr = '\0';
1068  string++;
1069 
1070  /* Find option with best keyword match */
1071  key_len = strlen(the_key);
1072  for (at_opt = &st->first_option; at_opt; at_opt = at_opt->next_opt) {
1073  if (!at_opt->key)
1074  continue;
1075 
1076  if (strcmp(the_key, at_opt->key) == 0) {
1077  matches[0] = at_opt;
1078  found = 1;
1079  break;
1080  }
1081 
1082  if (strncmp(the_key, at_opt->key, key_len) == 0 ||
1083  match_option(the_key, at_opt->key)) {
1084  if (found >= MAX_MATCHES)
1085  G_fatal_error("Too many matches (limit %d)", MAX_MATCHES);
1086  matches[found++] = at_opt;
1087  }
1088  }
1089 
1090  if (found > 1) {
1091  int shortest = 0;
1092  int length = strlen(matches[0]->key);
1093  int prefix = 1;
1094  int i;
1095  for (i = 1; i < found; i++) {
1096  int len = strlen(matches[i]->key);
1097  if (len < length) {
1098  length = len;
1099  shortest = i;
1100  }
1101  }
1102  for (i = 0; prefix && i < found; i++)
1103  if (strncmp(matches[i]->key, matches[shortest]->key, length) != 0)
1104  prefix = 0;
1105  if (prefix) {
1106  matches[0] = matches[shortest];
1107  found = 1;
1108  }
1109  else {
1110  G_asprintf(&err, _("%s: Sorry, <%s=> is ambiguous"), G_program_name(), the_key);
1111  append_error(err);
1112  for (i = 0; i < found; i++) {
1113  G_asprintf(&err, _("Option <%s=> matches"), matches[i]->key);
1114  append_error(err);
1115  }
1116  return;
1117  }
1118  }
1119 
1120  if (found)
1121  opt = matches[0];
1122 
1123  /* First, check if key has been renamed in GRASS 7 */
1124  if (found == 0) {
1125  const char *renamed_key = NULL;
1126 
1127  renamed_key = get_renamed_option(the_key);
1128  if (renamed_key) {
1129  for (at_opt = &st->first_option; at_opt; at_opt = at_opt->next_opt) {
1130  if (strcmp(renamed_key, at_opt->key) == 0) {
1131  G_warning(_("Please update the usage of <%s>: "
1132  "option <%s> has been renamed to <%s>"),
1133  G_program_name(), the_key, renamed_key);
1134  opt = at_opt;
1135  found = 1;
1136  break;
1137  }
1138  }
1139  }
1140  }
1141 
1142  /* If there is no match, complain */
1143  if (found == 0) {
1144  G_asprintf(&err, _("%s: Sorry, <%s> is not a valid parameter"), G_program_name(), the_key);
1145  append_error(err);
1146  return;
1147  }
1148 
1149  if (getenv("GRASS_FULL_OPTION_NAMES") && strcmp(the_key, opt->key) != 0)
1150  G_warning(_("<%s> is an abbreviation for <%s>"), the_key, opt->key);
1151 
1152  /* Allocate memory where answer is stored */
1153  if (opt->count++) {
1154  if (!opt->multiple) {
1155  G_asprintf(&err, _("Option <%s> does not accept multiple answers"), opt->key);
1156  append_error(err);
1157  }
1158  opt->answer = G_realloc(opt->answer,
1159  strlen(opt->answer) + strlen(string) + 2);
1160  strcat(opt->answer, ",");
1161  strcat(opt->answer, string);
1162  }
1163  else
1164  opt->answer = G_store(string);
1165 }
1166 
1167 void check_opts(void)
1168 {
1169  struct Option *opt;
1170  int ans;
1171 
1172  if (!st->n_opts)
1173  return;
1174 
1175  opt = &st->first_option;
1176  while (opt) {
1177  /* Check answer against options if any */
1178 
1179  if (opt->answer) {
1180  if (opt->multiple == 0)
1181  check_an_opt(opt->key, opt->type,
1182  opt->options, opt->opts, &opt->answer);
1183  else {
1184  for (ans = 0; opt->answers[ans] != '\0'; ans++)
1185  check_an_opt(opt->key, opt->type,
1186  opt->options, opt->opts, &opt->answers[ans]);
1187  }
1188  }
1189 
1190  /* Check answer against user's check subroutine if any */
1191 
1192  if (opt->checker)
1193  opt->checker(opt->answer);
1194 
1195  opt = opt->next_opt;
1196  }
1197 }
1198 
1199 void check_an_opt(const char *key, int type, const char *options,
1200  const char **opts, char **answerp)
1201 {
1202  const char *answer = *answerp;
1203  int error;
1204  char *err;
1205  int found;
1206 
1207  error = 0;
1208  err = NULL;
1209  found = 0;
1210 
1211  switch (type) {
1212  case TYPE_INTEGER:
1213  error = check_int(answer, opts);
1214  break;
1215  case TYPE_DOUBLE:
1216  error = check_double(answer, opts);
1217  break;
1218  case TYPE_STRING:
1219  error = check_string(answer, opts, &found);
1220  break;
1221  }
1222  switch (error) {
1223  case 0:
1224  break;
1225  case BAD_SYNTAX:
1226  G_asprintf(&err,
1227  _("Illegal range syntax for parameter <%s>\n"
1228  "\tPresented as: %s"), key, options);
1229  append_error(err);
1230  break;
1231  case OUT_OF_RANGE:
1232  G_asprintf(&err,
1233  _("Value <%s> out of range for parameter <%s>\n"
1234  "\tLegal range: %s"), answer, key, options);
1235  append_error(err);
1236  break;
1237  case MISSING_VALUE:
1238  G_asprintf(&err,
1239  _("Missing value for parameter <%s>"),
1240  key);
1241  append_error(err);
1242  break;
1243  case AMBIGUOUS:
1244  G_asprintf(&err,
1245  _("Value <%s> ambiguous for parameter <%s>\n"
1246  "\tValid options: %s"), answer, key, options);
1247  append_error(err);
1248  break;
1249  case REPLACED:
1250  *answerp = G_store(opts[found]);
1251  error = 0;
1252  break;
1253  }
1254 }
1255 
1256 int check_int(const char *ans, const char **opts)
1257 {
1258  int d, i;
1259 
1260  /* "-" is reserved for standard input */
1261  if (strcmp(ans, "-") == 0)
1262  return 0;
1263 
1264  if (sscanf(ans, "%d", &d) != 1)
1265  return MISSING_VALUE;
1266 
1267  if (!opts)
1268  return 0;
1269 
1270  for (i = 0; opts[i]; i++) {
1271  const char *opt = opts[i];
1272  int lo, hi;
1273 
1274  if (contains(opt, '-')) {
1275  if (sscanf(opt, "%d-%d", &lo, &hi) == 2) {
1276  if (d >= lo && d <= hi)
1277  return 0;
1278  }
1279  else if (sscanf(opt, "-%d", &hi) == 1) {
1280  if (d <= hi)
1281  return 0;
1282  }
1283  else if (sscanf(opt, "%d-", &lo) == 1) {
1284  if (d >= lo)
1285  return 0;
1286  }
1287  else
1288  return BAD_SYNTAX;
1289  }
1290  else {
1291  if (sscanf(opt, "%d", &lo) == 1) {
1292  if (d == lo)
1293  return 0;
1294  }
1295  else
1296  return BAD_SYNTAX;
1297  }
1298  }
1299 
1300  return OUT_OF_RANGE;
1301 }
1302 
1303 int check_double(const char *ans, const char **opts)
1304 {
1305  double d;
1306  int i;
1307 
1308  /* "-" is reserved for standard input */
1309  if (strcmp(ans, "-") == 0)
1310  return 0;
1311 
1312  if (sscanf(ans, "%lf", &d) != 1)
1313  return MISSING_VALUE;
1314 
1315  if (!opts)
1316  return 0;
1317 
1318  for (i = 0; opts[i]; i++) {
1319  const char *opt = opts[i];
1320  double lo, hi;
1321 
1322  if (contains(opt, '-')) {
1323  if (sscanf(opt, "%lf-%lf", &lo, &hi) == 2) {
1324  if (d >= lo && d <= hi)
1325  return 0;
1326  }
1327  else if (sscanf(opt, "-%lf", &hi) == 1) {
1328  if (d <= hi)
1329  return 0;
1330  }
1331  else if (sscanf(opt, "%lf-", &lo) == 1) {
1332  if (d >= lo)
1333  return 0;
1334  }
1335  else
1336  return BAD_SYNTAX;
1337  }
1338  else {
1339  if (sscanf(opt, "%lf", &lo) == 1) {
1340  if (d == lo)
1341  return 0;
1342  }
1343  else
1344  return BAD_SYNTAX;
1345  }
1346  }
1347 
1348  return OUT_OF_RANGE;
1349 }
1350 
1351 int check_string(const char *ans, const char **opts, int *result)
1352 {
1353  int len = strlen(ans);
1354  int found = 0;
1355  int matches[MAX_MATCHES];
1356  int i;
1357 
1358  if (!opts)
1359  return 0;
1360 
1361  for (i = 0; opts[i]; i++) {
1362  if (strcmp(ans, opts[i]) == 0)
1363  return 0;
1364  if (strncmp(ans, opts[i], len) == 0 || match_option(ans, opts[i])) {
1365  if (found >= MAX_MATCHES)
1366  G_fatal_error("too many matches (limit %d)", MAX_MATCHES);
1367  matches[found++] = i;
1368  }
1369  }
1370 
1371  if (found > 1) {
1372  int shortest = 0;
1373  int length = strlen(opts[matches[0]]);
1374  int prefix = 1;
1375  int i;
1376  for (i = 1; i < found; i++) {
1377  int len = strlen(opts[matches[i]]);
1378  if (len < length) {
1379  length = len;
1380  shortest = i;
1381  }
1382  }
1383  for (i = 0; prefix && i < found; i++)
1384  if (strncmp(opts[matches[i]], opts[matches[shortest]], length) != 0)
1385  prefix = 0;
1386  if (prefix) {
1387  matches[0] = matches[shortest];
1388  found = 1;
1389  }
1390  }
1391 
1392  if (found == 1)
1393  *result = matches[0];
1394 
1395  if (found > 0 && getenv("GRASS_FULL_OPTION_NAMES") && strcmp(ans, opts[matches[0]]) != 0)
1396  G_warning(_("<%s> is an abbreviation for <%s>"), ans, opts[matches[0]]);
1397 
1398  switch (found) {
1399  case 0: return OUT_OF_RANGE;
1400  case 1: return REPLACED;
1401  default: return AMBIGUOUS;
1402  }
1403 }
1404 
1405 void check_required(void)
1406 {
1407  struct Option *opt;
1408  char *err;
1409 
1410  err = NULL;
1411 
1412  if (!st->n_opts)
1413  return;
1414 
1415  opt = &st->first_option;
1416  while (opt) {
1417  if (opt->required && !opt->answer) {
1418  G_asprintf(&err, _("Required parameter <%s> not set:\n"
1419  "\t(%s)"),
1420  opt->key, (opt->label ? opt->label : opt->description));
1421  append_error(err);
1422  }
1423  opt = opt->next_opt;
1424  }
1425 }
1426 
1427 void split_opts(void)
1428 {
1429  struct Option *opt;
1430  const char *ptr1;
1431  const char *ptr2;
1432  int allocated;
1433  int ans_num;
1434  int len;
1435 
1436 
1437  if (!st->n_opts)
1438  return;
1439 
1440  opt = &st->first_option;
1441  while (opt) {
1442  if ( /*opt->multiple && */ opt->answer) {
1443  /* Allocate some memory to store array of pointers */
1444  allocated = 10;
1445  opt->answers = G_malloc(allocated * sizeof(char *));
1446 
1447  ans_num = 0;
1448  ptr1 = opt->answer;
1449  opt->answers[ans_num] = NULL;
1450 
1451  for (;;) {
1452  for (len = 0, ptr2 = ptr1; *ptr2 != '\0' && *ptr2 != ',';
1453  ptr2++, len++) ;
1454 
1455  if (len > 0) { /* skip ,, */
1456  opt->answers[ans_num] = G_malloc(len + 1);
1457  memcpy(opt->answers[ans_num], ptr1, len);
1458  opt->answers[ans_num][len] = 0;
1459 
1460  ans_num++;
1461 
1462  if (ans_num >= allocated) {
1463  allocated += 10;
1464  opt->answers = G_realloc(opt->answers,
1465  allocated * sizeof(char *));
1466  }
1467 
1468  opt->answers[ans_num] = NULL;
1469  }
1470 
1471  if (*ptr2 == '\0')
1472  break;
1473 
1474  ptr1 = ptr2 + 1;
1475 
1476  if (*ptr1 == '\0')
1477  break;
1478  }
1479  }
1480  opt = opt->next_opt;
1481  }
1482 }
1483 
1484 void check_multiple_opts(void)
1485 {
1486  struct Option *opt;
1487  const char *ptr;
1488  int n_commas;
1489  int n;
1490  char *err;
1491 
1492  if (!st->n_opts)
1493  return;
1494 
1495  err = NULL;
1496  opt = &st->first_option;
1497  while (opt) {
1498  /* "-" is reserved from standard input/output */
1499  if (opt->answer && strcmp(opt->answer, "-") && opt->key_desc) {
1500  /* count commas */
1501  n_commas = 1;
1502  for (ptr = opt->key_desc; *ptr != '\0'; ptr++)
1503  if (*ptr == ',')
1504  n_commas++;
1505  /* count items */
1506  for (n = 0; opt->answers[n] != '\0'; n++) ;
1507  /* if not correct multiple of items */
1508  if (n % n_commas) {
1509  G_asprintf(&err,
1510  _("Option <%s> must be provided in multiples of %d\n"
1511  "\tYou provided %d item(s): %s"),
1512  opt->key, n_commas, n, opt->answer);
1513  append_error(err);
1514 
1515  }
1516  }
1517  opt = opt->next_opt;
1518  }
1519 }
1520 
1521 /* Check for all 'new' if element already exists */
1522 int check_overwrite(void)
1523 {
1524  struct Option *opt;
1525  char age[KEYLENGTH];
1526  char element[KEYLENGTH];
1527  char desc[KEYLENGTH];
1528  int error = 0;
1529  const char *overstr;
1530  int over;
1531 
1532  st->module_info.overwrite = 0;
1533 
1534  if (!st->n_opts)
1535  return (0);
1536 
1537  over = 0;
1538  /* Check the GRASS OVERWRITE variable */
1539  if ((overstr = G_getenv_nofatal("OVERWRITE"))) {
1540  over = atoi(overstr);
1541  }
1542 
1543  /* Check the GRASS_OVERWRITE environment variable */
1544  if ((overstr = getenv("GRASS_OVERWRITE"))) {
1545  if (atoi(overstr))
1546  over = 1;
1547  }
1548 
1549  if (st->overwrite || over) {
1550  st->module_info.overwrite = 1;
1551  /* Set the environment so that programs run in a script also obey --o */
1552  putenv("GRASS_OVERWRITE=1");
1553  /* No need to check options for existing files if overwrite is true */
1554  return error;
1555  }
1556 
1557  opt = &st->first_option;
1558  while (opt) {
1559  if (opt->answer && opt->gisprompt) {
1560  split_gisprompt(opt->gisprompt, age, element, desc);
1561 
1562  if (strcmp(age, "new") == 0) {
1563  int i;
1564  char found;
1565 
1566  for (i = 0; opt->answers[i]; i++) {
1567  found = FALSE;
1568  if (strcmp(element, "file") == 0) {
1569  if (access(opt->answers[i], F_OK) == 0)
1570  found = TRUE;
1571  }
1572  else if (strcmp(element, "mapset") != 0) {
1573  /* TODO: also other elements should be
1574  probably skipped */
1575  if (G_find_file(element, opt->answers[i], G_mapset())) {
1576  found = TRUE;
1577  }
1578  }
1579 
1580  if (found) { /* found */
1581  if (!st->overwrite && !over) {
1582  if (G_verbose() > -1) {
1583  if (G_info_format() != G_INFO_FORMAT_GUI) {
1584  fprintf(stderr, _("ERROR: "));
1585  fprintf(stderr,
1586  _("option <%s>: <%s> exists. To overwrite, use the --overwrite flag"),
1587  opt->key, opt->answers[i]);
1588  fprintf(stderr, "\n");
1589  }
1590  else {
1591  fprintf(stderr, "GRASS_INFO_ERROR(%d,1): ", getpid());
1592  fprintf(stderr,
1593  _("option <%s>: <%s> exists. To overwrite, use the --overwrite flag"),
1594  opt->key, opt->answers[i]);
1595  fprintf(stderr, "\n");
1596  fprintf(stderr, "GRASS_INFO_END(%d,1)\n",
1597  getpid());
1598  }
1599  }
1600  error = 1;
1601  }
1602  }
1603  }
1604  }
1605  }
1606  opt = opt->next_opt;
1607  }
1608 
1609  return (error);
1610 }
1611 
1612 void split_gisprompt(const char *gisprompt, char *age, char *element,
1613  char *desc)
1614 {
1615  const char *ptr1;
1616  char *ptr2;
1617 
1618  for (ptr1 = gisprompt, ptr2 = age; *ptr1 != '\0'; ptr1++, ptr2++) {
1619  if (*ptr1 == ',')
1620  break;
1621  *ptr2 = *ptr1;
1622  }
1623  *ptr2 = '\0';
1624 
1625  for (ptr1++, ptr2 = element; *ptr1 != '\0'; ptr1++, ptr2++) {
1626  if (*ptr1 == ',')
1627  break;
1628  *ptr2 = *ptr1;
1629  }
1630  *ptr2 = '\0';
1631 
1632  for (ptr1++, ptr2 = desc; *ptr1 != '\0'; ptr1++, ptr2++) {
1633  if (*ptr1 == ',')
1634  break;
1635  *ptr2 = *ptr1;
1636  }
1637  *ptr2 = '\0';
1638 }
1639 
1640 void append_error(const char *msg)
1641 {
1642  st->error = G_realloc(st->error, sizeof(char *) * (st->n_errors + 1));
1643  st->error[st->n_errors++] = G_store(msg);
1644 }
1645 
1646 const char *get_renamed_option(const char *key)
1647 {
1648  const char *pgm, *key_new;
1649  char *pgm_key;
1650 
1651  if (!st->renamed_options) {
1652  /* read renamed options from file (renamed_options) */
1653  char path[GPATH_MAX];
1654 
1655  G_snprintf(path, GPATH_MAX, "%s/etc/renamed_options", G_gisbase());
1656  st->renamed_options = G_read_key_value_file(path);
1657  }
1658 
1659  /* try to check global changes first */
1660  key_new = G_find_key_value(key, st->renamed_options);
1661  if (key_new)
1662  return key_new;
1663 
1664  /* then check module-relevant changes */
1665  pgm = G_program_name();
1666  pgm_key = (char *) G_malloc (strlen(pgm) + strlen(key) + 2);
1667  G_asprintf(&pgm_key, "%s|%s", pgm, key);
1668 
1669  key_new = G_find_key_value(pgm_key, st->renamed_options);
1670  G_free(pgm_key);
1671 
1672  return key_new;
1673 }
1674 
1675 /*!
1676  \brief Get separator string from the option.
1677 
1678  Calls G_fatal_error() on error. Allocated string can be later freed
1679  by G_free().
1680 
1681  \code
1682  char *fs;
1683  struct Option *opt_fs;
1684 
1685  opt_fs = G_define_standard_option(G_OPT_F_SEP);
1686 
1687  if (G_parser(argc, argv))
1688  exit(EXIT_FAILURE);
1689 
1690  fs = G_option_to_separator(opt_fs);
1691  \endcode
1692 
1693  \param option pointer to separator option
1694 
1695  \return allocated string with separator
1696 */
1697 char* G_option_to_separator(const struct Option *option)
1698 {
1699  char* sep;
1700 
1701  if (option->gisprompt == NULL ||
1702  strcmp(option->gisprompt, "old,separator,separator") != 0)
1703  G_fatal_error(_("%s= is not a separator option"), option->key);
1704 
1705  if (option->answer == NULL)
1706  G_fatal_error(_("No separator given for %s="), option->key);
1707 
1708  if (strcmp(option->answer, "pipe") == 0)
1709  sep = G_store("|");
1710  else if (strcmp(option->answer, "comma") == 0)
1711  sep = G_store(",");
1712  else if (strcmp(option->answer, "space") == 0)
1713  sep = G_store(" ");
1714  else if (strcmp(option->answer, "tab") == 0 ||
1715  strcmp(option->answer, "\\t") == 0)
1716  sep = G_store("\t");
1717  else if (strcmp(option->answer, "newline") == 0 ||
1718  strcmp(option->answer, "\\n") == 0)
1719  sep = G_store("\n");
1720  else
1721  sep = G_store(option->answer);
1722 
1723  G_debug(3, "G_option_to_separator(): key = %s -> sep = '%s'",
1724  option->key, sep);
1725 
1726  return sep;
1727 }
1728 
1729 /*!
1730  \brief Get an input/output file pointer from the option. If the file name is
1731  omitted or '-', it returns either stdin or stdout based on the gisprompt.
1732 
1733  Calls G_fatal_error() on error. File pointer can be later closed by
1734  G_close_option_file().
1735 
1736  \code
1737  FILE *fp_input;
1738  FILE *fp_output;
1739  struct Option *opt_input;
1740  struct Option *opt_output;
1741 
1742  opt_input = G_define_standard_option(G_OPT_F_INPUT);
1743  opt_output = G_define_standard_option(G_OPT_F_OUTPUT);
1744 
1745  if (G_parser(argc, argv))
1746  exit(EXIT_FAILURE);
1747 
1748  fp_input = G_open_option_file(opt_input);
1749  fp_output = G_open_option_file(opt_output);
1750  ...
1751  G_close_option_file(fp_input);
1752  G_close_option_file(fp_output);
1753  \endcode
1754 
1755  \param option pointer to a file option
1756 
1757  \return file pointer
1758 */
1759 FILE *G_open_option_file(const struct Option *option)
1760 {
1761  int stdinout;
1762  FILE *fp;
1763 
1764  stdinout = !option->answer || !*(option->answer) ||
1765  strcmp(option->answer, "-") == 0;
1766 
1767  if (option->gisprompt == NULL)
1768  G_fatal_error(_("%s= is not a file option"), option->key);
1769  else if (option->multiple)
1770  G_fatal_error(_("Opening multiple files not supported for %s="),
1771  option->key);
1772  else if (strcmp(option->gisprompt, "old,file,file") == 0) {
1773  if (stdinout)
1774  fp = stdin;
1775  else if ((fp = fopen(option->answer, "r")) == NULL)
1776  G_fatal_error(_("Unable to open %s file <%s>"),
1777  option->key, option->answer);
1778  } else if (strcmp(option->gisprompt, "new,file,file") == 0) {
1779  if (stdinout)
1780  fp = stdout;
1781  else if ((fp = fopen(option->answer, "w")) == NULL)
1782  G_fatal_error(_("Unable to create %s file <%s>"),
1783  option->key, option->answer);
1784  } else
1785  G_fatal_error(_("%s= is not a file option"), option->key);
1786 
1787  return fp;
1788 }
1789 
1790 /*!
1791  \brief Close an input/output file returned by G_open_option_file(). If the
1792  file pointer is stdin, stdout, or stderr, nothing happens.
1793 
1794  \param file pointer
1795 */
1796 void G_close_option_file(FILE *fp)
1797 {
1798  if (fp != stdin && fp != stdout && fp != stderr)
1799  fclose(fp);
1800 }
int G__uses_new_gisprompt(void)
Definition: parser.c:852
int G_info_format(void)
Get current message format.
Definition: gis/error.c:531
int G_strcasecmp(const char *x, const char *y)
String compare ignoring case (upper or lower)
Definition: strings.c:46
int G__has_required_rule(void)
Checks if there is any rule RULE_REQUIRED (internal use only).
void G__usage_html(void)
Print module usage description in HTML format.
Definition: parser_html.c:29
const char * G_find_key_value(const char *key, const struct Key_Value *kv)
Find given key (case sensitive)
Definition: key_value1.c:84
const char * G_original_program_name(void)
Return original path of the executed program.
Definition: progrm_nme.c:46
#define KEYLENGTH
Definition: parser.c:97
const char * G_mapset(void)
Get current mapset name.
Definition: mapset.c:33
#define FALSE
Definition: dbfopen.c:117
void G__usage_xml(void)
Print module usage description in XML format.
struct GModule * G_define_module(void)
Initializes a new module.
Definition: parser.c:255
void G_zero(void *buf, int i)
Zero out a buffer, buf, of length i.
Definition: zero.c:23
const char * G_find_file(const char *element, char *name, const char *mapset)
Searches for a file from the mapset search list or in a specified mapset.
Definition: find_file.c:203
char * recreate_command(int original_path)
Creates command to run non-interactive.
Definition: parser.c:643
void G__usage_rest(void)
Print module usage description in reStructuredText format.
Definition: parser_rest.c:29
char * G_store(const char *s)
Copy string to allocated memory.
Definition: strings.c:86
void G__check_option_rules(void)
Check for option rules (internal use only)
int G_asprintf(char **out, const char *fmt,...)
Definition: asprintf.c:70
int G_get_overwrite()
Get overwrite value.
Definition: parser.c:912
#define NULL
Definition: ccmath.h:32
char * G_chop(char *line)
Chop leading and trailing white spaces.
Definition: strings.c:286
void G__usage_text(void)
Definition: parser_help.c:53
char * G_option_to_separator(const struct Option *option)
Get separator string from the option.
Definition: parser.c:1697
char * G_recreate_command(void)
Creates command to run non-interactive.
Definition: parser.c:800
char * G_recreate_command_original_path(void)
Creates command to run non-interactive.
Definition: parser.c:818
struct Flag * G_define_flag(void)
Initializes a Flag struct.
Definition: parser.c:156
int G_number_of_tokens(char **tokens)
Return number of tokens.
Definition: token.c:185
void G_fatal_error(const char *msg,...)
Print a fatal error message to stderr.
Definition: gis/error.c:159
int G_snprintf(char *str, size_t size, const char *fmt,...)
snprintf() clone.
Definition: snprintf.c:43
Definition: lidar.h:89
void G_close_option_file(FILE *fp)
Close an input/output file returned by G_open_option_file(). If the file pointer is stdin...
Definition: parser.c:1796
SYMBOL * err(FILE *fp, SYMBOL *s, char *msg)
Definition: symbol/read.c:220
int G_suppress_warnings(int flag)
Suppress printing a warning message to stderr.
Definition: gis/error.c:222
struct state * st
Definition: parser.c:103
struct Key_Value * G_read_key_value_file(const char *file)
Read key/values pairs from file.
Definition: key_value3.c:53
int G_parser(int argc, char **argv)
Parse command line.
Definition: parser.c:320
struct Option * G_define_option(void)
Initializes an Option struct.
Definition: parser.c:210
int G_verbose_max(void)
Get max verbosity level.
Definition: verbose.c:76
#define TRUE
Definition: dbfopen.c:118
int G_debug(int level, const char *msg,...)
Print debugging message.
Definition: debug.c:65
const char * G_getenv_nofatal(const char *name)
Get environment variable.
Definition: env.c:381
void G_set_keywords(const char *keywords)
Set keywords from the string.
Definition: parser.c:844
void G__script(void)
Generate Python script-like output.
Definition: parser_script.c:24
char * G_basename(char *filename, const char *desired_ext)
Truncates filename to the base part (before the last &#39;.&#39;) if it matches the extension, otherwise leaves it unchanged.
Definition: basename.c:38
const char * G_program_name(void)
Return module name.
Definition: progrm_nme.c:28
int G_verbose_std(void)
Get standard verbosity level.
Definition: verbose.c:86
void G_free_tokens(char **tokens)
Free memory allocated to tokens.
Definition: token.c:204
int G_verbose(void)
Get current verbosity level.
Definition: verbose.c:55
void G_usage(void)
Command line help/usage message.
Definition: parser_help.c:48
FILE * G_open_option_file(const struct Option *option)
Get an input/output file pointer from the option. If the file name is omitted or &#39;-&#39;, it returns either stdin or stdout based on the gisprompt.
Definition: parser.c:1759
void G_disable_interactive(void)
Disables the ability of the parser to operate interactively.
Definition: parser.c:139
#define MAX_MATCHES
Definition: parser.c:99
Definition: path.h:16
char ** G_tokenize(const char *buf, const char *delim)
Tokenize string.
Definition: token.c:48
int G_verbose_min(void)
Get min verbosity level.
Definition: verbose.c:96
void G__print_keywords(FILE *fd, void(*format)(FILE *, const char *))
Print list of keywords (internal use only)
Definition: parser.c:888
void G_add_keyword(const char *keyword)
Add keyword to the list.
Definition: parser.c:828
int G_is_dirsep(char c)
Checks if a specified character is a valid directory separator character on the host system...
Definition: paths.c:45
void G__wps_print_process_description(void)
Print the WPS 1.0.0 process description XML document to stdout.
Definition: parser_wps.c:140
void G_free(void *buf)
Free allocated memory.
Definition: alloc.c:149
struct state state
Definition: parser.c:102
const char * G_gisbase(void)
Get full path name of the top level module directory.
Definition: gisbase.c:41
void G_warning(const char *msg,...)
Print a warning message to stderr.
Definition: gis/error.c:203
opt_error
Definition: parser.c:89
int G_spawn(const char *command,...)
Spawn new process based on command.
Definition: spawn.c:924