parser.c 43 KB

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