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