parser.c 43 KB

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