parser.c 44 KB

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