parser.c 44 KB

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