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