parser.c 43 KB

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