GRASS GIS 8 Programmer's Manual  8.5.0dev(2025)-299a28a7d0
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  snprintf(buff, sizeof(buff), "GRASS_VERBOSE=%d",
549  G_verbose_max());
550  putenv(G_store(buff));
551  if (st->quiet == 1) {
552  G_warning(_("Use either --quiet or --verbose flag, not "
553  "both. Assuming --verbose."));
554  }
555  st->quiet = -1;
556  }
557 
558  /* Quiet option */
559  else if (strcmp(ptr, "--q") == 0 || strcmp(ptr, "--quiet") == 0) {
560  char buff[32];
561 
562  /* print nothing, but errors and warnings */
563  st->module_info.verbose = G_verbose_min();
564  snprintf(buff, sizeof(buff), "GRASS_VERBOSE=%d",
565  G_verbose_min());
566  putenv(G_store(buff));
567  if (st->quiet == -1) {
568  G_warning(_("Use either --quiet or --verbose flag, not "
569  "both. Assuming --quiet."));
570  }
571  st->quiet = 1; /* for passing to gui init */
572  }
573 
574  /* Super quiet option */
575  else if (strcmp(ptr, "--qq") == 0) {
576  char buff[32];
577 
578  /* print nothing, but errors */
579  st->module_info.verbose = G_verbose_min();
580  snprintf(buff, sizeof(buff), "GRASS_VERBOSE=%d",
581  G_verbose_min());
582  putenv(G_store(buff));
584  if (st->quiet == -1) {
585  G_warning(_("Use either --qq or --verbose flag, not both. "
586  "Assuming --qq."));
587  }
588  st->quiet = 1; /* for passing to gui init */
589  }
590 
591  /* Force gui to come up */
592  else if (strcmp(ptr, "--ui") == 0) {
593  force_gui = TRUE;
594  }
595 
596  /* If we see a flag */
597  else if (*ptr == '-') {
598  while (*(++ptr))
599  set_flag(*ptr);
600  }
601  /* If we see standard option format (option=val) */
602  else if (is_option(ptr)) {
603  set_option(ptr);
604  need_first_opt = 0;
605  }
606 
607  /* If we see the first option with no equal sign */
608  else if (need_first_opt && st->n_opts) {
609  st->first_option.answer = G_store(ptr);
610  st->first_option.count++;
611  need_first_opt = 0;
612  }
613 
614  /* If we see the non valid argument (no "=", just argument) */
615  else {
616  G_asprintf(&err, _("Sorry <%s> is not a valid option"), ptr);
617  append_error(err);
618  }
619  }
620  }
621 
622  /* Split options where multiple answers are OK */
623  split_opts();
624 
625  /* Run the gui if it was specifically requested */
626  if (force_gui) {
627  if (module_gui_wx() != 0)
628  G_fatal_error(_("Your installation doesn't include GUI, exiting."));
629  return -1;
630  }
631 
632  /* Check multiple options */
633  check_multiple_opts();
634 
635  /* Check answers against options and check subroutines */
636  if (!opt_checked)
637  check_opts();
638 
639  /* Make sure all required options are set */
640  if (!st->suppress_required)
641  check_required();
642 
644 
645  if (st->n_errors > 0) {
646  if (G_verbose() > -1) {
647  if (G_verbose() > G_verbose_min())
648  G_usage();
649  fprintf(stderr, "\n");
650  for (i = 0; i < st->n_errors; i++) {
651  fprintf(stderr, "%s: %s\n", _("ERROR"), st->error[i]);
652  }
653  }
654  return -1;
655  }
656 
657  /* Print the JSON definition of the command and exit */
658  if (print_json == 1) {
659  G__json();
660  exit(EXIT_SUCCESS);
661  }
662 
663  if (!st->suppress_overwrite) {
664  if (check_overwrite())
665  return -1;
666  }
667 
668  return 0;
669 }
670 
671 /*!
672  * \brief Creates command to run non-interactive.
673  *
674  * Creates a command-line that runs the current command completely
675  * non-interactive.
676  *
677  * \param original_path TRUE if original path should be used, FALSE for
678  * stripped and clean name of the module
679  * \return pointer to a char string
680  */
681 char *recreate_command(int original_path)
682 {
683  char *buff;
684  char flg[4];
685  char *cur;
686  const char *tmp;
687  struct Flag *flag;
688  struct Option *opt;
689  int n, len, slen;
690  int nalloced = 0;
691 
692  G_debug(3, "G_recreate_command()");
693 
694  /* Flag is not valid if there are no flags to set */
695 
696  buff = G_calloc(1024, sizeof(char));
697  nalloced += 1024;
698  if (original_path)
699  tmp = G_original_program_name();
700  else
701  tmp = G_program_name();
702  len = strlen(tmp);
703  if (len >= nalloced) {
704  nalloced += (1024 > len) ? 1024 : len + 1;
705  buff = G_realloc(buff, nalloced);
706  }
707  cur = buff;
708  strcpy(cur, tmp);
709  cur += len;
710 
711  if (st->overwrite) {
712  slen = strlen(" --overwrite");
713  if (len + slen >= nalloced) {
714  nalloced += (1024 > len) ? 1024 : len + 1;
715  buff = G_realloc(buff, nalloced);
716  }
717  strcpy(cur, " --overwrite");
718  cur += slen;
719  len += slen;
720  }
721 
722  if (st->module_info.verbose != G_verbose_std()) {
723  char *sflg;
724 
725  if (st->module_info.verbose == G_verbose_max())
726  sflg = " --verbose";
727  else
728  sflg = " --quiet";
729 
730  slen = strlen(sflg);
731  if (len + slen >= nalloced) {
732  nalloced += (1024 > len) ? 1024 : len + 1;
733  buff = G_realloc(buff, nalloced);
734  }
735  strcpy(cur, sflg);
736  cur += slen;
737  len += slen;
738  }
739 
740  if (st->n_flags) {
741  flag = &st->first_flag;
742  while (flag) {
743  if (flag->answer == 1) {
744  flg[0] = ' ';
745  flg[1] = '-';
746  flg[2] = flag->key;
747  flg[3] = '\0';
748  slen = strlen(flg);
749  if (len + slen >= nalloced) {
750  nalloced +=
751  (nalloced + 1024 > len + slen) ? 1024 : slen + 1;
752  buff = G_realloc(buff, nalloced);
753  cur = buff + len;
754  }
755  strcpy(cur, flg);
756  cur += slen;
757  len += slen;
758  }
759  flag = flag->next_flag;
760  }
761  }
762 
763  opt = &st->first_option;
764  while (st->n_opts && opt) {
765  if (opt->answer && opt->answer[0] == '\0') { /* answer = "" */
766  slen = strlen(opt->key) + 4; /* +4 for: ' ' = " " */
767  if (len + slen >= nalloced) {
768  nalloced += (nalloced + 1024 > len + slen) ? 1024 : slen + 1;
769  buff = G_realloc(buff, nalloced);
770  cur = buff + len;
771  }
772  strcpy(cur, " ");
773  cur++;
774  strcpy(cur, opt->key);
775  cur = strchr(cur, '\0');
776  strcpy(cur, "=");
777  cur++;
778  if (opt->type == TYPE_STRING) {
779  strcpy(cur, "\"\"");
780  cur += 2;
781  }
782  len = cur - buff;
783  }
784  else if (opt->answer && opt->answers && opt->answers[0]) {
785  slen = strlen(opt->key) + strlen(opt->answers[0]) +
786  4; /* +4 for: ' ' = " " */
787  if (len + slen >= nalloced) {
788  nalloced += (nalloced + 1024 > len + slen) ? 1024 : slen + 1;
789  buff = G_realloc(buff, nalloced);
790  cur = buff + len;
791  }
792  strcpy(cur, " ");
793  cur++;
794  strcpy(cur, opt->key);
795  cur = strchr(cur, '\0');
796  strcpy(cur, "=");
797  cur++;
798  if (opt->type == TYPE_STRING) {
799  strcpy(cur, "\"");
800  cur++;
801  }
802  strcpy(cur, opt->answers[0]);
803  cur = strchr(cur, '\0');
804  len = cur - buff;
805  for (n = 1; opt->answers[n]; n++) {
806  if (!opt->answers[n])
807  break;
808  slen = strlen(opt->answers[n]) + 2; /* +2 for , " */
809  if (len + slen >= nalloced) {
810  nalloced +=
811  (nalloced + 1024 > len + slen) ? 1024 : slen + 1;
812  buff = G_realloc(buff, nalloced);
813  cur = buff + len;
814  }
815  strcpy(cur, ",");
816  cur++;
817  strcpy(cur, opt->answers[n]);
818  cur = strchr(cur, '\0');
819  len = cur - buff;
820  }
821  if (opt->type == TYPE_STRING) {
822  strcpy(cur, "\"");
823  cur++;
824  len = cur - buff;
825  }
826  }
827  opt = opt->next_opt;
828  }
829 
830  return buff;
831 }
832 
833 /*!
834  * \brief Creates command to run non-interactive.
835  *
836  * Creates a command-line that runs the current command completely
837  * non-interactive.
838  *
839  * \return pointer to a char string
840  */
842 {
843  return recreate_command(FALSE);
844 }
845 
846 /* TODO: update to docs of these 3 functions to whatever general purpose
847  * they have now. */
848 /*!
849  * \brief Creates command to run non-interactive.
850  *
851  * Creates a command-line that runs the current command completely
852  * non-interactive.
853  *
854  * This gives the same as G_recreate_command() but the original path
855  * from the command line is used instead of the module name only.
856  *
857  * \return pointer to a char string
858  */
860 {
861  return recreate_command(TRUE);
862 }
863 
864 /*!
865  \brief Add keyword to the list
866 
867  \param keyword keyword string
868  */
869 void G_add_keyword(const char *keyword)
870 {
871  if (st->n_keys >= st->n_keys_alloc) {
872  st->n_keys_alloc += 10;
873  st->module_info.keywords = G_realloc(st->module_info.keywords,
874  st->n_keys_alloc * sizeof(char *));
875  }
876 
877  st->module_info.keywords[st->n_keys++] = G_store(keyword);
878 }
879 
880 /*!
881  \brief Set keywords from the string
882 
883  \param keywords keywords separated by commas
884  */
885 void G_set_keywords(const char *keywords)
886 {
887  char **tokens = G_tokenize(keywords, ",");
888 
889  st->module_info.keywords = (const char **)tokens;
890  st->n_keys = st->n_keys_alloc = G_number_of_tokens(tokens);
891 }
892 
894 {
895  struct Option *opt;
896  char age[KEYLENGTH];
897  char element[KEYLENGTH];
898  char desc[KEYLENGTH];
899 
900  if (st->module_info.overwrite)
901  return 1;
902 
903  /* figure out if any of the options use a "new" gisprompt */
904  /* This is to see if we should spit out the --o flag */
905  if (st->n_opts) {
906  opt = &st->first_option;
907  while (opt) {
908  if (opt->gisprompt) {
909  G__split_gisprompt(opt->gisprompt, age, element, desc);
910  if (strcmp(age, "new") == 0)
911  return 1;
912  }
913  opt = opt->next_opt;
914  }
915  }
916 
917  return 0;
918 }
919 
920 /*!
921  \brief Print list of keywords (internal use only)
922 
923  If <em>format</em> function is NULL then list of keywords is printed
924  comma-separated.
925 
926  \param[out] fd file where to print
927  \param format pointer to print function
928  \param newline TRUE to include newline
929  */
930 void G__print_keywords(FILE *fd, void (*format)(FILE *, const char *),
931  int newline)
932 {
933  int i;
934 
935  for (i = 0; i < st->n_keys; i++) {
936  if (!format) {
937  fprintf(fd, "%s", st->module_info.keywords[i]);
938  }
939  else {
940  format(fd, st->module_info.keywords[i]);
941  }
942  if (i < st->n_keys - 1) {
943  fprintf(fd, ",");
944  if (!newline)
945  fprintf(fd, " ");
946  }
947  if (newline)
948  fprintf(fd, "\n");
949  }
950 
951  fflush(fd);
952 }
953 
954 /*!
955  \brief Get overwrite value
956 
957  \return 1 overwrite enabled
958  \return 0 overwrite disabled
959  */
961 {
962  return st->module_info.overwrite;
963 }
964 
965 void define_keywords(void)
966 {
967  st->n_keys = 0;
968  st->n_keys_alloc = 0;
969 }
970 
971 /**************************************************************************
972  *
973  * The remaining routines are all local (static) routines used to support
974  * the parsing process.
975  *
976  **************************************************************************/
977 
978 /*!
979  \brief Invoke GUI dialog
980  */
981 int module_gui_wx(void)
982 {
983  char script[GPATH_MAX];
984 
985  /* TODO: the 4 following lines seems useless */
986  if (!st->pgm_path)
987  st->pgm_path = G_program_name();
988  if (!st->pgm_path)
989  G_fatal_error(_("Unable to determine program name"));
990 
991  snprintf(script, GPATH_MAX, "%s/gui/wxpython/gui_core/forms.py",
992  getenv("GISBASE"));
993  if (access(script, F_OK) != -1)
994  G_spawn(getenv("GRASS_PYTHON"), getenv("GRASS_PYTHON"), script,
996  else
997  return -1;
998 
999  return 0;
1000 }
1001 
1002 void set_flag(int f)
1003 {
1004  struct Flag *flag;
1005  char *key, *err;
1006  const char *renamed_key;
1007 
1008  err = NULL;
1009 
1010  /* Flag is not valid if there are no flags to set */
1011  if (!st->n_flags) {
1012  G_asprintf(&err, _("%s: Sorry, <%c> is not a valid flag"),
1013  G_program_name(), f);
1014  append_error(err);
1015  return;
1016  }
1017 
1018  /* Find flag with correct keyword */
1019  flag = &st->first_flag;
1020  while (flag) {
1021  if (flag->key == f) {
1022  flag->answer = 1;
1023  if (flag->suppress_required)
1024  st->suppress_required = 1;
1025  if (flag->suppress_overwrite)
1026  st->suppress_overwrite = 1;
1027  return;
1028  }
1029  flag = flag->next_flag;
1030  }
1031 
1032  /* First, check if key has been renamed */
1033  G_asprintf(&key, "-%c", f);
1034  renamed_key = get_renamed_option(key);
1035  G_free(key);
1036 
1037  if (renamed_key) {
1038  /* if renamed to a new flag */
1039  if (*renamed_key == '-') {
1040  /* if renamed to a long flag */
1041  if (renamed_key[1] == '-') {
1042  if (strcmp(renamed_key, "--overwrite") == 0) {
1043  /* this is a special case for -? to --overwrite */
1044  G_warning(_("Please update the usage of <%s>: "
1045  "flag <%c> has been renamed to <%s>"),
1046  G_program_name(), f, renamed_key);
1047  st->overwrite = 1;
1048  }
1049  else {
1050  /* long flags other than --overwrite are usually specific to
1051  * GRASS internals, just print an error and let's not
1052  * support them */
1053  G_asprintf(&err,
1054  _("Please update the usage of <%s>: "
1055  "flag <%c> has been renamed to <%s>"),
1056  G_program_name(), f, renamed_key);
1057  append_error(err);
1058  }
1059  return;
1060  }
1061  /* if renamed to a short flag */
1062  for (flag = &st->first_flag; flag; flag = flag->next_flag) {
1063  if (renamed_key[1] == flag->key) {
1064  G_warning(_("Please update the usage of <%s>: "
1065  "flag <%c> has been renamed to <%s>"),
1066  G_program_name(), f, renamed_key);
1067  flag->answer = 1;
1068  if (flag->suppress_required)
1069  st->suppress_required = 1;
1070  if (flag->suppress_overwrite)
1071  st->suppress_overwrite = 1;
1072  return;
1073  }
1074  }
1075  }
1076  else {
1077  /* if renamed to a new option (no option value given but will be
1078  * required), fatal error */
1079  struct Option *opt = NULL;
1080  for (opt = &st->first_option; opt; opt = opt->next_opt) {
1081  if (strcmp(renamed_key, opt->key) == 0) {
1082  G_asprintf(&err,
1083  _("Please update the usage of <%s>: "
1084  "flag <%c> has been renamed to option <%s>"),
1085  G_program_name(), f, renamed_key);
1086  append_error(err);
1087  return;
1088  }
1089  }
1090  }
1091  }
1092 
1093  G_asprintf(&err, _("%s: Sorry, <%c> is not a valid flag"), G_program_name(),
1094  f);
1095  append_error(err);
1096 }
1097 
1098 /* contents() is used to find things strings with characters like commas and
1099  * dashes.
1100  */
1101 int contains(const char *s, int c)
1102 {
1103  while (*s) {
1104  if (*s == c)
1105  return TRUE;
1106  s++;
1107  }
1108  return FALSE;
1109 }
1110 
1111 int valid_option_name(const char *string)
1112 {
1113  int m = strlen(string);
1114  int n = strspn(string, "abcdefghijklmnopqrstuvwxyz0123456789_");
1115 
1116  if (!m)
1117  return 0;
1118 
1119  if (m != n)
1120  return 0;
1121 
1122  if (string[m - 1] == '_')
1123  return 0;
1124 
1125  return 1;
1126 }
1127 
1128 int is_option(const char *string)
1129 {
1130  int n = strspn(string, "abcdefghijklmnopqrstuvwxyz0123456789_");
1131 
1132  return n > 0 && string[n] == '=' && string[0] != '_' &&
1133  string[n - 1] != '_';
1134 }
1135 
1136 int match_option_1(const char *string, const char *option)
1137 {
1138  const char *next;
1139 
1140  if (*string == '\0')
1141  return 1;
1142 
1143  if (*option == '\0')
1144  return 0;
1145 
1146  if (*string == *option && match_option_1(string + 1, option + 1))
1147  return 1;
1148 
1149  if (*option == '_' && match_option_1(string, option + 1))
1150  return 1;
1151 
1152  next = strchr(option, '_');
1153  if (!next)
1154  return 0;
1155 
1156  if (*string == '_')
1157  return match_option_1(string + 1, next + 1);
1158 
1159  return match_option_1(string, next + 1);
1160 }
1161 
1162 int match_option(const char *string, const char *option)
1163 {
1164  return (*string == *option) && match_option_1(string + 1, option + 1);
1165 }
1166 
1167 void set_option(const char *string)
1168 {
1169  struct Option *at_opt = NULL;
1170  struct Option *opt = NULL;
1171  size_t key_len;
1172  char the_key[KEYLENGTH];
1173  char *ptr, *err;
1174  struct Option *matches[MAX_MATCHES];
1175  int found = 0;
1176 
1177  err = NULL;
1178 
1179  for (ptr = the_key; *string != '='; ptr++, string++)
1180  *ptr = *string;
1181  *ptr = '\0';
1182  string++;
1183 
1184  /* an empty string is not a valid answer, skip */
1185  if (!*string)
1186  return;
1187 
1188  /* Find option with best keyword match */
1189  key_len = strlen(the_key);
1190  for (at_opt = &st->first_option; at_opt; at_opt = at_opt->next_opt) {
1191  if (!at_opt->key)
1192  continue;
1193 
1194  if (strcmp(the_key, at_opt->key) == 0) {
1195  matches[0] = at_opt;
1196  found = 1;
1197  break;
1198  }
1199 
1200  if (strncmp(the_key, at_opt->key, key_len) == 0 ||
1201  match_option(the_key, at_opt->key)) {
1202  if (found >= MAX_MATCHES)
1203  G_fatal_error("Too many matches (limit %d)", MAX_MATCHES);
1204  matches[found++] = at_opt;
1205  }
1206  }
1207 
1208  if (found > 1) {
1209  int shortest = 0;
1210  int length = strlen(matches[0]->key);
1211  int prefix = 1;
1212  int i;
1213 
1214  for (i = 1; i < found; i++) {
1215  int len = strlen(matches[i]->key);
1216 
1217  if (len < length) {
1218  length = len;
1219  shortest = i;
1220  }
1221  }
1222  for (i = 0; prefix && i < found; i++)
1223  if (strncmp(matches[i]->key, matches[shortest]->key, length) != 0)
1224  prefix = 0;
1225  if (prefix) {
1226  matches[0] = matches[shortest];
1227  found = 1;
1228  }
1229  else {
1230  G_asprintf(&err, _("%s: Sorry, <%s=> is ambiguous"),
1231  G_program_name(), the_key);
1232  append_error(err);
1233  for (i = 0; i < found; i++) {
1234  G_asprintf(&err, _("Option <%s=> matches"), matches[i]->key);
1235  append_error(err);
1236  }
1237  return;
1238  }
1239  }
1240 
1241  if (found)
1242  opt = matches[0];
1243 
1244  /* First, check if key has been renamed */
1245  if (found == 0) {
1246  const char *renamed_key = get_renamed_option(the_key);
1247 
1248  if (renamed_key) {
1249  /* if renamed to a new flag (option value given but will be lost),
1250  * fatal error */
1251  if (*renamed_key == '-') {
1252  if (renamed_key[1] == '-')
1253  G_asprintf(&err,
1254  _("Please update the usage of <%s>: "
1255  "option <%s> has been renamed to flag <%s>"),
1256  G_program_name(), the_key, renamed_key);
1257  else
1258  G_asprintf(&err,
1259  _("Please update the usage of <%s>: "
1260  "option <%s> has been renamed to flag <%c>"),
1261  G_program_name(), the_key, renamed_key[1]);
1262  append_error(err);
1263  return;
1264  }
1265 
1266  /* if renamed to a new option */
1267  for (at_opt = &st->first_option; at_opt;
1268  at_opt = at_opt->next_opt) {
1269  if (strcmp(renamed_key, at_opt->key) == 0) {
1270  G_warning(_("Please update the usage of <%s>: "
1271  "option <%s> has been renamed to <%s>"),
1272  G_program_name(), the_key, renamed_key);
1273  opt = at_opt;
1274  found = 1;
1275  break;
1276  }
1277  }
1278  }
1279  }
1280 
1281  /* If there is no match, complain */
1282  if (found == 0) {
1283  G_asprintf(&err, _("%s: Sorry, <%s> is not a valid parameter"),
1284  G_program_name(), the_key);
1285  append_error(err);
1286  return;
1287  }
1288 
1289  if (getenv("GRASS_FULL_OPTION_NAMES") && strcmp(the_key, opt->key) != 0)
1290  G_warning(_("<%s> is an abbreviation for <%s>"), the_key, opt->key);
1291 
1292  /* Allocate memory where answer is stored */
1293  if (opt->count++) {
1294  if (!opt->multiple) {
1295  G_asprintf(&err, _("Option <%s> does not accept multiple answers"),
1296  opt->key);
1297  append_error(err);
1298  }
1299  opt->answer =
1300  G_realloc(opt->answer, strlen(opt->answer) + strlen(string) + 2);
1301  strcat(opt->answer, ",");
1302  strcat(opt->answer, string);
1303  }
1304  else
1305  opt->answer = G_store(string);
1306 }
1307 
1308 void check_opts(void)
1309 {
1310  struct Option *opt;
1311  int ans;
1312 
1313  if (!st->n_opts)
1314  return;
1315 
1316  opt = &st->first_option;
1317  while (opt) {
1318  /* Check answer against options if any */
1319 
1320  if (opt->answer) {
1321  if (opt->multiple == 0)
1322  check_an_opt(opt->key, opt->type, opt->options, opt->opts,
1323  &opt->answer);
1324  else {
1325  for (ans = 0; opt->answers[ans] != NULL; ans++)
1326  check_an_opt(opt->key, opt->type, opt->options, opt->opts,
1327  &opt->answers[ans]);
1328  }
1329  }
1330 
1331  /* Check answer against user's check subroutine if any */
1332 
1333  if (opt->checker)
1334  opt->checker(opt->answer);
1335 
1336  opt = opt->next_opt;
1337  }
1338 }
1339 
1340 void check_an_opt(const char *key, int type, const char *options,
1341  const char **opts, char **answerp)
1342 {
1343  const char *answer = *answerp;
1344  int error;
1345  char *err;
1346  int found;
1347 
1348  error = 0;
1349  err = NULL;
1350  found = 0;
1351 
1352  switch (type) {
1353  case TYPE_INTEGER:
1354  error = check_int(answer, opts);
1355  break;
1356  case TYPE_DOUBLE:
1357  error = check_double(answer, opts);
1358  break;
1359  case TYPE_STRING:
1360  error = check_string(answer, opts, &found);
1361  break;
1362  }
1363  switch (error) {
1364  case 0:
1365  break;
1366  case BAD_SYNTAX:
1367  G_asprintf(&err,
1368  _("Illegal range syntax for parameter <%s>\n"
1369  "\tPresented as: %s"),
1370  key, options);
1371  append_error(err);
1372  break;
1373  case OUT_OF_RANGE:
1374  G_asprintf(&err,
1375  _("Value <%s> out of range for parameter <%s>\n"
1376  "\tLegal range: %s"),
1377  answer, key, options);
1378  append_error(err);
1379  break;
1380  case MISSING_VALUE:
1381  G_asprintf(&err, _("Missing value for parameter <%s>"), key);
1382  append_error(err);
1383  break;
1384  case INVALID_VALUE:
1385  G_asprintf(&err, _("Invalid value <%s> for parameter <%s>"), answer,
1386  key);
1387  append_error(err);
1388  break;
1389  case AMBIGUOUS:
1390  G_asprintf(&err,
1391  _("Value <%s> ambiguous for parameter <%s>\n"
1392  "\tValid options: %s"),
1393  answer, key, options);
1394  append_error(err);
1395  break;
1396  case REPLACED:
1397  *answerp = G_store(opts[found]);
1398  error = 0;
1399  break;
1400  }
1401 }
1402 
1403 int check_int(const char *ans, const char **opts)
1404 {
1405  int d, i;
1406 
1407  /* "-" is reserved for standard input */
1408  if (strcmp(ans, "-") == 0)
1409  return 0;
1410 
1411  if (!ans || !*ans)
1412  return MISSING_VALUE;
1413 
1414  if (sscanf(ans, "%d", &d) != 1)
1415  return INVALID_VALUE;
1416 
1417  if (!opts)
1418  return 0;
1419 
1420  for (i = 0; opts[i]; i++) {
1421  const char *opt = opts[i];
1422  int lo, hi;
1423 
1424  if (contains(opt, '-')) {
1425  if (sscanf(opt, "%d-%d", &lo, &hi) == 2) {
1426  if (d >= lo && d <= hi)
1427  return 0;
1428  }
1429  else if (sscanf(opt, "-%d", &hi) == 1) {
1430  if (d <= hi)
1431  return 0;
1432  }
1433  else if (sscanf(opt, "%d-", &lo) == 1) {
1434  if (d >= lo)
1435  return 0;
1436  }
1437  else
1438  return BAD_SYNTAX;
1439  }
1440  else {
1441  if (sscanf(opt, "%d", &lo) == 1) {
1442  if (d == lo)
1443  return 0;
1444  }
1445  else
1446  return BAD_SYNTAX;
1447  }
1448  }
1449 
1450  return OUT_OF_RANGE;
1451 }
1452 
1453 int check_double(const char *ans, const char **opts)
1454 {
1455  double d;
1456  int i;
1457 
1458  /* "-" is reserved for standard input */
1459  if (strcmp(ans, "-") == 0)
1460  return 0;
1461 
1462  if (!ans || !*ans)
1463  return MISSING_VALUE;
1464 
1465  if (sscanf(ans, "%lf", &d) != 1)
1466  return INVALID_VALUE;
1467 
1468  if (!opts)
1469  return 0;
1470 
1471  for (i = 0; opts[i]; i++) {
1472  const char *opt = opts[i];
1473  double lo, hi;
1474 
1475  if (contains(opt, '-')) {
1476  if (sscanf(opt, "%lf-%lf", &lo, &hi) == 2) {
1477  if (d >= lo && d <= hi)
1478  return 0;
1479  }
1480  else if (sscanf(opt, "-%lf", &hi) == 1) {
1481  if (d <= hi)
1482  return 0;
1483  }
1484  else if (sscanf(opt, "%lf-", &lo) == 1) {
1485  if (d >= lo)
1486  return 0;
1487  }
1488  else
1489  return BAD_SYNTAX;
1490  }
1491  else {
1492  if (sscanf(opt, "%lf", &lo) == 1) {
1493  if (d == lo)
1494  return 0;
1495  }
1496  else
1497  return BAD_SYNTAX;
1498  }
1499  }
1500 
1501  return OUT_OF_RANGE;
1502 }
1503 
1504 int check_string(const char *ans, const char **opts, int *result)
1505 {
1506  int len = strlen(ans);
1507  int found = 0;
1508  int matches[MAX_MATCHES];
1509  int i;
1510 
1511  if (!opts)
1512  return 0;
1513 
1514  for (i = 0; opts[i]; i++) {
1515  if (strcmp(ans, opts[i]) == 0)
1516  return 0;
1517  if (strncmp(ans, opts[i], len) == 0 || match_option(ans, opts[i])) {
1518  if (found >= MAX_MATCHES)
1519  G_fatal_error("too many matches (limit %d)", MAX_MATCHES);
1520  matches[found++] = i;
1521  }
1522  }
1523 
1524  if (found > 1) {
1525  int shortest = 0;
1526  int length = strlen(opts[matches[0]]);
1527  int prefix = 1;
1528 
1529  for (i = 1; i < found; i++) {
1530  int lengthi = strlen(opts[matches[i]]);
1531 
1532  if (lengthi < length) {
1533  length = lengthi;
1534  shortest = i;
1535  }
1536  }
1537  for (i = 0; prefix && i < found; i++)
1538  if (strncmp(opts[matches[i]], opts[matches[shortest]], length) != 0)
1539  prefix = 0;
1540  if (prefix) {
1541  matches[0] = matches[shortest];
1542  found = 1;
1543  }
1544  }
1545 
1546  if (found == 1)
1547  *result = matches[0];
1548 
1549  if (found > 0 && getenv("GRASS_FULL_OPTION_NAMES") &&
1550  strcmp(ans, opts[matches[0]]) != 0)
1551  G_warning(_("<%s> is an abbreviation for <%s>"), ans, opts[matches[0]]);
1552 
1553  switch (found) {
1554  case 0:
1555  return OUT_OF_RANGE;
1556  case 1:
1557  return REPLACED;
1558  default:
1559  return AMBIGUOUS;
1560  }
1561 }
1562 
1563 void check_required(void)
1564 {
1565  struct Option *opt;
1566  char *err;
1567 
1568  err = NULL;
1569 
1570  if (!st->n_opts)
1571  return;
1572 
1573  opt = &st->first_option;
1574  while (opt) {
1575  if (opt->required && !opt->answer) {
1576  G_asprintf(&err,
1577  _("Required parameter <%s> not set:\n"
1578  "\t(%s)"),
1579  opt->key, (opt->label ? opt->label : opt->description));
1580  append_error(err);
1581  }
1582  opt = opt->next_opt;
1583  }
1584 }
1585 
1586 void split_opts(void)
1587 {
1588  struct Option *opt;
1589  const char *ptr1;
1590  const char *ptr2;
1591  int allocated;
1592  int ans_num;
1593  int len;
1594 
1595  if (!st->n_opts)
1596  return;
1597 
1598  opt = &st->first_option;
1599  while (opt) {
1600  if (/*opt->multiple && */ opt->answer) {
1601  /* Allocate some memory to store array of pointers */
1602  allocated = 10;
1603  opt->answers = G_malloc(allocated * sizeof(char *));
1604 
1605  ans_num = 0;
1606  ptr1 = opt->answer;
1607  opt->answers[ans_num] = NULL;
1608 
1609  for (;;) {
1610  for (len = 0, ptr2 = ptr1; *ptr2 != '\0' && *ptr2 != ',';
1611  ptr2++, len++)
1612  ;
1613 
1614  if (len > 0) { /* skip ,, */
1615  opt->answers[ans_num] = G_malloc(len + 1);
1616  memcpy(opt->answers[ans_num], ptr1, len);
1617  opt->answers[ans_num][len] = 0;
1618 
1619  ans_num++;
1620 
1621  if (ans_num >= allocated) {
1622  allocated += 10;
1623  opt->answers =
1624  G_realloc(opt->answers, allocated * sizeof(char *));
1625  }
1626 
1627  opt->answers[ans_num] = NULL;
1628  }
1629 
1630  if (*ptr2 == '\0')
1631  break;
1632 
1633  ptr1 = ptr2 + 1;
1634 
1635  if (*ptr1 == '\0')
1636  break;
1637  }
1638  }
1639  opt = opt->next_opt;
1640  }
1641 }
1642 
1643 void check_multiple_opts(void)
1644 {
1645  struct Option *opt;
1646  const char *ptr;
1647  int n_commas;
1648  int n;
1649  char *err;
1650 
1651  if (!st->n_opts)
1652  return;
1653 
1654  err = NULL;
1655  opt = &st->first_option;
1656  while (opt) {
1657  /* "-" is reserved from standard input/output */
1658  if (opt->answer && strcmp(opt->answer, "-") && opt->key_desc) {
1659  /* count commas */
1660  n_commas = 1;
1661  for (ptr = opt->key_desc; *ptr != '\0'; ptr++)
1662  if (*ptr == ',')
1663  n_commas++;
1664  /* count items */
1665  for (n = 0; opt->answers[n] != NULL; n++)
1666  ;
1667  /* if not correct multiple of items */
1668  if (n % n_commas) {
1669  G_asprintf(&err,
1670  _("Option <%s> must be provided in multiples of %d\n"
1671  "\tYou provided %d item(s): %s"),
1672  opt->key, n_commas, n, opt->answer);
1673  append_error(err);
1674  }
1675  }
1676  opt = opt->next_opt;
1677  }
1678 }
1679 
1680 /* Check for all 'new' if element already exists */
1681 int check_overwrite(void)
1682 {
1683  struct Option *opt;
1684  char age[KEYLENGTH];
1685  char element[KEYLENGTH];
1686  char desc[KEYLENGTH];
1687  int error = 0;
1688  const char *overstr;
1689  int over;
1690 
1691  st->module_info.overwrite = 0;
1692 
1693  if (!st->n_opts)
1694  return (0);
1695 
1696  over = 0;
1697  /* Check the GRASS OVERWRITE variable */
1698  if ((overstr = G_getenv_nofatal("OVERWRITE"))) {
1699  over = atoi(overstr);
1700  }
1701 
1702  /* Check the GRASS_OVERWRITE environment variable */
1703  if ((overstr = getenv("GRASS_OVERWRITE"))) {
1704  if (atoi(overstr))
1705  over = 1;
1706  }
1707 
1708  if (st->overwrite || over) {
1709  st->module_info.overwrite = 1;
1710  /* Set the environment so that programs run in a script also obey --o */
1711  putenv("GRASS_OVERWRITE=1");
1712  /* No need to check options for existing files if overwrite is true */
1713  return error;
1714  }
1715 
1716  opt = &st->first_option;
1717  while (opt) {
1718  if (opt->answer && opt->gisprompt) {
1719  G__split_gisprompt(opt->gisprompt, age, element, desc);
1720 
1721  if (strcmp(age, "new") == 0) {
1722  int i;
1723  char found;
1724 
1725  for (i = 0; opt->answers[i]; i++) {
1726  found = FALSE;
1727  if (strcmp(element, "file") == 0) {
1728  if (access(opt->answers[i], F_OK) == 0)
1729  found = TRUE;
1730  }
1731  else if (strcmp(element, "mapset") != 0) {
1732  /* TODO: also other elements should be
1733  probably skipped */
1734  if (G_find_file(element, opt->answers[i], G_mapset())) {
1735  found = TRUE;
1736  }
1737  }
1738 
1739  if (found) { /* found */
1740  if (!st->overwrite && !over) {
1741  if (G_verbose() > -1) {
1742  if (G_info_format() != G_INFO_FORMAT_GUI) {
1743  fprintf(stderr, _("ERROR: "));
1744  fprintf(stderr,
1745  _("option <%s>: <%s> exists. To "
1746  "overwrite, use the --overwrite "
1747  "flag"),
1748  opt->key, opt->answers[i]);
1749  fprintf(stderr, "\n");
1750  }
1751  else {
1752  fprintf(stderr, "GRASS_INFO_ERROR(%d,1): ",
1753  getpid());
1754  fprintf(stderr,
1755  _("option <%s>: <%s> exists. To "
1756  "overwrite, use the --overwrite "
1757  "flag"),
1758  opt->key, opt->answers[i]);
1759  fprintf(stderr, "\n");
1760  fprintf(stderr, "GRASS_INFO_END(%d,1)\n",
1761  getpid());
1762  }
1763  }
1764  error = 1;
1765  }
1766  }
1767  }
1768  }
1769  }
1770  opt = opt->next_opt;
1771  }
1772 
1773  return (error);
1774 }
1775 
1776 void G__split_gisprompt(const char *gisprompt, char *age, char *element,
1777  char *desc)
1778 {
1779  const char *ptr1;
1780  char *ptr2;
1781 
1782  for (ptr1 = gisprompt, ptr2 = age; *ptr1 != '\0'; ptr1++, ptr2++) {
1783  if (*ptr1 == ',')
1784  break;
1785  *ptr2 = *ptr1;
1786  }
1787  *ptr2 = '\0';
1788 
1789  for (ptr1++, ptr2 = element; *ptr1 != '\0'; ptr1++, ptr2++) {
1790  if (*ptr1 == ',')
1791  break;
1792  *ptr2 = *ptr1;
1793  }
1794  *ptr2 = '\0';
1795 
1796  for (ptr1++, ptr2 = desc; *ptr1 != '\0'; ptr1++, ptr2++) {
1797  if (*ptr1 == ',')
1798  break;
1799  *ptr2 = *ptr1;
1800  }
1801  *ptr2 = '\0';
1802 }
1803 
1804 void append_error(const char *msg)
1805 {
1806  st->error = G_realloc(st->error, sizeof(char *) * (st->n_errors + 1));
1807  st->error[st->n_errors++] = G_store(msg);
1808 }
1809 
1810 const char *get_renamed_option(const char *key)
1811 {
1812  const char *pgm, *key_new;
1813  char *pgm_key;
1814 
1815  if (!st->renamed_options) {
1816  /* read renamed options from file (renamed_options) */
1817  char path[GPATH_MAX];
1818 
1819  snprintf(path, GPATH_MAX, "%s/etc/renamed_options", G_gisbase());
1820  st->renamed_options = G_read_key_value_file(path);
1821  }
1822 
1823  /* try to check global changes first */
1824  key_new = G_find_key_value(key, st->renamed_options);
1825  if (key_new)
1826  return key_new;
1827 
1828  /* then check module-relevant changes */
1829  pgm = G_program_name();
1830  pgm_key = (char *)G_malloc(strlen(pgm) + strlen(key) + 2);
1831  G_asprintf(&pgm_key, "%s|%s", pgm, key);
1832 
1833  key_new = G_find_key_value(pgm_key, st->renamed_options);
1834  G_free(pgm_key);
1835 
1836  return key_new;
1837 }
1838 
1839 /*!
1840  \brief Get separator string from the option.
1841 
1842  Calls G_fatal_error() on error. Allocated string can be later freed
1843  by G_free().
1844 
1845  \code
1846  char *fs;
1847  struct Option *opt_fs;
1848 
1849  opt_fs = G_define_standard_option(G_OPT_F_SEP);
1850 
1851  if (G_parser(argc, argv))
1852  exit(EXIT_FAILURE);
1853 
1854  fs = G_option_to_separator(opt_fs);
1855  \endcode
1856 
1857  \param option pointer to separator option
1858 
1859  \return allocated string with separator
1860  */
1861 char *G_option_to_separator(const struct Option *option)
1862 {
1863  char *sep;
1864 
1865  if (option->gisprompt == NULL ||
1866  strcmp(option->gisprompt, "old,separator,separator") != 0)
1867  G_fatal_error(_("%s= is not a separator option"), option->key);
1868 
1869  if (option->answer == NULL)
1870  G_fatal_error(_("No separator given for %s="), option->key);
1871 
1872  if (strcmp(option->answer, "pipe") == 0)
1873  sep = G_store("|");
1874  else if (strcmp(option->answer, "comma") == 0)
1875  sep = G_store(",");
1876  else if (strcmp(option->answer, "space") == 0)
1877  sep = G_store(" ");
1878  else if (strcmp(option->answer, "tab") == 0 ||
1879  strcmp(option->answer, "\\t") == 0)
1880  sep = G_store("\t");
1881  else if (strcmp(option->answer, "newline") == 0 ||
1882  strcmp(option->answer, "\\n") == 0)
1883  sep = G_store("\n");
1884  else
1885  sep = G_store(option->answer);
1886 
1887  G_debug(3, "G_option_to_separator(): key = %s -> sep = '%s'", option->key,
1888  sep);
1889 
1890  return sep;
1891 }
1892 
1893 /*!
1894  \brief Get an input/output file pointer from the option. If the file name is
1895  omitted or '-', it returns either stdin or stdout based on the gisprompt.
1896 
1897  Calls G_fatal_error() on error. File pointer can be later closed by
1898  G_close_option_file().
1899 
1900  \code
1901  FILE *fp_input;
1902  FILE *fp_output;
1903  struct Option *opt_input;
1904  struct Option *opt_output;
1905 
1906  opt_input = G_define_standard_option(G_OPT_F_INPUT);
1907  opt_output = G_define_standard_option(G_OPT_F_OUTPUT);
1908 
1909  if (G_parser(argc, argv))
1910  exit(EXIT_FAILURE);
1911 
1912  fp_input = G_open_option_file(opt_input);
1913  fp_output = G_open_option_file(opt_output);
1914  ...
1915  G_close_option_file(fp_input);
1916  G_close_option_file(fp_output);
1917  \endcode
1918 
1919  \param option pointer to a file option
1920 
1921  \return file pointer
1922  */
1923 FILE *G_open_option_file(const struct Option *option)
1924 {
1925  int stdinout;
1926  FILE *fp;
1927 
1928  stdinout = !option->answer || !*(option->answer) ||
1929  strcmp(option->answer, "-") == 0;
1930 
1931  if (option->gisprompt == NULL)
1932  G_fatal_error(_("%s= is not a file option"), option->key);
1933  else if (option->multiple)
1934  G_fatal_error(_("Opening multiple files not supported for %s="),
1935  option->key);
1936  else if (strcmp(option->gisprompt, "old,file,file") == 0) {
1937  if (stdinout)
1938  fp = stdin;
1939  else if ((fp = fopen(option->answer, "r")) == NULL)
1940  G_fatal_error(_("Unable to open %s file <%s>: %s"), option->key,
1941  option->answer, strerror(errno));
1942  }
1943  else if (strcmp(option->gisprompt, "new,file,file") == 0) {
1944  if (stdinout)
1945  fp = stdout;
1946  else if ((fp = fopen(option->answer, "w")) == NULL)
1947  G_fatal_error(_("Unable to create %s file <%s>: %s"), option->key,
1948  option->answer, strerror(errno));
1949  }
1950  else
1951  G_fatal_error(_("%s= is not a file option"), option->key);
1952 
1953  return fp;
1954 }
1955 
1956 /*!
1957  \brief Close an input/output file returned by G_open_option_file(). If the
1958  file pointer is stdin, stdout, or stderr, nothing happens.
1959 
1960  \param file pointer
1961  */
1962 void G_close_option_file(FILE *fp)
1963 {
1964  if (fp != stdin && fp != stdout && fp != stderr)
1965  fclose(fp);
1966 }
#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:540
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:922
#define G_INFO_FORMAT_GUI
Definition: gis.h:389
#define TYPE_STRING
Definition: gis.h:185
#define GPATH_MAX
Definition: gis.h:193
#define TYPE_INTEGER
Definition: gis.h:183
#define NO
Definition: gis.h:187
#define TRUE
Definition: gis.h:78
#define FALSE
Definition: gis.h:82
#define TYPE_DOUBLE
Definition: gis.h:184
#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:930
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:1923
char * G_recreate_command_original_path(void)
Creates command to run non-interactive.
Definition: parser.c:859
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:885
int G__uses_new_gisprompt(void)
Definition: parser.c:893
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:681
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:869
int G_get_overwrite(void)
Get overwrite value.
Definition: parser.c:960
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:1962
char * G_recreate_command(void)
Creates command to run non-interactive.
Definition: parser.c:841
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:1861
struct state * st
Definition: parser.c:104
void G__split_gisprompt(const char *gisprompt, char *age, char *element, char *desc)
Definition: parser.c:1776
#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.
Definition: parser_md.c:25
void G__usage_rest(void)
Print module usage description in reStructuredText format.
Definition: parser_rest.c:27
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
#define access
Definition: unistd.h:7
#define getpid
Definition: unistd.h:20
#define isatty
Definition: unistd.h:12
#define F_OK
Definition: unistd.h:22