parser.c 43 KB

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