parser.c 44 KB

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