parser.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464
  1. /*!
  2. * \file 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. * (C) 2001-2009, 2011 by the GRASS Development Team
  68. *
  69. * This program is free software under the GNU General Public License
  70. * (>=v2). Read the file COPYING that comes with GRASS for details.
  71. *
  72. * \author Original author CERL
  73. * \author Soeren Gebbert added Dec. 2009 WPS process_description document
  74. */
  75. #include <stdio.h>
  76. #include <stdlib.h>
  77. #include <string.h>
  78. #include <unistd.h>
  79. #include <grass/gis.h>
  80. #include <grass/spawn.h>
  81. #include <grass/glocale.h>
  82. #include "parser_local_proto.h"
  83. enum opt_error {
  84. BAD_SYNTAX = 1,
  85. OUT_OF_RANGE = 2,
  86. MISSING_VALUE = 3,
  87. AMBIGUOUS = 4,
  88. REPLACED = 5
  89. };
  90. #define KEYLENGTH 64
  91. /* initialize the global struct */
  92. struct state state;
  93. struct state *st = &state;
  94. /* local prototypes */
  95. static void set_flag(int);
  96. static int contains(const char *, int);
  97. static int is_option(const char *);
  98. static void set_option(const char *);
  99. static void check_opts(void);
  100. static void check_an_opt(const char *, int, const char *, const char **, char **);
  101. static int check_int(const char *, const char **);
  102. static int check_double(const char *, const char **);
  103. static int check_string(const char *, const char **, int *);
  104. static void check_required(void);
  105. static void split_opts(void);
  106. static void check_multiple_opts(void);
  107. static int check_overwrite(void);
  108. static void define_keywords(void);
  109. static void split_gisprompt(const char *gisprompt, char *age, char *element, char *desc);
  110. static void module_gui_wx(void);
  111. static void append_error(const char *);
  112. /*!
  113. * \brief Disables the ability of the parser to operate interactively.
  114. *
  115. * When a user calls a command with no arguments on the command line,
  116. * the parser will enter its own standardized interactive session in
  117. * which all flags and options are presented to the user for input. A
  118. * call to G_disable_interactive() disables the parser's interactive
  119. * prompting.
  120. *
  121. */
  122. void G_disable_interactive(void)
  123. {
  124. st->no_interactive = 1;
  125. }
  126. /*!
  127. * \brief Initializes a Flag struct.
  128. *
  129. * Allocates memory for the Flag structure and returns a pointer to
  130. * this memory.
  131. *
  132. * Flags are always represented by single letters. A user "turns them
  133. * on" at the command line using a minus sign followed by the
  134. * character representing the flag.
  135. *
  136. * \return Pointer to a Flag struct
  137. */
  138. struct Flag *G_define_flag(void)
  139. {
  140. struct Flag *flag;
  141. struct Item *item;
  142. /* Allocate memory if not the first flag */
  143. if (st->n_flags) {
  144. flag = G_malloc(sizeof(struct Flag));
  145. st->current_flag->next_flag = flag;
  146. }
  147. else
  148. flag = &st->first_flag;
  149. /* Zero structure */
  150. G_zero(flag, sizeof(struct Flag));
  151. st->current_flag = flag;
  152. st->n_flags++;
  153. if (st->n_items) {
  154. item = G_malloc(sizeof(struct Item));
  155. st->current_item->next_item = item;
  156. }
  157. else
  158. item = &st->first_item;
  159. G_zero(item, sizeof(struct Item));
  160. item->flag = flag;
  161. item->option = NULL;
  162. st->current_item = item;
  163. st->n_items++;
  164. return (flag);
  165. }
  166. /*!
  167. * \brief Initializes an Option struct.
  168. *
  169. * Allocates memory for the Option structure and returns a pointer to
  170. * this memory.
  171. *
  172. * Options are provided by user on command line using the standard
  173. * format: <i>key=value</i>. Options identified as REQUIRED must be
  174. * specified by user on command line. The option string can either
  175. * specify a range of values (e.g. "10-100") or a list of acceptable
  176. * values (e.g. "red,orange,yellow"). Unless the option string is
  177. * NULL, user provided input will be evaluated agaist this string.
  178. *
  179. * \return pointer to an Option struct
  180. */
  181. struct Option *G_define_option(void)
  182. {
  183. struct Option *opt;
  184. struct Item *item;
  185. /* Allocate memory if not the first option */
  186. if (st->n_opts) {
  187. opt = G_malloc(sizeof(struct Option));
  188. st->current_option->next_opt = opt;
  189. }
  190. else
  191. opt = &st->first_option;
  192. /* Zero structure */
  193. G_zero(opt, sizeof(struct Option));
  194. opt->required = NO;
  195. opt->multiple = NO;
  196. st->current_option = opt;
  197. st->n_opts++;
  198. if (st->n_items) {
  199. item = G_malloc(sizeof(struct Item));
  200. st->current_item->next_item = item;
  201. }
  202. else
  203. item = &st->first_item;
  204. G_zero(item, sizeof(struct Item));
  205. item->option = opt;
  206. st->current_item = item;
  207. st->n_items++;
  208. return (opt);
  209. }
  210. /*!
  211. * \brief Initializes a new module.
  212. *
  213. * \return pointer to a GModule struct
  214. */
  215. struct GModule *G_define_module(void)
  216. {
  217. struct GModule *module;
  218. /* Allocate memory */
  219. module = &st->module_info;
  220. /* Zero structure */
  221. G_zero(module, sizeof(struct GModule));
  222. /* Allocate keywords array */
  223. define_keywords();
  224. return (module);
  225. }
  226. /*!
  227. * \brief Parse command line.
  228. *
  229. * The command line parameters <i>argv</i> and the number of
  230. * parameters <i>argc</i> from the main() routine are passed directly
  231. * to G_parser(). G_parser() accepts the command line input entered by
  232. * the user, and parses this input according to the input options
  233. * and/or flags that were defined by the programmer.
  234. *
  235. * <b>Note:</b> The only functions which can legitimately be called
  236. * before G_parser() are:
  237. *
  238. * - G_gisinit()
  239. * - G_no_gisinit()
  240. * - G_define_module()
  241. * - G_define_flag()
  242. * - G_define_option()
  243. * - G_define_standard_option()
  244. * - G_disable_interactive()
  245. *
  246. * The usual order a module calls functions is:
  247. *
  248. * # G_gisinit()
  249. * # G_define_module()
  250. * # G_define_flag()
  251. * # G_define_option()
  252. * # G_parser()
  253. *
  254. * \param argc number of arguments
  255. * \param argv argument list
  256. *
  257. * \return 0 on success
  258. * \return -1 on error and calls G_usage()
  259. */
  260. int G_parser(int argc, char **argv)
  261. {
  262. int need_first_opt;
  263. int opt_checked = 0;
  264. char *ptr, *tmp_name, *err;
  265. int i;
  266. struct Option *opt;
  267. char force_gui = FALSE;
  268. err = NULL;
  269. need_first_opt = 1;
  270. tmp_name = G_store(argv[0]);
  271. st->pgm_path = tmp_name;
  272. st->n_errors = 0;
  273. st->error = NULL;
  274. i = strlen(tmp_name);
  275. while (--i >= 0) {
  276. if (G_is_dirsep(tmp_name[i])) {
  277. tmp_name += i + 1;
  278. break;
  279. }
  280. }
  281. G_basename(tmp_name, "exe");
  282. st->pgm_name = tmp_name;
  283. /* Stash default answers */
  284. opt = &st->first_option;
  285. while (opt) {
  286. if (opt->required)
  287. st->has_required = 1;
  288. /* Parse options */
  289. if (opt->options) {
  290. int cnt = 0;
  291. char **tokens, delm[2];
  292. delm[0] = ',';
  293. delm[1] = '\0';
  294. tokens = G_tokenize(opt->options, delm);
  295. i = 0;
  296. while (tokens[i]) {
  297. cnt++;
  298. i++;
  299. }
  300. opt->opts = G_calloc(cnt + 1, sizeof(const char *));
  301. i = 0;
  302. while (tokens[i]) {
  303. opt->opts[i] = G_store(tokens[i]);
  304. i++;
  305. }
  306. G_free_tokens(tokens);
  307. if (opt->descriptions) {
  308. delm[0] = ';';
  309. opt->descs = G_calloc(cnt + 1, sizeof(const char *));
  310. tokens = G_tokenize(opt->descriptions, delm);
  311. i = 0;
  312. while (tokens[i]) {
  313. int j, found;
  314. if (!tokens[i + 1])
  315. break;
  316. j = 0;
  317. found = 0;
  318. while (opt->opts[j]) {
  319. if (strcmp(opt->opts[j], tokens[i]) == 0) {
  320. found = 1;
  321. break;
  322. }
  323. j++;
  324. }
  325. if (!found) {
  326. G_warning(_("BUG in descriptions, option '%s' in <%s> does not exist"),
  327. tokens[i], opt->key);
  328. }
  329. else {
  330. opt->descs[j] = G_store(tokens[i + 1]);
  331. }
  332. i += 2;
  333. }
  334. G_free_tokens(tokens);
  335. }
  336. }
  337. /* Copy answer */
  338. if (opt->multiple && opt->answers && opt->answers[0]) {
  339. opt->answer = G_malloc(strlen(opt->answers[0]) + 1);
  340. strcpy(opt->answer, opt->answers[0]);
  341. for (i = 1; opt->answers[i]; i++) {
  342. opt->answer = G_realloc(opt->answer,
  343. strlen(opt->answer) +
  344. strlen(opt->answers[i]) + 2);
  345. strcat(opt->answer, ",");
  346. strcat(opt->answer, opt->answers[i]);
  347. }
  348. }
  349. opt->def = opt->answer;
  350. opt = opt->next_opt;
  351. }
  352. /* If there are NO arguments, go interactive */
  353. if (argc < 2 && st->has_required && !st->no_interactive && isatty(0)) {
  354. module_gui_wx();
  355. return -1;
  356. }
  357. else if (argc < 2 && st->has_required && isatty(0)) {
  358. G_usage();
  359. return -1;
  360. }
  361. else if (argc >= 2) {
  362. /* If first arg is "help" give a usage/syntax message */
  363. if (strcmp(argv[1], "help") == 0 ||
  364. strcmp(argv[1], "-help") == 0 || strcmp(argv[1], "--help") == 0) {
  365. G_usage();
  366. exit(EXIT_SUCCESS);
  367. }
  368. /* If first arg is "--help-text" give a usage/syntax message
  369. * with machine-readable sentinels */
  370. if (strcmp(argv[1], "--help-text") == 0) {
  371. G__usage_text();
  372. exit(EXIT_SUCCESS);
  373. }
  374. /* If first arg is "--interface-description" then print out
  375. * a xml description of the task */
  376. if (strcmp(argv[1], "--interface-description") == 0) {
  377. G__usage_xml();
  378. exit(EXIT_SUCCESS);
  379. }
  380. /* If first arg is "--html-description" then print out
  381. * a html description of the task */
  382. if (strcmp(argv[1], "--html-description") == 0) {
  383. G__usage_html();
  384. exit(EXIT_SUCCESS);
  385. }
  386. /* If first arg is "--rest-description" then print out
  387. * a ReST description of the task */
  388. if (strcmp(argv[1], "--rest-description") == 0) {
  389. G__usage_rest();
  390. exit(EXIT_SUCCESS);
  391. }
  392. /* If first arg is "--wps-process-description" then print out
  393. * the wps process description of the task */
  394. if (strcmp(argv[1], "--wps-process-description") == 0) {
  395. G__wps_print_process_description();
  396. exit(EXIT_SUCCESS);
  397. }
  398. /* If first arg is "--script" then then generate
  399. * g.parser boilerplate */
  400. if (strcmp(argv[1], "--script") == 0) {
  401. G__script();
  402. exit(EXIT_SUCCESS);
  403. }
  404. /* Loop thru all command line arguments */
  405. while (--argc) {
  406. ptr = *(++argv);
  407. if (strcmp(ptr, "help") == 0 ||
  408. strcmp(ptr, "-help") == 0 || strcmp(ptr, "--help") == 0) {
  409. G_usage();
  410. exit(EXIT_SUCCESS);
  411. }
  412. /* Overwrite option */
  413. if (strcmp(ptr, "--o") == 0 || strcmp(ptr, "--overwrite") == 0) {
  414. st->overwrite = 1;
  415. }
  416. /* Verbose option */
  417. else if (strcmp(ptr, "--v") == 0 || strcmp(ptr, "--verbose") == 0) {
  418. char buff[32];
  419. /* print everything: max verbosity level */
  420. st->module_info.verbose = G_verbose_max();
  421. sprintf(buff, "GRASS_VERBOSE=%d", G_verbose_max());
  422. putenv(G_store(buff));
  423. if (st->quiet == 1) {
  424. G_warning(_("Use either --quiet or --verbose flag, not both. Assuming --verbose."));
  425. }
  426. st->quiet = -1;
  427. }
  428. /* Quiet option */
  429. else if (strcmp(ptr, "--q") == 0 || strcmp(ptr, "--quiet") == 0) {
  430. char buff[32];
  431. /* print nothing, but errors and warnings */
  432. st->module_info.verbose = G_verbose_min();
  433. sprintf(buff, "GRASS_VERBOSE=%d", G_verbose_min());
  434. putenv(G_store(buff));
  435. if (st->quiet == -1) {
  436. G_warning(_("Use either --quiet or --verbose flag, not both. Assuming --quiet."));
  437. }
  438. st->quiet = 1; /* for passing to gui init */
  439. }
  440. /* Force gui to come up */
  441. else if (strcmp(ptr, "--ui") == 0) {
  442. force_gui = TRUE;
  443. }
  444. /* If we see a flag */
  445. else if (*ptr == '-') {
  446. while (*(++ptr))
  447. set_flag(*ptr);
  448. }
  449. /* If we see standard option format (option=val) */
  450. else if (is_option(ptr)) {
  451. set_option(ptr);
  452. need_first_opt = 0;
  453. }
  454. /* If we see the first option with no equal sign */
  455. else if (need_first_opt && st->n_opts) {
  456. st->first_option.answer = G_store(ptr);
  457. st->first_option.count++;
  458. need_first_opt = 0;
  459. }
  460. /* If we see the non valid argument (no "=", just argument) */
  461. else {
  462. G_asprintf(&err, _("Sorry <%s> is not a valid option"), ptr);
  463. append_error(err);
  464. }
  465. }
  466. }
  467. /* Split options where multiple answers are OK */
  468. split_opts();
  469. /* Run the gui if it was specifically requested */
  470. if (force_gui) {
  471. module_gui_wx();
  472. return -1;
  473. }
  474. /* Check multiple options */
  475. check_multiple_opts();
  476. /* Check answers against options and check subroutines */
  477. if (!opt_checked)
  478. check_opts();
  479. /* Make sure all required options are set */
  480. if (!st->suppress_required)
  481. check_required();
  482. if (st->n_errors > 0) {
  483. if (G_verbose() > -1) {
  484. if (G_verbose() > G_verbose_min())
  485. G_usage();
  486. fprintf(stderr, "\n");
  487. for (i = 0; i < st->n_errors; i++) {
  488. fprintf(stderr, "%s: %s\n", _("ERROR"), st->error[i]);
  489. }
  490. }
  491. return -1;
  492. }
  493. if (check_overwrite())
  494. return -1;
  495. return 0;
  496. }
  497. /*!
  498. * \brief Creates command to run non-interactive.
  499. *
  500. * Creates a command-line that runs the current command completely
  501. * non-interactive.
  502. *
  503. * \return pointer to a char string
  504. */
  505. char *G_recreate_command(void)
  506. {
  507. char *buff;
  508. char flg[4];
  509. char *cur;
  510. const char *tmp;
  511. struct Flag *flag;
  512. struct Option *opt;
  513. int n, len, slen;
  514. int nalloced = 0;
  515. G_debug(3, "G_recreate_command()");
  516. /* Flag is not valid if there are no flags to set */
  517. buff = G_calloc(1024, sizeof(char));
  518. nalloced += 1024;
  519. tmp = G_program_name();
  520. len = strlen(tmp);
  521. if (len >= nalloced) {
  522. nalloced += (1024 > len) ? 1024 : len + 1;
  523. buff = G_realloc(buff, nalloced);
  524. }
  525. cur = buff;
  526. strcpy(cur, tmp);
  527. cur += len;
  528. if (st->n_flags) {
  529. flag = &st->first_flag;
  530. while (flag) {
  531. if (flag->answer == 1) {
  532. flg[0] = ' ';
  533. flg[1] = '-';
  534. flg[2] = flag->key;
  535. flg[3] = '\0';
  536. slen = strlen(flg);
  537. if (len + slen >= nalloced) {
  538. nalloced +=
  539. (nalloced + 1024 > len + slen) ? 1024 : slen + 1;
  540. buff = G_realloc(buff, nalloced);
  541. cur = buff + len;
  542. }
  543. strcpy(cur, flg);
  544. cur += slen;
  545. len += slen;
  546. }
  547. flag = flag->next_flag;
  548. }
  549. }
  550. opt = &st->first_option;
  551. while (opt) {
  552. if (opt->answer && opt->answers && opt->answers[0]) {
  553. slen = strlen(opt->key) + strlen(opt->answers[0]) + 4; /* +4 for: ' ' = " " */
  554. if (len + slen >= nalloced) {
  555. nalloced += (nalloced + 1024 > len + slen) ? 1024 : slen + 1;
  556. buff = G_realloc(buff, nalloced);
  557. cur = buff + len;
  558. }
  559. strcpy(cur, " ");
  560. cur++;
  561. strcpy(cur, opt->key);
  562. cur = strchr(cur, '\0');
  563. strcpy(cur, "=");
  564. cur++;
  565. if (opt->type == TYPE_STRING) {
  566. strcpy(cur, "\"");
  567. cur++;
  568. }
  569. strcpy(cur, opt->answers[0]);
  570. cur = strchr(cur, '\0');
  571. len = cur - buff;
  572. for (n = 1; opt->answers[n]; n++) {
  573. if (!opt->answers[n])
  574. break;
  575. slen = strlen(opt->answers[n]) + 2; /* +2 for , " */
  576. if (len + slen >= nalloced) {
  577. nalloced +=
  578. (nalloced + 1024 > len + slen) ? 1024 : slen + 1;
  579. buff = G_realloc(buff, nalloced);
  580. cur = buff + len;
  581. }
  582. strcpy(cur, ",");
  583. cur++;
  584. strcpy(cur, opt->answers[n]);
  585. cur = strchr(cur, '\0');
  586. len = cur - buff;
  587. }
  588. if (opt->type == TYPE_STRING) {
  589. strcpy(cur, "\"");
  590. cur++;
  591. len = cur - buff;
  592. }
  593. }
  594. opt = opt->next_opt;
  595. }
  596. return buff;
  597. }
  598. /*!
  599. \brief Add keyword to the list
  600. \param keyword keyword string
  601. */
  602. void G_add_keyword(const char *keyword)
  603. {
  604. if (st->n_keys >= st->n_keys_alloc) {
  605. st->n_keys_alloc += 10;
  606. st->module_info.keywords = G_realloc(st->module_info.keywords,
  607. st->n_keys_alloc * sizeof(char *));
  608. }
  609. st->module_info.keywords[st->n_keys++] = G_store(keyword);
  610. }
  611. /*!
  612. \brief Set keywords from the string
  613. \param keywords keywords separated by commas
  614. */
  615. void G_set_keywords(const char *keywords)
  616. {
  617. char **tokens = G_tokenize(keywords, ",");
  618. st->module_info.keywords = (const char **)tokens;
  619. st->n_keys = st->n_keys_alloc = G_number_of_tokens(tokens);
  620. }
  621. int G__uses_new_gisprompt(void)
  622. {
  623. struct Option *opt;
  624. char age[KEYLENGTH];
  625. char element[KEYLENGTH];
  626. char desc[KEYLENGTH];
  627. if (st->module_info.overwrite)
  628. return 1;
  629. /* figure out if any of the options use a "new" gisprompt */
  630. /* This is to see if we should spit out the --o flag */
  631. if (st->n_opts) {
  632. opt = &st->first_option;
  633. while (opt) {
  634. if (opt->gisprompt) {
  635. split_gisprompt(opt->gisprompt, age, element, desc);
  636. if (strcmp(age, "new") == 0)
  637. return 1;
  638. }
  639. opt = opt->next_opt;
  640. }
  641. }
  642. return 0;
  643. }
  644. /*!
  645. \brief Print list of keywords (internal use only)
  646. If <em>format</em> function is NULL than list of keywords is printed
  647. comma-separated.
  648. \param[out] fd file where to print
  649. \param format pointer to print function
  650. */
  651. void G__print_keywords(FILE *fd, void (*format)(FILE *, const char *))
  652. {
  653. int i;
  654. for(i = 0; i < st->n_keys; i++) {
  655. if (!format) {
  656. fprintf(fd, "%s", st->module_info.keywords[i]);
  657. }
  658. else {
  659. format(fd, st->module_info.keywords[i]);
  660. }
  661. if (i < st->n_keys - 1)
  662. fprintf(fd, ", ");
  663. }
  664. fflush(fd);
  665. }
  666. /*!
  667. \brief Get overwrite value
  668. \return 1 overwrite enabled
  669. \return 0 overwrite disabled
  670. */
  671. int G_get_overwrite()
  672. {
  673. return st->overwrite;
  674. }
  675. void define_keywords(void)
  676. {
  677. st->n_keys = 0;
  678. st->n_keys_alloc = 0;
  679. }
  680. /**************************************************************************
  681. *
  682. * The remaining routines are all local (static) routines used to support
  683. * the parsing process.
  684. *
  685. **************************************************************************/
  686. /*!
  687. \brief Invoke GUI dialog
  688. */
  689. static void module_gui_wx(void)
  690. {
  691. char script[GPATH_MAX];
  692. if (!st->pgm_path)
  693. st->pgm_path = G_program_name();
  694. if (!st->pgm_path)
  695. G_fatal_error(_("Unable to determine program name"));
  696. sprintf(script, "%s/etc/gui/wxpython/gui_core/forms.py",
  697. getenv("GISBASE"));
  698. G_spawn(getenv("GRASS_PYTHON"), getenv("GRASS_PYTHON"), script, G_recreate_command(), NULL);
  699. }
  700. static void set_flag(int f)
  701. {
  702. struct Flag *flag;
  703. char *err;
  704. err = NULL;
  705. /* Flag is not valid if there are no flags to set */
  706. if (!st->n_flags) {
  707. G_asprintf(&err, _("Sorry, <%c> is not a valid flag"), f);
  708. append_error(err);
  709. return;
  710. }
  711. /* Find flag with corrrect keyword */
  712. flag = &st->first_flag;
  713. while (flag) {
  714. if (flag->key == f) {
  715. flag->answer = 1;
  716. if (flag->suppress_required)
  717. st->suppress_required = 1;
  718. return;
  719. }
  720. flag = flag->next_flag;
  721. }
  722. G_asprintf(&err, _("Sorry, <%c> is not a valid flag"), f);
  723. append_error(err);
  724. }
  725. /* contents() is used to find things strings with characters like commas and
  726. * dashes.
  727. */
  728. static int contains(const char *s, int c)
  729. {
  730. while (*s) {
  731. if (*s == c)
  732. return TRUE;
  733. s++;
  734. }
  735. return FALSE;
  736. }
  737. static int is_option(const char *string)
  738. {
  739. int n = strspn(string, "abcdefghijklmnopqrstuvwxyz0123456789_");
  740. return n > 0 && string[n] == '=' && string[0] != '_' && string[n-1] != '_';
  741. }
  742. static int match_option_1(const char *string, const char *option)
  743. {
  744. const char *next;
  745. if (*string == '\0')
  746. return 1;
  747. if (*option == '\0')
  748. return 0;
  749. if (*string == *option && match_option_1(string + 1, option + 1))
  750. return 1;
  751. if (*option == '_' && match_option_1(string, option + 1))
  752. return 1;
  753. next = strchr(option, '_');
  754. if (!next)
  755. return 0;
  756. if (*string == '_')
  757. return match_option_1(string + 1, next + 1);
  758. return match_option_1(string, next + 1);
  759. }
  760. static int match_option(const char *string, const char *option)
  761. {
  762. return (*string == *option)
  763. && match_option_1(string + 1, option + 1);
  764. }
  765. static void set_option(const char *string)
  766. {
  767. struct Option *at_opt = NULL;
  768. struct Option *opt = NULL;
  769. int got_one;
  770. size_t key_len;
  771. char the_key[KEYLENGTH];
  772. char *ptr, *err;
  773. err = NULL;
  774. for (ptr = the_key; *string != '='; ptr++, string++)
  775. *ptr = *string;
  776. *ptr = '\0';
  777. string++;
  778. /* Find option with best keyword match */
  779. got_one = 0;
  780. key_len = strlen(the_key);
  781. for (at_opt = &st->first_option; at_opt; at_opt = at_opt->next_opt) {
  782. if (!at_opt->key)
  783. continue;
  784. if (!match_option(the_key, at_opt->key))
  785. continue;
  786. got_one++;
  787. opt = at_opt;
  788. /* changed 1/15/91 -dpg old code is in parser.old */
  789. /* overide ambiguous check, if we get an exact match */
  790. if (strlen(at_opt->key) == key_len) {
  791. opt = at_opt;
  792. got_one = 1;
  793. break;
  794. }
  795. }
  796. if (got_one > 1) {
  797. G_asprintf(&err, _("Sorry, <%s=> is ambiguous"), the_key);
  798. append_error(err);
  799. return;
  800. }
  801. /* If there is no match, complain */
  802. if (got_one == 0) {
  803. G_asprintf(&err, _("Sorry, <%s> is not a valid parameter"), the_key);
  804. append_error(err);
  805. return;
  806. }
  807. /* Allocate memory where answer is stored */
  808. if (opt->count++) {
  809. if (!opt->multiple) {
  810. G_asprintf(&err, _("Option <%s> does not accept multiple answers"), opt->key);
  811. append_error(err);
  812. }
  813. opt->answer = G_realloc(opt->answer,
  814. strlen(opt->answer) + strlen(string) + 2);
  815. strcat(opt->answer, ",");
  816. strcat(opt->answer, string);
  817. }
  818. else
  819. opt->answer = G_store(string);
  820. }
  821. static void check_opts(void)
  822. {
  823. struct Option *opt;
  824. int ans;
  825. if (!st->n_opts)
  826. return;
  827. opt = &st->first_option;
  828. while (opt) {
  829. /* Check answer against options if any */
  830. if (opt->answer) {
  831. if (opt->multiple == 0)
  832. check_an_opt(opt->key, opt->type,
  833. opt->options, opt->opts, &opt->answer);
  834. else {
  835. for (ans = 0; opt->answers[ans] != '\0'; ans++)
  836. check_an_opt(opt->key, opt->type,
  837. opt->options, opt->opts, &opt->answers[ans]);
  838. }
  839. }
  840. /* Check answer against user's check subroutine if any */
  841. if (opt->checker)
  842. opt->checker(opt->answer);
  843. opt = opt->next_opt;
  844. }
  845. }
  846. static void check_an_opt(const char *key, int type, const char *options,
  847. const char **opts, char **answerp)
  848. {
  849. const char *answer = *answerp;
  850. int error;
  851. char *err;
  852. int found;
  853. error = 0;
  854. err = NULL;
  855. switch (type) {
  856. case TYPE_INTEGER:
  857. error = check_int(answer, opts);
  858. break;
  859. case TYPE_DOUBLE:
  860. error = check_double(answer, opts);
  861. break;
  862. case TYPE_STRING:
  863. error = check_string(answer, opts, &found);
  864. break;
  865. }
  866. switch (error) {
  867. case 0:
  868. break;
  869. case BAD_SYNTAX:
  870. G_asprintf(&err,
  871. _("Illegal range syntax for parameter <%s>\n"
  872. "\tPresented as: %s"), key, options);
  873. append_error(err);
  874. break;
  875. case OUT_OF_RANGE:
  876. G_asprintf(&err,
  877. _("Value <%s> out of range for parameter <%s>\n"
  878. "\tLegal range: %s"), answer, key, options);
  879. append_error(err);
  880. break;
  881. case MISSING_VALUE:
  882. G_asprintf(&err,
  883. _("Missing value for parameter <%s>"),
  884. key);
  885. append_error(err);
  886. break;
  887. case AMBIGUOUS:
  888. G_asprintf(&err,
  889. _("Value <%s> ambiguous for parameter <%s>\n"
  890. "\tValid options: %s"), answer, key, options);
  891. append_error(err);
  892. break;
  893. case REPLACED:
  894. *answerp = G_store(opts[found]);
  895. error = 0;
  896. break;
  897. }
  898. }
  899. static int check_int(const char *ans, const char **opts)
  900. {
  901. int d, i;
  902. /* "-" is reserved for standard input */
  903. if (strcmp(ans, "-") == 0)
  904. return 0;
  905. if (sscanf(ans, "%d", &d) != 1)
  906. return MISSING_VALUE;
  907. if (!opts)
  908. return 0;
  909. for (i = 0; opts[i]; i++) {
  910. const char *opt = opts[i];
  911. int lo, hi;
  912. if (contains(opt, '-')) {
  913. if (sscanf(opt, "%d-%d", &lo, &hi) == 2) {
  914. if (d >= lo && d <= hi)
  915. return 0;
  916. }
  917. else if (sscanf(opt, "-%d", &hi) == 1) {
  918. if (d <= hi)
  919. return 0;
  920. }
  921. else if (sscanf(opt, "%d-", &lo) == 1) {
  922. if (d >= lo)
  923. return 0;
  924. }
  925. else
  926. return BAD_SYNTAX;
  927. }
  928. else {
  929. if (sscanf(opt, "%d", &lo) == 1) {
  930. if (d == lo)
  931. return 0;
  932. }
  933. else
  934. return BAD_SYNTAX;
  935. }
  936. }
  937. return OUT_OF_RANGE;
  938. }
  939. static int check_double(const char *ans, const char **opts)
  940. {
  941. double d;
  942. int i;
  943. /* "-" is reserved for standard input */
  944. if (strcmp(ans, "-") == 0)
  945. return 0;
  946. if (sscanf(ans, "%lf", &d) != 1)
  947. return MISSING_VALUE;
  948. if (!opts)
  949. return 0;
  950. for (i = 0; opts[i]; i++) {
  951. const char *opt = opts[i];
  952. double lo, hi;
  953. if (contains(opt, '-')) {
  954. if (sscanf(opt, "%lf-%lf", &lo, &hi) == 2) {
  955. if (d >= lo && d <= hi)
  956. return 0;
  957. }
  958. else if (sscanf(opt, "-%lf", &hi) == 1) {
  959. if (d <= hi)
  960. return 0;
  961. }
  962. else if (sscanf(opt, "%lf-", &lo) == 1) {
  963. if (d >= lo)
  964. return 0;
  965. }
  966. else
  967. return BAD_SYNTAX;
  968. }
  969. else {
  970. if (sscanf(opt, "%lf", &lo) == 1) {
  971. if (d == lo)
  972. return 0;
  973. }
  974. else
  975. return BAD_SYNTAX;
  976. }
  977. }
  978. return OUT_OF_RANGE;
  979. }
  980. static int check_string(const char *ans, const char **opts, int *result)
  981. {
  982. int len = strlen(ans);
  983. int found = 0;
  984. int prefix = 0;
  985. int i;
  986. if (!opts)
  987. return 0;
  988. for (i = 0; opts[i]; i++) {
  989. if (strcmp(ans, opts[i]) == 0)
  990. return 0;
  991. if (strncmp(ans, opts[i], len) == 0) {
  992. *result = i;
  993. found++;
  994. prefix++;
  995. }
  996. if (match_option(ans, opts[i])) {
  997. if (!found)
  998. *result = i;
  999. found++;
  1000. }
  1001. }
  1002. switch (found) {
  1003. case 0: return OUT_OF_RANGE;
  1004. case 1: return REPLACED;
  1005. default:
  1006. switch (prefix) {
  1007. case 1: return REPLACED;
  1008. default: return AMBIGUOUS;
  1009. }
  1010. }
  1011. }
  1012. static void check_required(void)
  1013. {
  1014. struct Option *opt;
  1015. char *err;
  1016. err = NULL;
  1017. if (!st->n_opts)
  1018. return;
  1019. opt = &st->first_option;
  1020. while (opt) {
  1021. if (opt->required && !opt->answer) {
  1022. G_asprintf(&err, _("Required parameter <%s> not set:\n"
  1023. "\t(%s)"),
  1024. opt->key, (opt->label ? opt->label : opt->description));
  1025. append_error(err);
  1026. }
  1027. opt = opt->next_opt;
  1028. }
  1029. }
  1030. static void split_opts(void)
  1031. {
  1032. struct Option *opt;
  1033. const char *ptr1;
  1034. const char *ptr2;
  1035. int allocated;
  1036. int ans_num;
  1037. int len;
  1038. if (!st->n_opts)
  1039. return;
  1040. opt = &st->first_option;
  1041. while (opt) {
  1042. if ( /*opt->multiple && */ opt->answer) {
  1043. /* Allocate some memory to store array of pointers */
  1044. allocated = 10;
  1045. opt->answers = G_malloc(allocated * sizeof(char *));
  1046. ans_num = 0;
  1047. ptr1 = opt->answer;
  1048. opt->answers[ans_num] = NULL;
  1049. for (;;) {
  1050. for (len = 0, ptr2 = ptr1; *ptr2 != '\0' && *ptr2 != ',';
  1051. ptr2++, len++) ;
  1052. if (len > 0) { /* skip ,, */
  1053. opt->answers[ans_num] = G_malloc(len + 1);
  1054. memcpy(opt->answers[ans_num], ptr1, len);
  1055. opt->answers[ans_num][len] = 0;
  1056. ans_num++;
  1057. if (ans_num >= allocated) {
  1058. allocated += 10;
  1059. opt->answers = G_realloc(opt->answers,
  1060. allocated * sizeof(char *));
  1061. }
  1062. opt->answers[ans_num] = NULL;
  1063. }
  1064. if (*ptr2 == '\0')
  1065. break;
  1066. ptr1 = ptr2 + 1;
  1067. if (*ptr1 == '\0')
  1068. break;
  1069. }
  1070. }
  1071. opt = opt->next_opt;
  1072. }
  1073. }
  1074. static void check_multiple_opts(void)
  1075. {
  1076. struct Option *opt;
  1077. const char *ptr;
  1078. int n_commas;
  1079. int n;
  1080. char *err;
  1081. if (!st->n_opts)
  1082. return;
  1083. err = NULL;
  1084. opt = &st->first_option;
  1085. while (opt) {
  1086. /* "-" is reserved from standard input/output */
  1087. if (opt->answer && strcmp(opt->answer, "-") && opt->key_desc) {
  1088. /* count commas */
  1089. n_commas = 1;
  1090. for (ptr = opt->key_desc; *ptr != '\0'; ptr++)
  1091. if (*ptr == ',')
  1092. n_commas++;
  1093. /* count items */
  1094. for (n = 0; opt->answers[n] != '\0'; n++) ;
  1095. /* if not correct multiple of items */
  1096. if (n % n_commas) {
  1097. G_asprintf(&err,
  1098. _("Option <%s> must be provided in multiples of %d\n"
  1099. "\tYou provided %d item(s): %s"),
  1100. opt->key, n_commas, n, opt->answer);
  1101. append_error(err);
  1102. }
  1103. }
  1104. opt = opt->next_opt;
  1105. }
  1106. }
  1107. /* Check for all 'new' if element already exists */
  1108. static int check_overwrite(void)
  1109. {
  1110. struct Option *opt;
  1111. char age[KEYLENGTH];
  1112. char element[KEYLENGTH];
  1113. char desc[KEYLENGTH];
  1114. int error = 0;
  1115. const char *overstr;
  1116. int over;
  1117. st->module_info.overwrite = 0;
  1118. if (!st->n_opts)
  1119. return (0);
  1120. over = 0;
  1121. /* Check the GRASS OVERWRITE variable */
  1122. if ((overstr = G__getenv("OVERWRITE"))) {
  1123. over = atoi(overstr);
  1124. }
  1125. /* Check the GRASS_OVERWRITE environment variable */
  1126. if ((overstr = getenv("GRASS_OVERWRITE"))) {
  1127. if (atoi(overstr))
  1128. over = 1;
  1129. }
  1130. if (st->overwrite || over) {
  1131. st->module_info.overwrite = 1;
  1132. /* Set the environment so that programs run in a script also obey --o */
  1133. putenv("GRASS_OVERWRITE=1");
  1134. /* No need to check options for existing files if overwrite is true */
  1135. return error;
  1136. }
  1137. opt = &st->first_option;
  1138. while (opt) {
  1139. if (opt->answer && opt->gisprompt) {
  1140. split_gisprompt(opt->gisprompt, age, element, desc);
  1141. if (strcmp(age, "new") == 0) {
  1142. int i;
  1143. char found;
  1144. for (i = 0; opt->answers[i]; i++) {
  1145. found = FALSE;
  1146. if (strcmp(element, "file") == 0) {
  1147. if (access(opt->answers[i], F_OK) == 0)
  1148. found = TRUE;
  1149. }
  1150. else if (strcmp(element, "mapset") != 0) {
  1151. /* TODO: also other elements should be
  1152. probably skipped */
  1153. if (G_find_file(element, opt->answers[i], G_mapset())) {
  1154. found = TRUE;
  1155. }
  1156. }
  1157. if (found) { /* found */
  1158. if (!st->overwrite && !over) {
  1159. if (G_verbose() > -1) {
  1160. if (G_info_format() != G_INFO_FORMAT_GUI) {
  1161. fprintf(stderr,
  1162. _("ERROR: option <%s>: <%s> exists.\n"),
  1163. opt->key, opt->answers[i]);
  1164. }
  1165. else {
  1166. fprintf(stderr,
  1167. "GRASS_INFO_ERROR(%d,1): option <%s>: <%s> exists.\n",
  1168. getpid(), opt->key, opt->answers[i]);
  1169. fprintf(stderr, "GRASS_INFO_END(%d,1)\n",
  1170. getpid());
  1171. }
  1172. }
  1173. error = 1;
  1174. }
  1175. }
  1176. }
  1177. }
  1178. }
  1179. opt = opt->next_opt;
  1180. }
  1181. return (error);
  1182. }
  1183. static void split_gisprompt(const char *gisprompt, char *age, char *element,
  1184. char *desc)
  1185. {
  1186. const char *ptr1;
  1187. char *ptr2;
  1188. for (ptr1 = gisprompt, ptr2 = age; *ptr1 != '\0'; ptr1++, ptr2++) {
  1189. if (*ptr1 == ',')
  1190. break;
  1191. *ptr2 = *ptr1;
  1192. }
  1193. *ptr2 = '\0';
  1194. for (ptr1++, ptr2 = element; *ptr1 != '\0'; ptr1++, ptr2++) {
  1195. if (*ptr1 == ',')
  1196. break;
  1197. *ptr2 = *ptr1;
  1198. }
  1199. *ptr2 = '\0';
  1200. for (ptr1++, ptr2 = desc; *ptr1 != '\0'; ptr1++, ptr2++) {
  1201. if (*ptr1 == ',')
  1202. break;
  1203. *ptr2 = *ptr1;
  1204. }
  1205. *ptr2 = '\0';
  1206. }
  1207. static void append_error(const char *msg)
  1208. {
  1209. st->error = G_realloc(st->error, sizeof(char *) * (st->n_errors + 1));
  1210. st->error[st->n_errors++] = G_store(msg);
  1211. }
  1212. /*!
  1213. \brief Get separator string from the option.
  1214. Calls G_fatal_error() on error. Allocated string can be later freed
  1215. by G_free().
  1216. \code
  1217. char *fs;
  1218. struct Option *opt_fs;
  1219. opt_fs = G_define_standard_option(G_OPT_F_SEP);
  1220. if (G_parser(argc, argv))
  1221. exit(EXIT_FAILURE);
  1222. fs = G_option_to_separator(opt_fs);
  1223. \endcode
  1224. \param option pointer to separator option
  1225. \return allocated string with separator
  1226. */
  1227. char* G_option_to_separator(const struct Option *option)
  1228. {
  1229. char* sep;
  1230. if (option->answer == NULL)
  1231. G_fatal_error(_("No separator given"));
  1232. if (strcmp(option->answer, "space") == 0)
  1233. sep = G_store(" ");
  1234. else if (strcmp(option->answer, "tab") == 0 ||
  1235. strcmp(option->answer, "\\t") == 0)
  1236. sep = G_store("\t");
  1237. else if (strcmp(option->answer, "newline") == 0)
  1238. sep = G_store("\n");
  1239. else if (strcmp(option->answer, "comma") == 0)
  1240. sep = G_store(",");
  1241. else {
  1242. sep = G_store(option->answer);
  1243. }
  1244. G_debug(1, "G_option_to_separator(): key = %s -> sep = '%s'",
  1245. option->key, sep);
  1246. return sep;
  1247. }