parser.c 43 KB

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