parser.c 43 KB

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