Debian Codegraph @

easel/esl_getopts.c

raw symbols SCIP
1 /* Implements a somewhat more powerful command line getopt interface
2 * than the standard UNIX/POSIX call.
3 *
4 * Contents:
5 * 1. The ESL_GETOPTS object.
6 * 2. Setting and testing a configuration.
7 * 3. Retrieving option settings and command line args.
8 * 4. Formatting option help.
9 * 5. Private functions.
10 * 6. Test driver.
11 * 7. Examples.
12 *
13 * xref STL8/p152; STL9/p5.
14 */
15 #include <esl_config.h>
16
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <ctype.h>
21
22 #include "easel.h"
23 #include "esl_getopts.h"
24
25 /* Forward declarations of private functions. */
26 static int set_option(ESL_GETOPTS *g, int opti, char *optarg,
27 int setby, int do_alloc);
28 static int get_optidx_exactly(const ESL_GETOPTS *g, char *optname, int *ret_opti);
29 static int get_optidx_abbrev(ESL_GETOPTS *g, char *optname, int n,
30 int *ret_opti);
31 static int esl_getopts(ESL_GETOPTS *g, int *ret_opti, char **ret_optarg);
32 static int process_longopt(ESL_GETOPTS *g, int *ret_opti, char **ret_optarg);
33 static int process_stdopt(ESL_GETOPTS *g, int *ret_opti, char **ret_optarg);
34 static int verify_type_and_range(ESL_GETOPTS *g, int i, char *val, int setby);
35 static int verify_integer_range(char *arg, char *range);
36 static int verify_real_range(char *arg, char *range);
37 static int verify_char_range(char *arg, char *range);
38 static int parse_rangestring(char *range, char c, char **ret_lowerp,
39 int *ret_geq, char **ret_upperp, int *ret_leq);
40 static int process_optlist(ESL_GETOPTS *g, char **ret_s, int *ret_opti);
41
42
43
44 /*****************************************************************
45 *# 1. The <ESL_GETOPTS> object
46 *****************************************************************/
47
48 /* Function: esl_getopts_Create()
49 * Synopsis: Create a new <ESL_GETOPTS> object.
50 *
51 * Purpose: Creates an <ESL_GETOPTS> object, given the
52 * array of valid options <opt> (NULL-element-terminated).
53 * Sets default values for all config
54 * options (as defined in <opt>).
55 *
56 * Returns: ptr to the new <ESL_GETOPTS> object.
57 *
58 * Throws: NULL on failure, including allocation failures or
59 * an invalid <ESL_OPTIONS> structure.
60 */
61 ESL_GETOPTS *
62 esl_getopts_Create(const ESL_OPTIONS *opt)
63 {
64 ESL_GETOPTS *g = NULL;
65 int status;
66 int i;
67
68 ESL_ALLOC(g, sizeof(ESL_GETOPTS));
69
70 g->opt = opt;
71 g->argc = 0;
72 g->argv = NULL;
73 g->optind = 1;
74 g->nfiles = 0;
75 g->val = NULL;
76 g->setby = NULL;
77 g->valloc = NULL;
78 g->optstring = NULL;
79 g->spoof = NULL;
80 g->spoof_argv= NULL;
81 g->errbuf[0] = '\0';
82
83 /* Figure out the number of options.
84 *
85 * Using the NULL-terminated structure array is a design decision.
86 * Alternatively, the caller could provide us with noptions, and use
87 * a #define noptions (sizeof(options) / sizeof(ESL_GETOPTS)) idiom.
88 * Note that we can't use sizeof() here, because now <opt> is just a
89 * pointer.
90 *
91 * A drawback of requiring NULL termination is, what happens when
92 * the caller forgets? Thus the check for a leading '-' on all
93 * options; if we start straying into memory, that check should
94 * catch us.
95 */
96 g->nopts = 0;
97 while (g->opt[g->nopts].name != NULL) {
98 if (g->opt[g->nopts].name[0] != '-')
99 ESL_XEXCEPTION(eslEINVAL, "option %d didn't start with '-';\nyou may have forgotten to NULL-terminate the ESL_OPTIONS array", g->nopts);
100 g->nopts++;
101 }
102
103 /* Set default values for all options.
104 * Note the valloc[] setting: we only need to dup strings
105 * into allocated space if the value is volatile memory, and
106 * that only happens in config files; not in defaults, cmdline,
107 * or environment.
108 */
109 ESL_ALLOC(g->val, sizeof(char *) * g->nopts);
110 ESL_ALLOC(g->setby, sizeof(int) * g->nopts);
111 ESL_ALLOC(g->valloc, sizeof(int) * g->nopts);
112
113 for (i = 0; i < g->nopts; i++)
114 {
115 g->val[i] = g->opt[i].defval;
116 g->setby[i] = eslARG_SETBY_DEFAULT;
117 g->valloc[i] = 0;
118 }
119
120 /* Verify type/range of the defaults, even though it's
121 * an application error (not user error) if they're invalid.
122 */
123 for (i = 0; i < g->nopts; i++)
124 if (verify_type_and_range(g, i, g->val[i], eslARG_SETBY_DEFAULT) != eslOK)
125 ESL_XEXCEPTION(eslEINVAL, "%s\n", g->errbuf);
126 return g;
127
128 ERROR:
129 esl_getopts_Destroy(g);
130 return NULL;
131 }
132
133 /* Function: esl_getopts_CreateDefaultApp()
134 * Synopsis: Initialize a standard Easel application.
135 *
136 * Purpose: Carry out the usual sequence of events in initializing a
137 * small Easel-based application: parses the command line,
138 * process the <-h> option to produce a (single-sectioned)
139 * help page, and check that the number of command line
140 * options is right.
141 *
142 * <options> is an array of <ESL_OPTIONS> structures describing
143 * the options, terminated by an all-<NULL> structure.
144 *
145 * <nargs> is the number of commandline arguments
146 * expected. If the number of commandline arguments isn't
147 * equal to this, an error message is printed, with the
148 * <usage> string, and <exit()> is called. If <nargs> is
149 * -1, this check isn't done; if your program deliberately
150 * has a variable number of commandline arguments (i.e.
151 * if the number is unknown at compile time), pass -1
152 * for <nargs>.
153 *
154 * <argc> and <argv> are the command line
155 * arguments (number and pointer array) from <main()>.
156 *
157 * <banner> is an optional one-line description of the
158 * program's function, such as <"compare RNA structures">.
159 * When the <-h> help option is selected, this description
160 * will be combined with the program's name (the tail of
161 * <argv[0]>) and Easel's copyright and license information
162 * to give a header like:
163 *
164 * \begin{cchunk}
165 * # esl-compstruct :: compare RNA structures
166 * # Easel 0.1 (February 2005)
167 * # Copyright (C) 2004-2007 HHMI Janelia Farm Research Campus
168 * # Freely licensed under the Janelia Software License.
169 * # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
170 * \end{cchunk}
171 *
172 * <usage> is an optional one-line description of command
173 * line usage (without the command name), such as
174 * \begin{cchunk}
175 * [options] <trusted file> <test file>
176 * \end{cchunk}
177 * On errors, or
178 * on the help page, this usage string is combined with
179 * the program's name to give a usage line like:
180 *
181 * \begin{cchunk}
182 * Usage: esl-compstruct [options] <trusted file> <test file>
183 * \end{cchunk}
184 *
185 * <banner> and <usage> are optional, meaning that either
186 * can be provided as <NULL> and they won't be shown.
187 *
188 * Returns: a pointer to a new <ESL_GETOPTS> object, which contains
189 * all the option settings and command line arguments.
190 *
191 * On command line errors, this routine exits with abnormal
192 * (1) status.
193 *
194 * If the <-h> help option is seen, this routine exits with
195 * normal (0) status after printing a help page.
196 *
197 */
198 ESL_GETOPTS *
199 esl_getopts_CreateDefaultApp(const ESL_OPTIONS *options, int nargs, int argc, char **argv, char *banner, char *usage)
200 {
201 ESL_GETOPTS *go = NULL;
202
203 go = esl_getopts_Create(options);
204 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK ||
205 esl_opt_VerifyConfig(go) != eslOK)
206 {
207 printf("Failed to parse command line: %s\n", go->errbuf);
208 if (usage != NULL) esl_usage(stdout, argv[0], usage);
209 printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
210 exit(1);
211 }
212 if (esl_opt_GetBoolean(go, "-h") == TRUE)
213 {
214 if (banner != NULL) esl_banner(stdout, argv[0], banner);
215 if (usage != NULL) esl_usage (stdout, argv[0], usage);
216 puts("\nOptions:");
217 esl_opt_DisplayHelp(stdout, go, 0, 2, 80);
218 exit(0);
219 }
220 if (nargs != -1 && esl_opt_ArgNumber(go) != nargs)
221 {
222 puts("Incorrect number of command line arguments.");
223 esl_usage(stdout, argv[0], usage);
224 printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
225 exit(1);
226 }
227 return go;
228 }
229
230
231 /* Function: esl_getopts_Reuse()
232 * Synopsis: Reset application state to default.
233 *
234 * Purpose: Reset application configuration <g> to initial defaults,
235 * as if it were newly created (before any
236 * processing of environment, config files, or
237 * command line).
238 *
239 * Returns: <eslOK> on success.
240 *
241 * Throws: (no abnormal error conditions)
242 *
243 * Xref: J4/24.
244 */
245 int
246 esl_getopts_Reuse(ESL_GETOPTS *g)
247 {
248 int i;
249
250 /* Restore defaults for all options */
251 for (i = 0; i < g->nopts; i++)
252 {
253 if (g->valloc[i] > 0) { free(g->val[i]); }
254 g->val[i] = g->opt[i].defval;
255 g->setby[i] = eslARG_SETBY_DEFAULT;
256 g->valloc[i] = 0;
257 }
258
259 if (g->spoof != NULL) free(g->spoof);
260 if (g->spoof_argv != NULL) free(g->spoof_argv);
261
262 g->argc = 0;
263 g->argv = NULL;
264 g->optind = 1;
265 g->nfiles = 0;
266 g->optstring = NULL;
267 g->spoof = NULL;
268 g->spoof_argv = NULL;
269 g->errbuf[0] = '\0';
270 return eslOK;
271 }
272
273
274 /* Function: esl_getopts_Destroy()
275 * Synopsis: Destroys an <ESL_GETOPTS> object.
276 *
277 * Purpose: Free's a created <ESL_GETOPTS> object.
278 *
279 * Returns: void.
280 */
281 void
282 esl_getopts_Destroy(ESL_GETOPTS *g)
283 {
284 int i;
285
286 if (g != NULL)
287 {
288 if (g->val != NULL)
289 {
290 /* A few of our vals may have been allocated.
291 */
292 for (i = 0; i < g->nopts; i++)
293 if (g->valloc[i] > 0)
294 free(g->val[i]);
295 free(g->val);
296 }
297 if (g->setby != NULL) free(g->setby);
298 if (g->valloc != NULL) free(g->valloc);
299 if (g->spoof != NULL) free(g->spoof);
300 if (g->spoof_argv != NULL) free(g->spoof_argv);
301 free(g);
302 }
303 }
304
305
306 /* Function: esl_getopts_Dump()
307 * Synopsis: Dumps a summary of a <ESL_GETOPTS> configuration.
308 *
309 * Purpose: Dump the state of <g> to an output stream
310 * <ofp>, often stdout or stderr.
311 */
312 void
313 esl_getopts_Dump(FILE *ofp, ESL_GETOPTS *g)
314 {
315 int i, j;
316
317 if (g->argv != NULL)
318 {
319 fprintf(ofp, "argv[0]: %s\n", g->argv[0]);
320 for (i = 1, j = g->optind; j < g->argc; j++, i++)
321 fprintf(ofp, "argument %2d (argv[%2d]): %s\n", i, j, g->argv[j]);
322 fputc('\n', ofp);
323 }
324
325 fprintf(ofp, "%12s %12s %9s\n", "Option", "Setting", "Set by");
326 fprintf(ofp, "------------ ------------ ---------\n");
327
328 for (i = 0; i < g->nopts; i++)
329 {
330 fprintf(ofp, "%-12s ", g->opt[i].name);
331
332 if (g->opt[i].type == eslARG_NONE) fprintf(ofp, "%-12s ", g->val[i] == NULL ? "off" : "on");
333 else fprintf(ofp, "%-12s ", g->val[i]);
334
335 if (g->setby[i] == eslARG_SETBY_DEFAULT) fprintf(ofp, "(default) ");
336 else if (g->setby[i] == eslARG_SETBY_CMDLINE) fprintf(ofp, "cmdline ");
337 else if (g->setby[i] == eslARG_SETBY_ENV) fprintf(ofp, "environ ");
338 else if (g->setby[i] >= eslARG_SETBY_CFGFILE) fprintf(ofp, "cfgfile ");
339
340 fprintf(ofp, "\n");
341 }
342 return;
343 }
344
345 /* Function: esl_getopts_CreateOptsline()
346 *
347 * Synopsis: Creates a string that contains a set of command-line
348 * options that could be provided to the original program to
349 * generate an equivalent getopts object as the one
350 * passed to <esl_getopts_CreateOptsLine()>. This command line
351 * will contain text to set all options in the getopts object
352 * that were not at their default value, regardless of how
353 * those options were set (command-line argument, environment
354 * variable, or in a config file). It may thus differ from the
355 * actual command line that was passed to the program.
356 *
357 * Purpose: This function is ussed within hmmclient/hmmserver to generate
358 * commandline equivalents that can be passed from machine to
359 * machine to re-create the user's desired configuration.
360 *
361 * Returns: The generated string, or NULL if it was unable to create one
362 */
363 char *
364 esl_getopts_CreateOptsLine(ESL_GETOPTS *g)
365 {
366 char *ret_string = (char *) malloc(256); // will grow/realloc as needed
367 char quotemark[2];
368 quotemark[0] = 34; //brutal hack to get a quotation mark into a string without the escape character
369 quotemark[1] = '\0';
370 if (ret_string == NULL) return(NULL);
371 int ret_length =256;
372 int used = 1;
373 ret_string[0] = '\0'; // Set this to a null string in case we don't find any commandiline arguments to return
374 int i, optsize;
375 for (i=0; i < g->nopts; i++){
376 if (g->setby[i] != eslARG_SETBY_DEFAULT && !((g->opt[i].type == eslARG_NONE) && (g->val[i] == 0))){
377 // We need to handle this option because it has a non-default value and isn't false
378 // Unless this is an option that doesn't take an argument and has a value of FALSE. In that case, it must have been
379 // toggled false by some other argument, so ignore it
380 optsize = strlen(g->opt[i].name) +2; //+1 for space after option name
381 if(g->opt[i].type != eslARG_NONE){ //Need an argument to the option
382 optsize+=(strlen(g->val[i])) + 1; // +1 for space after name or terminator character
383 if(g->opt[i].type ==eslARG_STRING){
384 optsize += 2; //quotes around strings
385 }
386 }
387 while(used + optsize > ret_length){
388 ret_string = realloc(ret_string, ret_length *2);
389 ret_length *=2;
390 if(ret_string == 0){
391 return(NULL);
392 }
393 }
394 //Now that we know we have space, add the options string for this option and its value to the commandline
395 strcat(ret_string, " ");
396 strcat(ret_string, g->opt[i].name);
397 if(g->opt[i].type != eslARG_NONE){
398 strcat(ret_string, " ");
399 if(g->opt[i].type== eslARG_STRING){
400 strcat(ret_string, quotemark);
401 }
402 strcat(ret_string, g->val[i]);
403 if(g->opt[i].type== eslARG_STRING){
404 strcat(ret_string, quotemark);
405 }
406 }
407 used += optsize;
408 }
409 }
410 return(ret_string);
411 }
412
413 /*****************************************************************
414 *# 2. Setting and testing a configuration
415 *****************************************************************/
416
417 /* Function: esl_opt_ProcessConfigfile()
418 * Synopsis: Parses options in a config file.
419 *
420 * Purpose: Given an open configuration file <fp> (and
421 * its name <filename>, for error reporting),
422 * parse it and set options in <g> accordingly.
423 * Anything following a <\#> in the file is a
424 * comment. Blank (or all-comment) lines are
425 * ignored. Data lines contain one option and
426 * its optional argument: for example <--foo arg>
427 * or <-a>. All option arguments are type and
428 * range checked, as specified in <g>.
429 *
430 * Returns: <eslOK> on success.
431 *
432 * Returns <eslESYNTAX> on parse or format error in the
433 * file, or f option argument fails a type or range check,
434 * or if an option is set twice by the same config file.
435 * In any of these "normal" (user) error cases, <g->errbuf>
436 * is set to a useful error message to indicate the error.
437 *
438 * Throws: <eslEMEM> on allocation problem.
439 */
440 int
441 esl_opt_ProcessConfigfile(ESL_GETOPTS *g, char *filename, FILE *fp)
442 {
443 char *buf = NULL;
444 int n = 0;
445 char *s;
446 char *optname; /* tainted: from user's input file */
447 char *optarg; /* tainted: from user's input file */
448 char *comment;
449 int line;
450 int opti;
451 int status;
452
453 line = 0;
454 while ((status = esl_fgets(&buf, &n, fp)) != eslEOF)
455 {
456 if (status != eslOK) return status; /* esl_fgets() failed (EMEM) */
457
458 line++;
459 optname = NULL;
460 optarg = NULL;
461
462 /* First token is the option, e.g. "--foo"
463 */
464 s = buf;
465 esl_strtok(&s, " \t\n", &optname);
466 if (optname == NULL) continue; /* blank line */
467 if (*optname == '#') continue; /* comment line */
468 if (*optname != '-')
469 ESL_FAIL(eslESYNTAX, g->errbuf,
470 "Parse failed at line %d of cfg file %.24s (saw %.24s, not an option)\n",
471 line, filename, optname);
472
473 /* Second token, if present, is the arg
474 */
475 if (*s == '"') esl_strtok(&s, "\"", &optarg); /* quote-delimited arg */
476 else esl_strtok(&s, " \t\n", &optarg); /* space-delimited arg */
477
478 /* Anything else on the line had better be a comment
479 */
480 esl_strtok(&s, " \t\n", &comment);
481 if (comment != NULL && *comment != '#')
482 ESL_FAIL(eslESYNTAX, g->errbuf,
483 "Parse failed at line %d of cfg file %.24s (saw %.24s, not a comment)\n",
484 line, filename, comment);
485
486 /* Now we've got an optname and an optional optarg;
487 * figure out what option this is.
488 */
489 if (get_optidx_exactly(g, optname, &opti) != eslOK)
490 ESL_FAIL(eslESYNTAX, g->errbuf,
491 "%.24s is not a recognized option (config file %.24s, line %d)\n",
492 optname, filename, line);
493
494 /* Set that option.
495 * Pass TRUE to set_option's do_alloc flag, because our buffer
496 * is volatile memory that's going away soon - set_option needs
497 * to strdup the arg, not just point to it.
498 */
499 status = set_option(g, opti, optarg,
500 eslARG_SETBY_CFGFILE+g->nfiles,
501 TRUE);
502 if (status != eslOK) return status;
503 }
504
505 if (buf != NULL) free(buf);
506 g->nfiles++;
507 return eslOK;
508 }
509
510
511
512
513 /* Function: esl_opt_ProcessEnvironment()
514 * Synopsis: Parses options in the environment.
515 *
516 * Purpose: For any option defined in <g> that can be modified
517 * by an environment variable, check the environment
518 * and set that option accordingly. The value provided
519 * by the environment is type and range checked.
520 * When an option is turned on that has other options
521 * toggle-tied to it, those options are turned off.
522 * An option's state may only be changed once by the
523 * environment (even indirectly thru toggle-tying);
524 * else an error is generated.
525 *
526 * Returns: <eslOK> on success, and <g> is loaded with all
527 * options specified in the environment.
528 *
529 * Returns <eslEINVAL> on user input problems,
530 * including type/range check failures, and
531 * sets <g->errbuf> to a useful error message.
532 *
533 * Throws: <eslEMEM> on allocation problem.
534 */
535 int
536 esl_opt_ProcessEnvironment(ESL_GETOPTS *g)
537 {
538 int i;
539 char *optarg;
540 int status;
541
542 for (i = 0; i < g->nopts; i++)
543 if (g->opt[i].envvar != NULL &&
544 (optarg = getenv(g->opt[i].envvar)) != NULL)
545 {
546 status = set_option(g, i, optarg, eslARG_SETBY_ENV, FALSE);
547 if (status != eslOK) return status;
548 }
549 return eslOK;
550 }
551
552
553
554 /* Function: esl_opt_ProcessCmdline()
555 * Synopsis: Parses options from the command line.
556 *
557 * Purpose: Process a command line (<argc> and <argv>), parsing out
558 * and setting application options in <g>. Option arguments
559 * are type and range checked before they are set, if type
560 * and range information was set when <g> was created.
561 * When an option is set, if it has any other options
562 * "toggle-tied" to it, those options are also turned off.
563 *
564 * Any given option can only change state (on/off) once
565 * per command line; trying to set the same option more than
566 * once generates an error.
567 *
568 * On successful return, <g> contains settings of all
569 * command line options and their option arguments, for
570 * subsequent retrieval by <esl_opt_Get*()>
571 * functions. <g> also contains an <optind> state variable
572 * pointing to the next <argv[]> element that is not an
573 * option. <esl_opt_GetArg()> needs this to know
574 * where the options end and command line arguments begin
575 * in <argv[0]>.
576 *
577 * The parser starts with <argv[1]> and reads <argv[]> elements
578 * in order until it reaches an element that is not an option;
579 * at this point, all subsequent <argv[]> elements are
580 * interpreted as arguments to the application.
581 *
582 * Any <argv[]> element encountered in the command line that
583 * starts with <- > is an option, except <- > or <-- > by
584 * themselves. <- > by itself is interpreted as a command
585 * line argument (usually meaning ``read from stdin instead
586 * of a filename''). <-- > by itself is interpreted as
587 * ``end of options''; all subsequent <argv[]> elements are
588 * interpreted as command-line arguments even if they
589 * begin with <- >.
590 *
591 * Returns: <eslOK> on success. <g> is loaded with
592 * all option settings specified on the cmdline.
593 * Returns <eslEINVAL> on any cmdline parsing problem,
594 * including option argument type/range check failures,
595 * and sets <g->errbuf> to a useful error message for
596 * the user.
597 *
598 * Throws: <eslEMEM> on allocation problem.
599 */
600 int
601 esl_opt_ProcessCmdline(ESL_GETOPTS *g, int argc, char **argv)
602 {
603 int opti;
604 char *optarg;
605 int status, setstatus;
606
607 g->argc = argc;
608 g->argv = argv;
609 g->optind = 1; /* start at argv[1] */
610 g->optstring = NULL; /* not in a -abc optstring yet */
611
612 /* Walk through each option in the command line using esl_getopts(),
613 * which advances g->optind as the index of the next argv element we need
614 * to look at.
615 */
616 while ((status = esl_getopts(g, &opti, &optarg)) == eslOK)
617 {
618 setstatus = set_option(g, opti, optarg, eslARG_SETBY_CMDLINE, FALSE);
619 if (setstatus != eslOK) return setstatus;
620 }
621 if (status == eslEOD) return eslOK;
622 else return status;
623 }
624
625
626 /* Function: esl_opt_ProcessSpoof()
627 * Synopsis: Parses a string as if it were a command line.
628 *
629 * Purpose: Process the string <cmdline> as if it were a
630 * complete command line.
631 *
632 * Essentially the same as <esl_opt_ProcessCmdline()>
633 * except that whitespace-delimited tokens first need to be
634 * identified in the <cmdline> first, then passed as
635 * <argc>,<argv> to <esl_opt_ProcessCmdline()>.
636 *
637 * Returns: <eslOK> on success, and <g> is loaded with the
638 * application configuration.
639 *
640 * Returns <eslEINVAL> on any parsing problem, and sets
641 * <g->errbuf> to an informative error message.
642 *
643 * Throws: <eslEMEM> on allocation failure.
644 *
645 * Xref: J4/24.
646 */
647 int
648 esl_opt_ProcessSpoof(ESL_GETOPTS *g, const char *cmdline)
649 {
650 int argc = 0;
651 char *s = NULL;
652 void *p;
653 char *tok;
654 int status;
655
656 if (g->spoof != NULL || g->spoof_argv != NULL)
657 ESL_XFAIL(eslEINVAL, g->errbuf, "cannot process more than one spoofed command line");
658
659 if ((status = esl_strdup(cmdline, -1, &(g->spoof))) != eslOK) goto ERROR;
660 s = g->spoof;
661
662 /* old version
663 while (esl_strtok(&s, " \t\n", &tok) == eslOK)
664 {
665 argc++;
666 ESL_RALLOC(g->spoof_argv, p, sizeof(char *) * argc);
667 g->spoof_argv[argc-1] = tok;
668 }
669 */
670 while(*s != '\0'){
671 int status2;
672 if(*s == '\"'){ //token begins with a quote, must end with one or EOL
673 status2 = esl_strtok(&s, "\"", &tok);
674 }
675 else{
676 status2 = esl_strtok(&s, " \t\n", &tok);
677 }
678 if(status2 != eslOK){
679 break; // done parsing tokens
680 }
681 argc++;
682 ESL_RALLOC(g->spoof_argv, p, sizeof(char *) * argc);
683 g->spoof_argv[argc-1] = tok;
684 }
685 status = esl_opt_ProcessCmdline(g, argc, g->spoof_argv);
686 return status;
687
688 ERROR:
689 if (g->spoof != NULL) { free(g->spoof); g->spoof = NULL; }
690 if (g->spoof_argv != NULL) { free(g->spoof_argv); g->spoof_argv = NULL; }
691 return status;
692 }
693
694 /* Function: esl_opt_VerifyConfig()
695 * Synopsis: Validates configuration after options are set.
696 *
697 * Purpose: Given a <g> that we think is fully configured now --
698 * from config file(s), environment, and command line --
699 * verify that the configuration is self-consistent:
700 * for every option that is set, make sure that any
701 * required options are also set, and that no
702 * incompatible options are set. ``Set'' means
703 * the configured value is non-default and non-NULL (including booleans),
704 * and ``not set'' means the value is default or NULL. (That is,
705 * we don't go solely by <setby>, which refers to who
706 * determined the state of an option, even if
707 * it is turned off.)
708 *
709 * Returns: <eslOK> on success.
710 * <eslESYNTAX> if a required option is not set, or
711 * if an incompatible option is set; in this case, sets
712 * <g->errbuf> to contain a useful error message for
713 * the user.
714 *
715 * Throws: <eslEINVAL> if something's wrong with the <ESL_OPTIONS>
716 * structure itself -- a coding error in the application.
717 */
718 int
719 esl_opt_VerifyConfig(ESL_GETOPTS *g)
720 {
721 int i,reqi,incompati;
722 char *s;
723 int status;
724
725 /* For all options that are set (not in default configuration,
726 * and turned on with non-NULL vals),
727 * verify that all their required_opts are set.
728 */
729 for (i = 0; i < g->nopts; i++)
730 {
731 if (g->setby[i] != eslARG_SETBY_DEFAULT && g->val[i] != NULL)
732 {
733 s = g->opt[i].required_opts;
734 while ((status = process_optlist(g, &s, &reqi)) != eslEOD)
735 {
736 if (status != eslOK) ESL_EXCEPTION(eslEINVAL, "something's wrong with format of optlist: %s\n", s);
737 if (g->val[reqi] == NULL)
738 {
739 if (g->setby[i] >= eslARG_SETBY_CFGFILE)
740 ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s (set by cfg file %d) requires (or has no effect without) option(s) %.24s",
741 g->opt[i].name, g->setby[i]-2, g->opt[i].required_opts);
742 else if (g->setby[i] == eslARG_SETBY_ENV)
743 ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s (set by env var %s) requires (or has no effect without) option(s) %.24s",
744 g->opt[i].name, g->opt[i].envvar, g->opt[i].required_opts);
745 else
746 ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s requires (or has no effect without) option(s) %.24s",
747 g->opt[i].name, g->opt[i].required_opts);
748 }
749 }
750 }
751 }
752
753 /* For all options that are set (turned on with non-NULL vals),
754 * verify that no incompatible options are set to non-default
755 * values (notice the setby[incompati] check)
756 */
757 for (i = 0; i < g->nopts; i++)
758 {
759 if (g->setby[i] != eslARG_SETBY_DEFAULT && g->val[i] != NULL)
760 {
761 s = g->opt[i].incompat_opts;
762 while ((status = process_optlist(g, &s, &incompati)) != eslEOD)
763 {
764 if (status != eslOK) ESL_EXCEPTION(eslEINVAL, "something's wrong with format of optlist: %s\n", s);
765 if (incompati != i && (g->setby[incompati] != eslARG_SETBY_DEFAULT && g->val[incompati] != NULL))
766 {
767 if (g->setby[i] >= eslARG_SETBY_CFGFILE)
768 ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s (set by cfg file %d) is incompatible with option(s) %.24s",
769 g->opt[i].name, g->setby[i]-2, g->opt[i].incompat_opts);
770
771 else if (g->setby[i] == eslARG_SETBY_ENV)
772 ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s (set by env var %s) is incompatible with option(s) %.24s",
773 g->opt[i].name, g->opt[i].envvar, g->opt[i].incompat_opts);
774 else
775 ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s is incompatible with option(s) %.24s",
776 g->opt[i].name, g->opt[i].incompat_opts);
777 }
778 }
779 }
780 }
781 return eslOK;
782 }
783
784 /* Function: esl_opt_ArgNumber()
785 * Synopsis: Returns number of command line arguments.
786 *
787 * Purpose: Returns the number of command line arguments.
788 *
789 * Caller must have already called
790 * <esl_opt_ProcessCmdline()>, in order for all the options
791 * to be parsed first. Everything left on the command line
792 * is taken to be an argument.
793 */
794 int
795 esl_opt_ArgNumber(const ESL_GETOPTS *g)
796 {
797 return ((g)->argc - (g)->optind);
798 }
799
800
801 /* Function: esl_opt_SpoofCmdline()
802 * Synopsis: Create faux command line from current option configuration.
803 *
804 * Purpose: Given the current configuration state of the application
805 * <g>, create a command line that would recreate the same
806 * state by itself (without any environment or config file
807 * settings), and return it in <*ret_cmdline>.
808 *
809 * Returns: <eslOK> on success. The <*ret_cmdline> is allocated here,
810 * and caller is responsible for freeing it.
811 *
812 * Throws: <eslEMEM> on allocation error, and <*ret_cmdline> is <NULL>.
813 *
814 * Xref: J4/24
815 */
816 int
817 esl_opt_SpoofCmdline(const ESL_GETOPTS *g, char **ret_cmdline)
818 {
819 char *cmdline = NULL;
820 char *p = NULL;
821 int ntot = 0;
822 int n;
823 int i, j;
824 int status;
825
826 /* Application name/path */
827 ntot = strlen(g->argv[0]) + 1; // +1 for the space
828 ESL_ALLOC(cmdline, sizeof(char) * (ntot+1)); // +1 for the \0
829 snprintf(cmdline, ntot+1, "%s ", g->argv[0]);
830
831 /* Options */
832 for (i = 0; i < g->nopts; i++)
833 if (g->setby[i] != eslARG_SETBY_DEFAULT)
834 {
835 if (g->opt[i].type == eslARG_NONE) n = strlen(g->opt[i].name) + 1;
836 else n = (strlen(g->opt[i].name) + strlen(g->val[i])) + 2;
837
838 ESL_RALLOC(cmdline, p, sizeof(char) * (ntot + n + 1));
839
840 if (g->opt[i].type == eslARG_NONE) snprintf(cmdline + ntot, n+1, "%s ", g->opt[i].name);
841 else snprintf(cmdline + ntot, n+1, "%s %s ", g->opt[i].name, g->val[i]);
842
843 ntot += n;
844 }
845
846 /* Arguments */
847 for (j = g->optind; j < g->argc; j++)
848 {
849 n = strlen(g->argv[j]) + 1;
850 ESL_RALLOC(cmdline, p, sizeof(char) * (ntot + n + 1));
851 snprintf(cmdline + ntot, n+1, "%s ", g->argv[j]);
852 ntot += n;
853 }
854
855 /* Terminate */
856 cmdline[ntot] = '\0';
857 *ret_cmdline = cmdline;
858 return eslOK;
859
860 ERROR:
861 if (cmdline != NULL) free(cmdline);
862 *ret_cmdline = NULL;
863 return status;
864 }
865
866 /*****************************************************************
867 *# 3. Retrieving option settings and command line args
868 *****************************************************************/
869
870 /* Function: esl_opt_IsDefault()
871 * Synopsis: Returns <TRUE> if option remained at default setting.
872 *
873 * Purpose: Returns <TRUE> if option <optname> is in its
874 * default state; returns <FALSE> if <optname> was
875 * changed on the command line, in the environment, or in
876 * a configuration file.
877 */
878 int
879 esl_opt_IsDefault(const ESL_GETOPTS *g, char *optname)
880 {
881 int opti;
882
883 if (get_optidx_exactly(g, optname, &opti) != eslOK) esl_fatal("no such option %s\n", optname);
884 if (g->setby[opti] == eslARG_SETBY_DEFAULT) return TRUE;
885
886 if (g->val[opti] == NULL && g->opt[opti].defval == NULL) return TRUE;
887 if (esl_strcmp(g->opt[opti].defval, g->val[opti]) == 0) return TRUE; /* option may have been set but restored to original default value */
888 return FALSE;
889 }
890
891 /* Function: esl_opt_IsOn()
892 * Synopsis: Returns <TRUE> if option is set to a non-<NULL> value.
893 *
894 * Purpose: Returns <TRUE> if option is on (set to a non-<NULL>
895 * value).
896 *
897 * This is most useful when using integer-, real-, char-,
898 * or string-valued options also as boolean switches, where
899 * they can either be OFF, or they can be turned ON by
900 * having a value. Caller can test <esl_opt_IsOn()> to see
901 * if the option's active at all, then use
902 * <esl_opt_GetString()> or whatever to extract the option
903 * value.
904 *
905 * For a boolean option, the result is identical to
906 * <esl_opt_GetBoolean()>.
907 *
908 * Xref: J4/83.
909 */
910 int
911 esl_opt_IsOn(const ESL_GETOPTS *g, char *optname)
912 {
913 int opti;
914
915 if (get_optidx_exactly(g, optname, &opti) != eslOK) esl_fatal("no such option %s\n", optname);
916 if (g->val[opti] == NULL) return FALSE;
917 else return TRUE;
918 }
919
920
921 /* Function: esl_opt_IsUsed()
922 * Synopsis: Returns <TRUE> if option is on, and this is not the default.
923 *
924 * Purpose: Returns <TRUE> if option <optname> is in use: it has been
925 * set to a non-default value, and that value correspond to
926 * the option being "on" (a non-<NULL> value).
927 *
928 * This is used in printing application headers, where
929 * we want to report all the options that are in effect that
930 * weren't already on by default.
931 *
932 * Xref: J4/83
933 */
934 int
935 esl_opt_IsUsed(const ESL_GETOPTS *g, char *optname)
936 {
937 int opti;
938
939 if (get_optidx_exactly(g, optname, &opti) != eslOK) esl_fatal("no such option %s\n", optname);
940 if (esl_opt_IsDefault(g, optname)) return FALSE;
941 if (g->val[opti] == NULL) return FALSE;
942 return TRUE;
943 }
944
945
946 /* Function: esl_opt_GetSetter()
947 * Synopsis: Returns code for who set this option.
948 *
949 * Purpose: For a processed options object <g>, return the code
950 * for who set option <optname>. This code is <eslARG_SETBY_DEFAULT>,
951 * <eslARG_SETBY_CMDLINE>, <eslARG_SETBY_ENV>, or it
952 * is $\geq$ <eslARG_SETBY_CFGFILE>. If the option
953 * was configured by a config file, the file number (the order
954 * of <esl_opt_ProcessConfigFile()> calls) is encoded in codes
955 * $\geq <eslARG_SETBY_CFGFILE>$ as
956 * file number $=$ <code> - <eslARG_SETBY_CFGFILE> + 1.
957 */
958 int
959 esl_opt_GetSetter(const ESL_GETOPTS *g, char *optname)
960 {
961 int opti;
962
963 if (get_optidx_exactly(g, optname, &opti) != eslOK) esl_fatal("no such option %s\n", optname);
964 return g->setby[opti];
965 }
966
967
968 /* Function: esl_opt_GetBoolean()
969 * Synopsis: Retrieve <TRUE>/<FALSE> for a boolean option.
970 *
971 * Purpose: Retrieves the configured TRUE/FALSE value for option <optname>
972 * from <g>.
973 */
974 int
975 esl_opt_GetBoolean(const ESL_GETOPTS *g, char *optname)
976 {
977 int opti;
978
979 if (get_optidx_exactly(g, optname, &opti) == eslENOTFOUND)
980 esl_fatal("no such option %s\n", optname);
981 if (g->opt[opti].type != eslARG_NONE)
982 esl_fatal("option %s is not a boolean; code called _GetBoolean", optname);
983
984 if (g->val[opti] == NULL) return FALSE;
985 else return TRUE;
986 }
987
988 /* Function: esl_opt_GetInteger()
989 * Synopsis: Retrieve value of an integer option.
990 *
991 * Purpose: Retrieves the configured value for option <optname>
992 * from <g>.
993 */
994 int
995 esl_opt_GetInteger(const ESL_GETOPTS *g, char *optname)
996 {
997 int opti;
998
999 if (get_optidx_exactly(g, optname, &opti) == eslENOTFOUND)
1000 esl_fatal("no such option %s\n", optname);
1001 if (g->opt[opti].type != eslARG_INT)
1002 esl_fatal("option %s does not take an integer arg; code called _GetInteger", optname);
1003 return atoi(g->val[opti]);
1004 }
1005
1006 /* Function: esl_opt_GetReal()
1007 * Synopsis: Retrieve value of a real-valued option.
1008 *
1009 * Purpose: Retrieves the configured value for option <optname>
1010 * from <g>.
1011 */
1012 double
1013 esl_opt_GetReal(const ESL_GETOPTS *g, char *optname)
1014 {
1015 int opti;
1016
1017 if (get_optidx_exactly(g, optname, &opti) == eslENOTFOUND)
1018 esl_fatal("no such option %s\n", optname);
1019 if (g->opt[opti].type != eslARG_REAL)
1020 esl_fatal("option %s does not take a real-valued arg; code called _GetReal", optname);
1021
1022 return (atof(g->val[opti]));
1023 }
1024
1025 /* Function: esl_opt_GetChar()
1026 * Synopsis: Retrieve value of a character option.
1027 *
1028 * Purpose: Retrieves the configured value for option <optname>
1029 * from <g>.
1030 */
1031 char
1032 esl_opt_GetChar(const ESL_GETOPTS *g, char *optname)
1033 {
1034 int opti;
1035
1036 if (get_optidx_exactly(g, optname, &opti) == eslENOTFOUND)
1037 esl_fatal("no such option %s\n", optname);
1038 if (g->opt[opti].type != eslARG_CHAR)
1039 esl_fatal("option %s does not take a char arg; code called _GetChar", optname);
1040
1041 return (*g->val[opti]);
1042 }
1043
1044 /* Function: esl_opt_GetString()
1045 * Synopsis: Retrieve value of a string option.
1046 *
1047 * Purpose: Retrieves the configured value for option <optname>
1048 * from <g>.
1049 *
1050 * This retrieves options of type <eslARG_STRING>,
1051 * obviously, but also options of type <eslARG_INFILE>
1052 * and <eslARG_OUTFILE>.
1053 */
1054 char *
1055 esl_opt_GetString(const ESL_GETOPTS *g, char *optname)
1056 {
1057 int opti;
1058
1059 if (get_optidx_exactly(g, optname, &opti) == eslENOTFOUND)
1060 esl_fatal("no such option %s\n", optname);
1061 if (g->opt[opti].type != eslARG_STRING &&
1062 g->opt[opti].type != eslARG_INFILE &&
1063 g->opt[opti].type != eslARG_OUTFILE)
1064 esl_fatal("option %s does not take a string arg; code called _GetString", optname);
1065
1066 return g->val[opti];
1067 }
1068
1069
1070 /* Function: esl_opt_GetArg()
1071 * Synopsis: Retrieve numbered command line argument.
1072 *
1073 * Purpose: Returns a pointer to command line argument number
1074 * <which>, where <which> ranges from <1..n> for <n>
1075 * total arguments.
1076 *
1077 * If the caller has already verified that <n> arguments
1078 * exist by testing <esl_opt_ArgNumber(g) == n>,
1079 * <esl_opt_GetArg()> is guaranteed to return non-<NULL>
1080 * arguments for <which = 1..n>.
1081 *
1082 * Caller is responsible for verifying that the argument
1083 * makes sense for what it's supposed to be.
1084 *
1085 * Returns: A pointer to command line argument <which> on success, or
1086 * <NULL> if there is no such argument.
1087 */
1088 char *
1089 esl_opt_GetArg(const ESL_GETOPTS *g, int which)
1090 {
1091 if (which <= 0) return NULL;
1092 if (g->optind+which-1 >= g->argc) return NULL;
1093 return g->argv[g->optind+which-1];
1094 }
1095
1096
1097 /*****************************************************************
1098 * 4. Formatting option help
1099 *****************************************************************/
1100
1101 /* Function: esl_opt_DisplayHelp()
1102 * Synopsis: Formats one-line help for each option.
1103 *
1104 * Purpose: For each option in <go>, print one line of brief
1105 * documentation for it, consisting of the option name
1106 * (and argument, if any) and the help string. If space
1107 * allows, default values for the options (if any) are
1108 * shown in brackets. If space still allows, range restrictions
1109 * for the options (if any) are shown in parentheses.
1110 *
1111 * If <docgroup> is non-zero, help lines are only printed
1112 * for options with the matching <go->opt[i].docgrouptag>.
1113 * This allows the caller to group option documentation
1114 * into multiple sections with different headers. To
1115 * print all options in one call, pass 0 for <docgroup>.
1116 *
1117 * <indent> specifies how many spaces to prefix each line with.
1118 *
1119 * <textwidth> specifies the maximum text width for the
1120 * line. This would typically be 80 characters. Lines are
1121 * not allowed to exceed this length. If a line does exceed
1122 * this length, range restriction display is silently
1123 * dropped (for all options). If any line still exceeds
1124 * <textwidth>, the default value display is silently dropped,
1125 * for all options. If any line still exceeds <textwidth>, even
1126 * though it now consists almost solely of the option name and
1127 * its help string, an <eslEINVAL> error is thrown. The
1128 * caller should either shorten the help string(s) or
1129 * increase the <textwidth>.
1130 *
1131 * Returns: <eslOK> on success.
1132 *
1133 * Throws: <eslEINVAL> if one or more help lines are too long for
1134 * the specified <textwidth>.
1135 * <eslEWRITE> if a write fails.
1136 */
1137 int
1138 esl_opt_DisplayHelp(FILE *ofp, const ESL_GETOPTS *go, int docgroup, int indent,
1139 int textwidth)
1140 {
1141 int optwidth = 0; /* maximum width for "-foo <n>" options */
1142 int helpwidth[3] = {0,0,0}; /* 0=everything; 1=with defaults, no range; 2=help string only */
1143 int show_defaults;
1144 int show_ranges;
1145 int i, n;
1146
1147 /* Figure out the field widths we need in the output.
1148 */
1149 for (i = 0; i < go->nopts; i++)
1150 if (! docgroup || docgroup == go->opt[i].docgrouptag)
1151 {
1152 n = strlen(go->opt[i].name); /* "--foo" */
1153 if (go->opt[i].type != eslARG_NONE) n += 4; /* + " <n>" */
1154 if (n > optwidth) optwidth = n;
1155
1156 n = 2; /* init with " : " */
1157 if (go->opt[i].help != NULL)
1158 n = strlen(go->opt[i].help) + 1; /* include " " in width */
1159 if (n > helpwidth[2]) helpwidth[2] = n;
1160
1161 if (go->opt[i].defval != NULL)
1162 n += strlen(go->opt[i].defval) + 4; /* include " []" in width */
1163 if (n > helpwidth[1]) helpwidth[1] = n;
1164
1165 if (go->opt[i].range != NULL)
1166 n += strlen(go->opt[i].range) + 4; /* include " ()" in width */
1167 if (n > helpwidth[0]) helpwidth[0] = n;
1168 }
1169
1170 /* Figure out what we have room for.
1171 */
1172 if (indent + optwidth + helpwidth[0] <= textwidth)
1173 {
1174 show_defaults = TRUE;
1175 show_ranges = TRUE;
1176 }
1177 else if (indent + optwidth + helpwidth[1] <= textwidth)
1178 {
1179 show_defaults = TRUE;
1180 show_ranges = FALSE;
1181 }
1182 else if (indent + optwidth + helpwidth[2] <= textwidth)
1183 {
1184 show_defaults = FALSE;
1185 show_ranges = FALSE;
1186 }
1187 else ESL_EXCEPTION(eslEINVAL, "Help line too long");
1188
1189 /* Format and print the options in this docgroup. */
1190 for (i = 0; i < go->nopts; i++)
1191 if (! docgroup || docgroup == go->opt[i].docgrouptag)
1192 {
1193 if (fprintf(ofp, "%*s", indent, "") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
1194 n = 0;
1195 if (fprintf(ofp, "%s", go->opt[i].name) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
1196 n += strlen(go->opt[i].name);
1197
1198 switch (go->opt[i].type) {
1199 case eslARG_NONE: break;
1200 case eslARG_INT: if (fprintf(ofp, " <n>") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); n += 4; break;
1201 case eslARG_REAL: if (fprintf(ofp, " <x>") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); n += 4; break;
1202 case eslARG_CHAR: if (fprintf(ofp, " <c>") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); n += 4; break;
1203 case eslARG_STRING: if (fprintf(ofp, " <s>") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); n += 4; break;
1204 case eslARG_INFILE: if (fprintf(ofp, " <f>") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); n += 4; break;
1205 case eslARG_OUTFILE: if (fprintf(ofp, " <f>") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); n += 4; break;
1206 }
1207
1208 if (fprintf(ofp, "%*s", optwidth-n, "") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
1209 if (fprintf(ofp, " :") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
1210
1211 if (go->opt[i].help != NULL)
1212 { if (fprintf(ofp, " %s", go->opt[i].help) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); }
1213
1214 if (show_defaults && go->opt[i].defval != NULL)
1215 if (go->opt[i].type != eslARG_CHAR || *(go->opt[i].defval) != '\0')
1216 { if (fprintf(ofp, " [%s]", go->opt[i].defval) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); }
1217
1218 if (show_ranges && go->opt[i].range != NULL)
1219 { if (fprintf(ofp, " (%s)", go->opt[i].range) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); }
1220
1221 if (fprintf(ofp, "\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
1222 }
1223 return eslOK;
1224 }
1225 /*------------------ end of the public API -----------------------*/
1226
1227
1228
1229
1230
1231 /*****************************************************************
1232 * 5. Miscellaneous private functions
1233 *****************************************************************/
1234
1235 /* set_option()
1236 *
1237 * Turn option <opti> ON (if it's a boolean) or set its option
1238 * argument to <optarg>. Record that it was set by <setby> (e.g.
1239 * <eslARG_SETBY_CMDLINE>).
1240 *
1241 * <do_alloc> is a TRUE/FALSE flag. If <arg> is a pointer to a string
1242 * that isn't going to go away (e.g. into argv[], or into the
1243 * environment) we can get away with just pointing our option's val
1244 * at <arg>. But if <arg> is pointing to something volatile (e.g.
1245 * the line buffer as we're reading a file) then we need to
1246 * strdup the arg -- and remember that we did that, so we free()
1247 * it when we destroy the getopts object.
1248 *
1249 * All user errors (problems with optarg) are normal (returned) errors of
1250 * type <eslESYNTAX>, which leave an error message in <g->errbuf>.
1251 *
1252 * May also throw <eslEMEM> on allocation failure, or <eslEINVAL>
1253 * if something's wrong internally, usually indicating a coding error
1254 * in the application's <ESL_OPTIONS> structure.
1255 */
1256 int
1257 set_option(ESL_GETOPTS *g, int opti, char *optarg, int setby, int do_alloc)
1258 {
1259 int arglen;
1260 char *where = NULL;
1261 char *s;
1262 int togi;
1263 int status;
1264 void *tmp;
1265
1266 if (setby == eslARG_SETBY_DEFAULT) where = "as default";
1267 else if (setby == eslARG_SETBY_CMDLINE) where = "on cmdline";
1268 else if (setby == eslARG_SETBY_ENV) where = "in env";
1269 else if (setby >= eslARG_SETBY_CFGFILE) where = "in cfgfile";
1270
1271 /* Have we already set this option? */
1272 if (g->setby[opti] == setby)
1273 ESL_FAIL(eslESYNTAX, g->errbuf,
1274 "Option %.24s has already been set %s.",
1275 g->opt[opti].name, where);
1276
1277 /* Type and range check the option argument.
1278 */
1279 if (verify_type_and_range(g, opti, optarg, setby) != eslOK) return eslESYNTAX;
1280
1281 /* Set the option, being careful about when val
1282 * is alloc'ed vs. not.
1283 */
1284 g->setby[opti] = setby;
1285 if (g->opt[opti].type == eslARG_NONE) /* booleans: any non-NULL is TRUE... */
1286 { /* watch out for booleans getting toggled off/on */
1287 if (g->opt[opti].defval) g->val[opti] = g->opt[opti].defval; /* use default string if provided: IsDefault() needs this */
1288 else g->val[opti] = (char *) TRUE; /* else 0x1 will do fine. */
1289 }
1290 else
1291 {
1292 /* If do_alloc is FALSE or the optarg is NULL, then:
1293 * - free any previous alloc;
1294 * - set the pointer.
1295 */
1296 if (!do_alloc || optarg == NULL)
1297 {
1298 if (g->valloc[opti] > 0) { free(g->val[opti]); g->valloc[opti] = 0; }
1299 g->val[opti] = optarg;
1300 }
1301 /* else do_alloc is TRUE, so:
1302 * - make sure we have enough room, either reallocating or allocating
1303 * - copy the arg.
1304 */
1305 else
1306 {
1307 arglen = strlen(optarg);
1308 if (g->valloc[opti] < arglen+1)
1309 {
1310 if (g->valloc[opti] == 0) ESL_ALLOC (g->val[opti], sizeof(char) * (arglen+1));
1311 else ESL_RALLOC(g->val[opti], tmp, sizeof(char) * (arglen+1));
1312 g->valloc[opti] = arglen+1;
1313 }
1314 strcpy(g->val[opti], optarg);
1315 }
1316 }
1317
1318 /* Unset all options toggle-tied to this one.
1319 */
1320 s = g->opt[opti].toggle_opts;
1321 while ((status = process_optlist(g, &s, &togi)) != eslEOD)
1322 {
1323 if (status != eslOK) ESL_EXCEPTION(eslEINVAL, "something's wrong with format of optlist: %s\n", s);
1324 if (togi == opti) continue; /* ignore ourself, so we can have one toggle list per group */
1325 if (g->val[togi] == NULL) continue; /* it's already off; don't touch it */
1326
1327 if (g->setby[togi] == setby)
1328 ESL_FAIL(eslESYNTAX, g->errbuf,
1329 "Options %.24s and %.24s conflict, toggling each other.",
1330 g->opt[togi].name, g->opt[opti].name);
1331
1332 g->setby[togi] = setby; /* indirectly, but still */
1333 if (g->valloc[togi] > 0) /* careful about val's that were alloc'ed */
1334 { free(g->val[togi]); g->valloc[togi] = 0; }
1335 g->val[togi] = NULL; /* ok for false booleans too */
1336 }
1337 return eslOK;
1338
1339 ERROR:
1340 return status;
1341 }
1342
1343 /* get_optidx_exactly():
1344 *
1345 * Find option named <optname> in <g>; set <ret_opti> to be
1346 * the index of the option, and return eslOK. <optname>
1347 * must exactly match one of the options in <g>.
1348 *
1349 * If the option is not found, return <eslENOTFOUND>; in this
1350 * case <*ret_opti> is -1 (and caller should not use it!)
1351 */
1352 static int
1353 get_optidx_exactly(const ESL_GETOPTS *g, char *optname, int *ret_opti)
1354 {
1355 int i;
1356
1357 for (i = 0; i < g->nopts; i++)
1358 if (strcmp(optname, g->opt[i].name) == 0) { *ret_opti = i; return eslOK; }
1359 *ret_opti = -1;
1360 return eslENOTFOUND;
1361 }
1362
1363 /* get_optidx_abbrev():
1364 *
1365 * Find option named <optname> in <g>; set <ret_opti> to be the index
1366 * of the option, and return eslOK. Allow <optname> to be an
1367 * abbreviation of one of the option names in <g>, so long as it is
1368 * unambiguous. If <n> is >0, the <optname> has an attached argument
1369 * (--foo=arg) and <n> is the # of characters before the = character
1370 * that we should match to find the option (5, in this example).
1371 *
1372 * If the option is not found, return <eslENOTFOUND>.
1373 * If <optname> ambiguously matches two or more options in <g>,
1374 * return <eslEAMBIGUOUS>.
1375 */
1376 static int
1377 get_optidx_abbrev(ESL_GETOPTS *g, char *optname, int n, int *ret_opti)
1378 {
1379 int nabbrev = 0;
1380 int nexact = 0;
1381 int i;
1382
1383 if (n == 0) /* unless we're told otherwise: */
1384 n = strlen(optname); /* all of optname abbrev must match against the real name */
1385
1386 for (i = 0; i < g->nopts; i++)
1387 if (strncmp(g->opt[i].name, optname, n) == 0)
1388 {
1389 nabbrev++;
1390 *ret_opti = i;
1391 if (n == strlen(g->opt[i].name)) { nexact++; break; } /* an exact match; can stop now (xref bug #e4) */
1392 }
1393 if (nexact != 1 && nabbrev > 1) return eslEAMBIGUOUS;
1394 if (nabbrev == 0) return eslENOTFOUND;
1395 return eslOK;
1396 }
1397 /*----------- end of private functions for retrieving option indices -------------*/
1398
1399
1400
1401 /*****************************************************************
1402 * Private functions for processing options out of a command line
1403 *****************************************************************/
1404
1405 /* esl_getopts():
1406 *
1407 * Get the next option in argv[], and its argument (if any),
1408 * and pass this information back via <ret_opti> (index of
1409 * next option) and <ret_optarg).
1410 *
1411 * Return <eslOK> on success, <eslEOD> if we're out of
1412 * options.
1413 *
1414 * Returns <eslESYNTAX> and sets <g->errbuf> to a useful error
1415 * message if something's wrong with one of the user's options.
1416 *
1417 * Throws <eslEINVAL> if something's wrong internally with the
1418 * <ESL_OPTIONS> structure.
1419 */
1420 static int
1421 esl_getopts(ESL_GETOPTS *g, int *ret_opti, char **ret_optarg)
1422 {
1423 *ret_optarg = NULL;
1424
1425 /* Check to see if we've run out of options.
1426 * A '-' by itself is an argument (e.g. "read from stdin"), not an option.
1427 */
1428 if (g->optstring == NULL &&
1429 (g->optind >= g->argc || g->argv[g->optind][0] != '-' || strcmp(g->argv[g->optind], "-") == 0))
1430 return eslEOD; /* normal end-of-data (end of options) return */
1431
1432 /* Check to see if we're being told that this is the end
1433 * of the options with the special "--" flag.
1434 */
1435 if (g->optstring == NULL &&
1436 strcmp(g->argv[g->optind], "--") == 0)
1437 {
1438 g->optind++;
1439 return eslEOD; /* also a normal end-of-data return */
1440 }
1441
1442 /* We have an option: an argv element that starts with -, but is
1443 * not "-" or "--".
1444 *
1445 * We know the strncmp() test is ok for 2 chars, because if the option was
1446 * 1 char, we would've already caught it above (either it's a bare "-"
1447 * or it's a single non-option char, and in either case it's not an option
1448 * and we returned eslEOD.
1449 *
1450 * Watch out for the case where we're in the middle of a concatenated optstring
1451 * of single-letter options, a la -abc
1452 */
1453 if (g->optstring == NULL && strncmp(g->argv[g->optind], "--", 2) == 0)
1454 return process_longopt(g, ret_opti, ret_optarg);
1455 else
1456 return process_stdopt(g, ret_opti, ret_optarg);
1457 }
1458
1459 /* process_longopt():
1460 *
1461 * optind is sitting on a long option, w/ syntax of one of these forms:
1462 * --foo
1463 * --foo arg
1464 * --foo=arg
1465 * (GNU getopt long option syntax.)
1466 *
1467 * Allow unambiguous abbreviations of long options when matching;
1468 * e.g. --foo is ok for matching a long option --foobar.
1469 *
1470 * Returns <eslOK> on success, returning the option number through
1471 * <ret_opti>, and a ptr to its argument through <ret_optarg> (or NULL
1472 * if this option takes no argument.) Internally, g->optind is
1473 * advanced to next argv element (+1, +2, +1, respectively, for --foo,
1474 * --foo arg, --foo=arg).
1475 *
1476 * Returns <eslESYNTAX> and sets a useful error mesg in <g->errbuf> if:
1477 * 1. Option can't be found in opt[].
1478 * 2. Option abbreviation is ambiguous, matching opt[] nonuniquely.
1479 * 3. Option takes an argument, but no argument found.
1480 * 4. Option does not take an argument, but one was provided by =arg syntax.
1481 * All of these are user input errors.
1482
1483 */
1484 static int
1485 process_longopt(ESL_GETOPTS *g, int *ret_opti, char **ret_optarg)
1486 {
1487 int opti; /* option number found */
1488 char *argptr; /* ptr to arg in --foo=arg syntax */
1489 int n; /* length of argv elem's option part (up to = or \0) */
1490 int status;
1491
1492 /* Deal with options of syntax "--foo=arg" w/o modifying argv.
1493 */
1494 if ((argptr = strchr(g->argv[g->optind], '=')) != NULL)
1495 { n = argptr - g->argv[g->optind]; argptr++; } /* bump argptr off the = to the arg itself */
1496 else
1497 { n = strlen(g->argv[g->optind]); } /* and argptr == NULL from above. */
1498
1499 /* Figure out which option this is.
1500 * The trick here is to allow abbreviations, and identify
1501 * ambiguities while we're doing it. (GNU getopt allows abbrevs.)
1502 */
1503 status = get_optidx_abbrev(g, g->argv[g->optind], n, &opti);
1504 if (status == eslEAMBIGUOUS)
1505 ESL_FAIL(eslESYNTAX, g->errbuf, "Abbreviated option \"%.24s\" is ambiguous.", g->argv[g->optind]);
1506 else if (status == eslENOTFOUND)
1507 ESL_FAIL(eslESYNTAX, g->errbuf, "No such option \"%.24s\".", g->argv[g->optind]);
1508 else if (status != eslOK)
1509 ESL_EXCEPTION(eslEINCONCEIVABLE, "Something went wrong with option \"%.24s\".", g->argv[g->optind]);
1510
1511 *ret_opti = opti;
1512 g->optind++; /* optind was on the option --foo; advance the counter to next argv element */
1513
1514 /* Find the argument, if there is supposed to be one.
1515 */
1516 if (g->opt[opti].type != eslARG_NONE)
1517 {
1518 if (argptr != NULL) /* if --foo=arg syntax, then we already found it */
1519 *ret_optarg = argptr;
1520 else if (g->optind >= g->argc)
1521 ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s requires an argument.", g->opt[opti].name);
1522 else { /* "--foo 666" style, with a space */
1523 *ret_optarg = g->argv[g->optind++]; /* assign optind as the arg, advance counter */
1524
1525 /* Watch out for options masquerading as missing arguments. */
1526 if ((g->opt[opti].type == eslARG_STRING || g->opt[opti].type == eslARG_INFILE || g->opt[opti].type == eslARG_OUTFILE)
1527 && **ret_optarg == '-')
1528 ESL_FAIL(eslESYNTAX, g->errbuf,
1529 "Arg looks like option? Use %.24s=%.24s if you really mean it.",
1530 g->opt[opti].name, *ret_optarg);
1531 }
1532 }
1533 else /* if there's not supposed to be an arg, but there is, then die */
1534 {
1535 if (argptr != NULL)
1536 ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s does not take an argument.", g->opt[opti].name);
1537 *ret_optarg = NULL;
1538 }
1539 return eslOK;
1540 }
1541
1542 /* process_stdopt():
1543 *
1544 * Either we're in the middle of working on an optstring (and optind
1545 * is sitting on the next argv element, which may be an argument of
1546 * the last char in the optstring), or optind is sitting on a "-"
1547 * option and we should start working on a new optstring. That is,
1548 * we're dealing with standard one-char options, which may be
1549 * concatenated into an optstring.
1550 *
1551 * Only the last optchar in a optstring may take an argument. The argument
1552 * is either the remainder of the argv element (if any) or if not, the
1553 * next argv element.
1554 *
1555 * Examples of syntax:
1556 * -a
1557 * -W arg
1558 * -Warg
1559 * -abc
1560 * -abcW arg
1561 * -abcWarg
1562 *
1563 * Process next optchar; return <eslOK> on success, returning option
1564 * number through <ret_opti> and a pointer to any argument through
1565 * <ret_optarg>. Internally, optind is advanced to the next argv element;
1566 * either 0, +1, or +2, depending on whether we're still processing an
1567 * optstring from a prev optind, starting a new optstring, or reading
1568 * a "-W arg" form, respectively.
1569 *
1570 * Returns <eslESYNTAX> and sets <g->errbuf> to a helpful error mesg if:
1571 * 1. The option doesn't exist.
1572 * 2. The option takes an argument, but none was found.
1573 * 3. The option takes an untypechecked argument (eslARG_STRING,
1574 * eslARG_INFILE, or eslARG_OUTFILE), the argument is unattached
1575 * (space-delimited), and it appears to be an option instead of
1576 * an argument, because it starts with '-'.
1577 * All these are user input errors.
1578 */
1579 static int
1580 process_stdopt(ESL_GETOPTS *g, int *ret_opti, char **ret_optarg)
1581 {
1582 int opti;
1583
1584 /* Do we need to start a new optstring in a new argv element?
1585 * (as opposed to still being in an optstring from a prev parse)
1586 */
1587 if (g->optstring == NULL)
1588 g->optstring = g->argv[g->optind++]+1; /* init optstring on first option char; advance optind */
1589
1590 /* Figure out what option this optchar is
1591 */
1592 for (opti = 0; opti < g->nopts; opti++)
1593 if (*(g->optstring) == g->opt[opti].name[1]) break; /* this'll also fail appropriately for long opts. */
1594 if (opti == g->nopts)
1595 ESL_FAIL(eslESYNTAX, g->errbuf, "No such option \"-%c\".", *(g->optstring));
1596 *ret_opti = opti;
1597
1598 /* Find the argument, if there's supposed to be one */
1599 if (g->opt[opti].type != eslARG_NONE)
1600 {
1601 if (*(g->optstring+1) != '\0') /* attached argument case, a la -Warg */
1602 *ret_optarg = g->optstring+1;
1603 else if (g->optind < g->argc) { /* unattached argument; assign optind, advance counter */
1604 *ret_optarg = g->argv[g->optind++];
1605
1606 /* Watch out for options masquerading as missing arguments. */
1607 if ((g->opt[opti].type == eslARG_STRING || g->opt[opti].type == eslARG_INFILE || g->opt[opti].type == eslARG_OUTFILE)
1608 && **ret_optarg == '-')
1609 ESL_FAIL(eslESYNTAX, g->errbuf,
1610 "Arg looks like option? Use %.24s%.24s if you really mean it.",
1611 g->opt[opti].name, *ret_optarg);
1612 } else
1613 ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s requires an argument", g->opt[opti].name);
1614
1615 g->optstring = NULL; /* An optchar that takes an arg must terminate an optstring. */
1616 }
1617 else /* if there's not supposed to be an argument, then check if we're still in an optstring */
1618 {
1619 *ret_optarg = NULL;
1620 if (*(g->optstring+1) != '\0') /* yup, we're still in an optstring */
1621 g->optstring++;
1622 else
1623 g->optstring = NULL; /* nope, that's it; move to next field in args */
1624 }
1625 return eslOK;
1626 }
1627 /*----------- end of private functions for processing command line options -------------*/
1628
1629
1630
1631
1632 /*****************************************************************
1633 * Private functions for type and range checking.
1634 *****************************************************************/
1635
1636 /* verify_type_and_range():
1637 *
1638 * Implementation of type and range checking for options.
1639 *
1640 * Given a value <val> (as a string) for option <i> in the option
1641 * object <g>, verify that <val> satisfies the appropriate type and
1642 * range. If successful, return <eslOK>.
1643 *
1644 * The <setby> flag is used to help format useful error messages,
1645 * by saying who was responsible for a bad <val>.
1646 *
1647 * Returns: <eslOK> on success.
1648 * Returns <eslESYNTAX> if <val> fails type/range checking,
1649 * and <g->errbuf> is set to contain an error report for the user.
1650 *
1651 * Throws: <eslEINVAL>: a range string format was bogus.
1652 * <eslEINCONCEIVABLE>: "can't happen" internal errors.
1653 */
1654 static int
1655 verify_type_and_range(ESL_GETOPTS *g, int i, char *val, int setby)
1656 {
1657 char *where = NULL;
1658
1659 if (setby == eslARG_SETBY_DEFAULT) where = "as default";
1660 else if (setby == eslARG_SETBY_CMDLINE) where = "on cmdline";
1661 else if (setby == eslARG_SETBY_ENV) where = "in env";
1662 else if (setby >= eslARG_SETBY_CFGFILE) where = "in cfgfile";
1663
1664 /* A special case: Any option may be "unset" by default by having a
1665 * NULL default value. Thus, for instance, an eslARG_REAL can be
1666 * off by default, or set to a value by a command line option.
1667 */
1668 if (setby == eslARG_SETBY_DEFAULT && val == NULL)
1669 return eslOK;
1670
1671 switch (g->opt[i].type) {
1672 case eslARG_NONE:
1673 /* treat as unchecked, because val may be "on", 0x1, "true", etc.:
1674 * any non-NULL ptr means on, and NULL means off.
1675 */
1676 break;
1677
1678 case eslARG_INT:
1679 if (! esl_str_IsInteger(val))
1680 ESL_FAIL(eslESYNTAX, g->errbuf,
1681 "Option %.24s takes integer arg; got %.24s %s",
1682 g->opt[i].name, val, where);
1683
1684 if (verify_integer_range(val, g->opt[i].range) != eslOK)
1685 ESL_FAIL(eslESYNTAX, g->errbuf,
1686 "option %.24s takes integer arg in range %.24s; got %.24s %s",
1687 g->opt[i].name, g->opt[i].range, val, where);
1688 break;
1689
1690 case eslARG_REAL:
1691 if (! esl_str_IsReal(val))
1692 ESL_FAIL(eslESYNTAX, g->errbuf,
1693 "Option %.24s takes real-valued arg; got %.24s %s",
1694 g->opt[i].name, val, where);
1695
1696 if (verify_real_range(val, g->opt[i].range) != eslOK)
1697 ESL_FAIL(eslESYNTAX, g->errbuf,
1698 "Option %.24s takes real-valued arg in range %.24s; got %.24s %s",
1699 g->opt[i].name, g->opt[i].range, val, where);
1700 break;
1701
1702 case eslARG_CHAR:
1703 if (strlen(val) > 1)
1704 ESL_FAIL(eslESYNTAX, g->errbuf,
1705 "Option %.24s takes char arg; got %.24s %s",
1706 g->opt[i].name, val, where);
1707
1708 if (verify_char_range(val, g->opt[i].range) != eslOK)
1709 ESL_FAIL(eslESYNTAX, g->errbuf,
1710 "Option %.24s takes char arg in range %.24s; got %.24s %s",
1711 g->opt[i].name, g->opt[i].range, val, where);
1712 break;
1713
1714 case eslARG_STRING: /* unchecked type. */
1715 case eslARG_INFILE:
1716 case eslARG_OUTFILE:
1717 if (g->opt[i].range != NULL)
1718 ESL_EXCEPTION(eslEINVAL, "option %s takes a string arg that can't be range checked", g->opt[i].name);
1719 break;
1720
1721 default:
1722 ESL_EXCEPTION(eslEINVAL, "no such argument type");
1723 }
1724
1725 return eslOK;
1726 }
1727
1728
1729 /* verify_integer_range():
1730 *
1731 * Returns <eslOK> if the string <arg>, when converted to an integer
1732 * by atoi(), gives a value that lies within the given <range>, if
1733 * <range> is non-NULL. (If <range> is NULL, there is no constraint on
1734 * the range of this <arg>, so return TRUE.) Else, <arg> does not lie
1735 * in the <range>; return <eslERANGE> (a user input error). If <range>
1736 * itself is misformatted, return <eslEINVAL> (a coding error).
1737 *
1738 * Range must be in one of three formats, matched
1739 * by these regexps (though regexps aren't used by the
1740 * parser):
1741 * n>=?(\d+) lower bound
1742 * n<=?(\d+) upper bound
1743 * (\d+)<=?n<=?(\d+) lower and upper bound
1744 * Optional = signs indicate whether a bound is
1745 * inclusive or not. The "n" character indicates the
1746 * given integer value.
1747 *
1748 * Returns: <eslOK>: <arg> is within allowed <range>.
1749 * <eslERANGE>: <arg> is not within allowed <range>.
1750 * <eslEINVAL>: something wrong with <range> string.
1751 */
1752 static int
1753 verify_integer_range(char *arg, char *range)
1754 {
1755 int n;
1756 int upper, lower; /* upper, lower bounds */
1757 char *up, *lp;
1758 int geq, leq; /* use >=, <= instead of >, < */
1759
1760 if (range == NULL) return eslOK;
1761 n = atoi(arg);
1762
1763 if (parse_rangestring(range, 'n', &lp, &geq, &up, &leq) != eslOK) return eslEINVAL;
1764
1765 if (lp != NULL) {
1766 lower = atoi(lp);
1767 if ((geq && ! (n >= lower)) || (!geq && !(n > lower))) return eslERANGE;
1768 }
1769
1770 if (up != NULL) {
1771 upper = atoi(up);
1772 if ((leq && ! (n <= upper)) || (!leq && !(n < upper))) return eslERANGE;
1773 }
1774 return eslOK;
1775 }
1776
1777
1778
1779 /* verify_real_range():
1780 *
1781 * Verify that a string <arg>, when converted to a
1782 * double-precision real by atof(), gives a value that lies
1783 * within the range defined by <range>. If <range> is NULL,
1784 * there is no range constraint, and any <arg> is valid.
1785 *
1786 * Returns: <eslOK>: <arg> is within allowed <range>.
1787 * <eslERANGE>: <arg> is not within allowed <range>.
1788 * <eslEINVAL>: something wrong with <range> string.
1789 */
1790 static int
1791 verify_real_range(char *arg, char *range)
1792 {
1793 double x;
1794 double upper, lower; /* upper, lower bounds */
1795 char *up, *lp;
1796 int geq, leq; /* use >=, <= instead of >, < */
1797
1798 if (range == NULL) return eslOK;
1799 x = atof(arg);
1800
1801 if (parse_rangestring(range, 'x', &lp, &geq, &up, &leq) != eslOK)
1802 return eslEINVAL;
1803
1804 if (lp != NULL)
1805 {
1806 lower = atof(lp);
1807 if ((geq && ! (x >= lower)) || (!geq && !(x > lower)))
1808 return eslERANGE;
1809 }
1810
1811 if (up != NULL)
1812 {
1813 upper = atof(up);
1814 if ((leq && ! (x <= upper)) || (!leq && !(x < upper)))
1815 return eslERANGE;
1816 }
1817 return eslOK;
1818 }
1819
1820
1821 /* verify_char_range():
1822 *
1823 * Verify that a string <arg>, when interpreted as a single
1824 * char argument, is a character that lies within the defined
1825 * <range>. If <range> is NULL, there is no range constraint,
1826 * and any <arg> is valid.
1827 *
1828 * Currently, <range> expression is limited to ASCII chars that can be
1829 * expressed as single chars. Could improve by allowing integer ASCII
1830 * codes, or backslash escapes.
1831 *
1832 * Returns: <eslOK>: <arg> is within allowed <range>.
1833 * <eslERANGE>: <arg> is not within allowed <range>.
1834 * <eslEINVAL>: something wrong with <range> string.
1835 */
1836 static int
1837 verify_char_range(char *arg, char *range)
1838 {
1839 char c;
1840 char *upper, *lower;
1841 int geq, leq; /* use >=, <= instead of >, < */
1842
1843 if (range == NULL) return eslOK;
1844 c = *arg;
1845
1846 if (parse_rangestring(range, 'c', &lower, &geq, &upper, &leq) != eslOK)
1847 return eslEINVAL;
1848
1849 if (lower != NULL)
1850 {
1851 if ((geq && ! (c >= *lower)) || (!geq && !(c > *lower)))
1852 return eslERANGE;
1853 }
1854
1855 if (upper != NULL)
1856 {
1857 if ((leq && ! (c <= *upper)) || (!leq && !(c < *upper)))
1858 return eslERANGE;
1859 }
1860 return eslOK;
1861 }
1862
1863
1864
1865 /* parse_rangestring():
1866 *
1867 * Given a range definition string in one of the following forms:
1868 * c>=?(\d+) lower bound
1869 * c<=?(\d+) upper bound
1870 * (\d+)<=?c<=?(\d+) lower and upper bound
1871 * where <c> is a one-character marker expected for the
1872 * argument type ('n' for integers, 'f' for floating-point values,
1873 * 'c' for characters).
1874 *
1875 * Sets pointers to upper and lower bound strings, for parsing by
1876 * atoi() or atof() as appropriate.
1877 * Sets geq, leq flags to TRUE if bounds are supposed to be inclusive.
1878 *
1879 * Returns <eslOK> on success, <eslEINVAL> if the range string
1880 * is invalid. No errors are thrown here, so caller can format a
1881 * useful error message if range string is bogus.
1882 */
1883 static int
1884 parse_rangestring(char *range, char c, char **ret_lowerp, int *ret_geq, char **ret_upperp, int *ret_leq)
1885 {
1886 char *ptr;
1887
1888 *ret_geq = *ret_leq = FALSE; /* 'til proven otherwise */
1889 *ret_lowerp = *ret_upperp = NULL; /* 'til proven otherwise */
1890
1891 if ((ptr = strchr(range, c)) == NULL) return eslEINVAL;
1892 if (ptr == range) /* we're "n>=a" or "n<=b" form, where n came first */
1893 {
1894 if (ptr[1] == '>') /* "n>=a" form; lower bound */
1895 {
1896 if (ptr[2] == '=') { *ret_geq = TRUE; *ret_lowerp = ptr+3; }
1897 else *ret_lowerp = ptr+2;
1898 }
1899 else if (ptr[1] == '<') /* "n<=a" form; upper bound */
1900 {
1901 if (ptr[2] == '=') { *ret_leq = TRUE; *ret_upperp = ptr+3; }
1902 else *ret_upperp = ptr+2;
1903 }
1904 else return eslEINVAL;
1905 }
1906 else /* we're in a<=n<=b form; upper bound after n, lower before */
1907 {
1908 if (*(ptr+1) != '<') return eslEINVAL;
1909 if (*(ptr+2) == '=') { *ret_leq = TRUE; *ret_upperp = ptr+3; } else *ret_upperp = ptr+2;
1910
1911 ptr--;
1912 if (*ptr == '=') { *ret_geq = TRUE; ptr--; }
1913 if (*ptr != '<') return eslEINVAL;
1914 *ret_lowerp = range; /* start of string */
1915 }
1916 return eslOK;
1917 }
1918
1919 /*-------------- end of private type/range-checking functions ----------------*/
1920
1921
1922
1923
1924 /*****************************************************************
1925 * Private functions for checking optlists (toggles, required options,
1926 * and incompatible options
1927 *****************************************************************/
1928
1929 /* process_optlist():
1930 *
1931 * Given a pointer <s> to the next option name in
1932 * a comma-delimited list, figure out what option
1933 * this is; set <ret_opti> to its index. If another
1934 * option remains in the optlist, reset <s> to
1935 * the start of it, for the next call to process_optlist().
1936 * If no options remain after this one, reset <s> to NULL.
1937 *
1938 * Returns: <eslOK> if an option has been successfully parsed
1939 * out of the list and <ret_opti> is valid;
1940 * <eslEOD> if no more option remains (<s> is NULL,
1941 * or points to a \0).
1942 * <eslEINVAL> if an option in the list isn't
1943 * recognized (a coding error).
1944 */
1945 static int
1946 process_optlist(ESL_GETOPTS *g, char **ret_s, int *ret_opti)
1947 {
1948 char *s;
1949 int i;
1950 int n;
1951
1952 if ((s = *ret_s) == NULL) return eslEOD;
1953 if (*s == '\0') return eslEOD;
1954
1955 n = strcspn(s, ",");
1956
1957 /* a little weak here; we're only matching a n-long prefix, so we're
1958 * not going to catch the case where the optlist contains a
1959 * truncated, ambiguous optionname. but optlists are not user
1960 * input, so the answer to this problem is "don't do that".
1961 */
1962 for (i = 0; i < g->nopts; i++)
1963 if (strncmp(g->opt[i].name, s, n) == 0) break;
1964 if (i == g->nopts) return eslEINVAL;
1965
1966 *ret_opti = i;
1967 if (s[n] == ',') *ret_s = s+n+1;
1968 else *ret_s = NULL;
1969
1970 return eslOK;
1971 }
1972
1973 /*------- end of private functions for processing optlists -----------*/
1974
1975
1976
1977 /*****************************************************************
1978 * 6. Test driver.
1979 *****************************************************************/
1980
1981 #ifdef eslGETOPTS_TESTDRIVE
1982 /* gcc -g -Wall -o getopts_utest -I. -DeslGETOPTS_TESTDRIVE esl_getopts.c easel.c
1983 */
1984 #include <stdlib.h>
1985 #include <stdio.h>
1986
1987 #include "easel.h"
1988 #include "esl_getopts.h"
1989
1990 /*::cexcerpt::getopts_bigarray::begin::*/
1991 #define BGROUP "-b,--no-b"
1992 static ESL_OPTIONS options[] = {
1993 /* name type default env_var range toggles req incompat help docgroup */
1994 { "-a", eslARG_NONE, FALSE,"FOOTEST",NULL, NULL, NULL, NULL, "toggle a on", 1 },
1995 { "-b", eslARG_NONE, FALSE, NULL, NULL, BGROUP, NULL, NULL, "toggle b on", 1 },
1996 { "--no-b", eslARG_NONE,"TRUE", NULL, NULL, BGROUP, NULL, NULL, "toggle b off", 1 },
1997 { "-c", eslARG_CHAR, "x", NULL,"a<=c<=z",NULL, NULL, NULL, "character arg", 2 },
1998 { "--d1", eslARG_NONE,"TRUE", NULL, NULL, "--d2", NULL, NULL, "toggle d1 on, d2 off", 2 },
1999 { "--d2", eslARG_NONE, FALSE, NULL, NULL, "--d1", NULL, NULL, "toggle d2 on, d1 off", 2 },
2000 { "-n", eslARG_INT, "0", NULL,"0<=n<10",NULL, NULL, NULL, "integer arg", 2 },
2001 { "-x", eslARG_REAL, "0.8", NULL, "0<x<1", NULL, NULL, NULL, "real-value arg", 2 },
2002 { "--lowx", eslARG_REAL, "1.0", NULL, "x>0", NULL, NULL, NULL, "real arg with lower bound", 2 },
2003 { "--hix", eslARG_REAL, "0.9", NULL, "x<1", NULL, NULL, NULL, "real arg with upper bound", 2 },
2004 { "--lown", eslARG_INT, "42", NULL, "n>0", NULL,"-a,-b", NULL, "int arg with lower bound", 2 },
2005 { "--hin", eslARG_INT, "-1", NULL, "n<0", NULL, NULL,"--no-b","int arg with upper bound", 2 },
2006 { "--host", eslARG_STRING, "","HOSTTEST",NULL, NULL, NULL, NULL, "string arg with env var", 3 },
2007 { "--multi",eslARG_STRING,NULL, NULL, NULL, NULL, NULL, NULL, "test quoted configfile arg",3 },
2008 { "--mul", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "test long opt abbreviation",3 }, /* xref bug #e4 */
2009 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
2010 };
2011 /*::cexcerpt::getopts_bigarray::end::*/
2012
2013 int
2014 main(void)
2015 {
2016 ESL_GETOPTS *go, *go2;
2017 char file1[32] = "esltmpXXXXXX";
2018 char file2[32] = "esltmpXXXXXX";
2019 char *errmsg = "getopts unit test failure";
2020 FILE *f1, *f2;
2021 int i;
2022
2023 /* Declare a "command line" internally. */
2024 int argc = 11; /* progname; 8 options; 2 args */
2025 char *argv[] = { "progname", "-bc", "y", "--d1", "-n9", "--hix=0.0", "--lown", "43", "--mul", "arg1", "2005"};
2026
2027 /* Create a config file #1. */
2028 if (esl_tmpfile_named(file1, &f1) != eslOK) esl_fatal("failed to create named tmpfile 1");
2029 fprintf(f1, "# Test config file #1\n");
2030 fprintf(f1, "#\n");
2031 fprintf(f1, "-b\n");
2032 fprintf(f1, "--d2\n");
2033 fprintf(f1, "-n 3\n");
2034 fprintf(f1, "-x 0.5\n");
2035 fprintf(f1, "--multi \"one two three\"\n");
2036 fclose(f1);
2037
2038 /* Create config file #2. */
2039 if (esl_tmpfile_named(file2, &f2) != eslOK) esl_fatal("failed to create named tmpfile 2");
2040 fprintf(f2, "# Test config file #2\n");
2041 fprintf(f2, "#\n");
2042 fprintf(f2, "--no-b\n");
2043 fprintf(f2, "--hin -33\n");
2044 fprintf(f2, "--host www.nytimes.com\n");
2045 fclose(f2);
2046
2047 /* Put some test vars in the environment.
2048 * (Note: apparently, on some OS's (Mac OS/X), setenv() necessarily leaks memory.)
2049 */
2050 setenv("FOOTEST", "", 1);
2051 setenv("HOSTTEST", "wasp.cryptogenomicon.org", 1);
2052
2053 /* Open the test config files for reading.
2054 */
2055 if ((f1 = fopen(file1, "r")) == NULL) esl_fatal("getopts fopen() 1 failed");
2056 if ((f2 = fopen(file2, "r")) == NULL) esl_fatal("getopts fopen() 2 failed");
2057
2058 go = esl_getopts_Create(options);
2059 if (esl_opt_ProcessConfigfile(go, file1, f1) != eslOK) esl_fatal("getopts failed to process config file 1\n%s\n", go->errbuf);
2060 if (esl_opt_ProcessConfigfile(go, file2, f2) != eslOK) esl_fatal("getopts failed to process config file 2\n%s\n", go->errbuf);
2061 if (esl_opt_ProcessEnvironment(go) != eslOK) esl_fatal("getopts failed to process environment:\n%s\n", go->errbuf);
2062 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK) esl_fatal("getopts failed to process command line:\n%s\n", go->errbuf);
2063 if (esl_opt_VerifyConfig(go) != eslOK) esl_fatal("getopts config fails validation:\n%s\n", go->errbuf);
2064
2065 fclose(f1);
2066 fclose(f2);
2067
2068 if (esl_opt_GetBoolean(go, "-a") != TRUE) esl_fatal("getopts failed on -a"); /* -a is ON: by environment */
2069 if (esl_opt_GetBoolean(go, "-b") != TRUE) esl_fatal("getopts failed on -b"); /* -b is toggled thrice, ends up ON */
2070 if (esl_opt_GetBoolean(go, "--no-b") != FALSE) esl_fatal("getopts failed on --no-b"); /* so --no-b is OFF */
2071 if (esl_opt_GetChar (go, "-c") != 'y') esl_fatal("getopts failed on -c"); /* set to y on cmdline in an optstring */
2072 if (esl_opt_GetInteger(go, "-n") != 9) esl_fatal("getopts failed on -n"); /* cfgfile, then on cmdline as linked arg*/
2073 if (esl_opt_GetReal (go, "-x") != 0.5) esl_fatal("getopts failed on -x"); /* cfgfile #1 */
2074 if (esl_opt_GetReal (go, "--lowx") != 1.0) esl_fatal("getopts failed on --lowx"); /* stays at default */
2075 if (esl_opt_GetReal (go, "--hix") != 0.0) esl_fatal("getopts failed on --hix"); /* arg=x format on cmdline */
2076 if (esl_opt_GetInteger(go, "--lown") != 43) esl_fatal("getopts failed on --lown"); /* cmdline; requires -a -b */
2077 if (esl_opt_GetInteger(go, "--hin") != -33) esl_fatal("getopts failed on --hin"); /* cfgfile 2; requires --no-b to be off */
2078 if (esl_opt_GetBoolean(go, "--mul") != TRUE) esl_fatal("getopts failed on --mul"); /* --mul should not be confused with --multi by abbrev parser*/
2079 if (strcmp(esl_opt_GetString(go, "--host"), "wasp.cryptogenomicon.org") != 0)
2080 esl_fatal("getopts failed on --host"); /* cfgfile 2, then overridden by environment */
2081 if (strcmp(esl_opt_GetString(go, "--multi"), "one two three") != 0)
2082 esl_fatal("config file didn't handle quoted argument");
2083
2084 /* --d1, --d2 test that we can resolve the difference between IsDefault(), IsOn(), and IsUsed() */
2085 /* these options, despite getting toggled twice on/off, remain at default values;
2086 * so d1 is default, on, and not used (because it's default); d2 is default, off, and not used.
2087 * IsDefault IsOn IsUsed
2088 * ------- ----- -------
2089 * true true true [can't happen: option must be non-default to be considered "in use"]
2090 * true true false --d1 for example, despite being toggled twice
2091 * true false true [can't happen: option must be non-default to be considered "in use"]
2092 * true false false --d2 for example, despite being toggled twice
2093 * false true true -a,-b for example
2094 * false true false [can't happen: if option is ON and not in default state, it's "in use"]
2095 * false false true [can't happen: if option is OFF, it's not "in use"]
2096 * false false false --no-b for example
2097 */
2098 if (! esl_opt_IsDefault(go, "--d1")) esl_fatal(errmsg);
2099 if (! esl_opt_IsOn (go, "--d1")) esl_fatal(errmsg);
2100 if ( esl_opt_IsUsed (go, "--d1")) esl_fatal(errmsg);
2101 if (! esl_opt_IsDefault(go, "--d2")) esl_fatal(errmsg);
2102 if ( esl_opt_IsOn (go, "--d2")) esl_fatal(errmsg);
2103 if ( esl_opt_IsUsed (go, "--d2")) esl_fatal(errmsg);
2104 if ( esl_opt_IsDefault(go, "-a")) esl_fatal(errmsg);
2105 if (! esl_opt_IsOn (go, "-a")) esl_fatal(errmsg);
2106 if (! esl_opt_IsUsed (go, "-a")) esl_fatal(errmsg);
2107 if ( esl_opt_IsDefault(go, "-b")) esl_fatal(errmsg);
2108 if (! esl_opt_IsOn (go, "-b")) esl_fatal(errmsg);
2109 if (! esl_opt_IsUsed (go, "-b")) esl_fatal(errmsg);
2110 if ( esl_opt_IsDefault(go, "--no-b")) esl_fatal(errmsg);
2111 if ( esl_opt_IsOn (go, "--no-b")) esl_fatal(errmsg);
2112 if ( esl_opt_IsUsed (go, "--no-b")) esl_fatal(errmsg);
2113
2114 for (i = 0; i < go->nopts; i++)
2115 { /* Test that no option is in an impossible default/on/used state according to logic table above */
2116 if ( esl_opt_IsDefault(go, go->opt[i].name) && esl_opt_IsOn(go, go->opt[i].name) && esl_opt_IsUsed(go, go->opt[i].name)) esl_fatal(errmsg);
2117 if ( esl_opt_IsDefault(go, go->opt[i].name) && ! esl_opt_IsOn(go, go->opt[i].name) && esl_opt_IsUsed(go, go->opt[i].name)) esl_fatal(errmsg);
2118 if (! esl_opt_IsDefault(go, go->opt[i].name) && esl_opt_IsOn(go, go->opt[i].name) && ! esl_opt_IsUsed(go, go->opt[i].name)) esl_fatal(errmsg);
2119 if (! esl_opt_IsDefault(go, go->opt[i].name) && ! esl_opt_IsOn(go, go->opt[i].name) && esl_opt_IsUsed(go, go->opt[i].name)) esl_fatal(errmsg);
2120 }
2121
2122 //test if we can recover options line from getopts
2123 char *cmdline = esl_getopts_CreateOptsLine(go);
2124 #if 0 // some test code removed here
2125 int mismatch;
2126 if (mismatch = strcmp(cmdline, " -a -b -c y --d1 -n 9 -x 0.5 --hix 0.0 --lown 43 --hin -33 --host \"wasp.cryptogenomicon.org\" --multi \"one two three\" --mul"))
2127 esl_fatal("esl_getopts_CreateOptsLine test failed at position %d", mismatch);
2128 #endif
2129 char *spoofline;
2130 spoofline = (char *) malloc(strlen(cmdline)+ 8);
2131 if(spoofline == NULL) esl_fatal(errmsg);
2132 strcpy(spoofline, "getopts");
2133 strcat(spoofline, cmdline);
2134
2135 //test that we can parse the options line into a new getopts:
2136 go2 = esl_getopts_Create(options);
2137 if (esl_opt_ProcessSpoof(go2, spoofline) != eslOK) esl_fatal("errmsg");
2138 if (esl_opt_VerifyConfig(go2) != eslOK) esl_fatal("errmsg");
2139
2140 //go2 should now be the same as go, so re-run all checks
2141 if (esl_opt_GetBoolean(go2, "-a") != TRUE) esl_fatal("getopts failed on -a"); /* -a is ON: by environment */
2142 if (esl_opt_GetBoolean(go2, "-b") != TRUE) esl_fatal("getopts failed on -b"); /* -b is toggled thrice, ends up ON */
2143 if (esl_opt_GetBoolean(go2, "--no-b") != FALSE) esl_fatal("getopts failed on --no-b"); /* so --no-b is OFF */
2144 if (esl_opt_GetChar (go2, "-c") != 'y') esl_fatal("getopts failed on -c"); /* set to y on cmdline in an optstring */
2145 if (esl_opt_GetInteger(go2, "-n") != 9) esl_fatal("getopts failed on -n"); /* cfgfile, then on cmdline as linked arg*/
2146 if (esl_opt_GetReal (go2, "-x") != 0.5) esl_fatal("getopts failed on -x"); /* cfgfile #1 */
2147 if (esl_opt_GetReal (go2, "--lowx") != 1.0) esl_fatal("getopts failed on --lowx"); /* stays at default */
2148 if (esl_opt_GetReal (go2, "--hix") != 0.0) esl_fatal("getopts failed on --hix"); /* arg=x format on cmdline */
2149 if (esl_opt_GetInteger(go2, "--lown") != 43) esl_fatal("getopts failed on --lown"); /* cmdline; requires -a -b */
2150 if (esl_opt_GetInteger(go2, "--hin") != -33) esl_fatal("getopts failed on --hin"); /* cfgfile 2; requires --no-b to be off */
2151 if (esl_opt_GetBoolean(go2, "--mul") != TRUE) esl_fatal("getopts failed on --mul"); /* --mul should not be confused with --multi by abbrev parser*/
2152 if (strcmp(esl_opt_GetString(go2, "--host"), "wasp.cryptogenomicon.org") != 0)
2153 esl_fatal("getopts failed on --host"); /* cfgfile 2, then overridden by environment */
2154 if (strcmp(esl_opt_GetString(go2, "--multi"), "one two three") != 0)
2155 esl_fatal("config file didn't handle quoted argument");
2156 if (! esl_opt_IsDefault(go2, "--d1")) esl_fatal(errmsg);
2157 if (! esl_opt_IsOn (go2, "--d1")) esl_fatal(errmsg);
2158 if ( esl_opt_IsUsed (go2, "--d1")) esl_fatal(errmsg);
2159 if (! esl_opt_IsDefault(go2, "--d2")) esl_fatal(errmsg);
2160 if ( esl_opt_IsOn (go2, "--d2")) esl_fatal(errmsg);
2161 if ( esl_opt_IsUsed (go2, "--d2")) esl_fatal(errmsg);
2162 if ( esl_opt_IsDefault(go2, "-a")) esl_fatal(errmsg);
2163 if (! esl_opt_IsOn (go2, "-a")) esl_fatal(errmsg);
2164 if (! esl_opt_IsUsed (go2, "-a")) esl_fatal(errmsg);
2165 if ( esl_opt_IsDefault(go2, "-b")) esl_fatal(errmsg);
2166 if (! esl_opt_IsOn (go2, "-b")) esl_fatal(errmsg);
2167 if (! esl_opt_IsUsed (go2, "-b")) esl_fatal(errmsg);
2168 if ( esl_opt_IsDefault(go2, "--no-b")) esl_fatal(errmsg);
2169 if ( esl_opt_IsOn (go2, "--no-b")) esl_fatal(errmsg);
2170 if ( esl_opt_IsUsed (go2, "--no-b")) esl_fatal(errmsg);
2171
2172 for (i = 0; i < go->nopts; i++)
2173 { /* Test that no option is in an impossible default/on/used state according to logic table above */
2174 if ( esl_opt_IsDefault(go2, go2->opt[i].name) && esl_opt_IsOn(go2, go2->opt[i].name) && esl_opt_IsUsed(go2, go2->opt[i].name)) esl_fatal(errmsg);
2175 if ( esl_opt_IsDefault(go2, go2->opt[i].name) && ! esl_opt_IsOn(go2, go2->opt[i].name) && esl_opt_IsUsed(go2, go2->opt[i].name)) esl_fatal(errmsg);
2176 if (! esl_opt_IsDefault(go2, go2->opt[i].name) && esl_opt_IsOn(go2, go2->opt[i].name) && ! esl_opt_IsUsed(go2, go2->opt[i].name)) esl_fatal(errmsg);
2177 if (! esl_opt_IsDefault(go2, go2->opt[i].name) && ! esl_opt_IsOn(go2, go2->opt[i].name) && esl_opt_IsUsed(go2, go2->opt[i].name)) esl_fatal(errmsg);
2178 }
2179 free(cmdline);
2180 free(spoofline);
2181 /* Now the two remaining argv[] elements are the command line args
2182 */
2183 if (esl_opt_ArgNumber(go) != 2) esl_fatal("getopts failed with wrong arg number");
2184
2185 if (strcmp("arg1", esl_opt_GetArg(go, 1)) != 0) esl_fatal("getopts failed on argument 1");
2186 if (strcmp("2005", esl_opt_GetArg(go, 2)) != 0) esl_fatal("getopts failed on argument 2");
2187
2188 esl_getopts_Destroy(go);
2189 esl_getopts_Destroy(go2);
2190 remove(file1);
2191 remove(file2);
2192 exit(0);
2193 }
2194
2195 #endif /*eslGETOPTS_TESTDRIVE*/
2196 /*-------------- end of test driver -------------------------*/
2197
2198 /*****************************************************************
2199 * 7. Examples.
2200 *****************************************************************/
2201
2202 /* The starting example of "standard" getopts behavior, without
2203 * any of the bells and whistles.
2204 * Compile:
2205 gcc -g -Wall -o getopts_example -I. -DeslGETOPTS_EXAMPLE esl_getopts.c easel.c
2206 */
2207 #ifdef eslGETOPTS_EXAMPLE
2208 /*::cexcerpt::getopts_example::begin::*/
2209 #include <stdio.h>
2210 #include "easel.h"
2211 #include "esl_getopts.h"
2212
2213 static ESL_OPTIONS options[] = {
2214 /* name type def env range toggles reqs incomp help docgroup*/
2215 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
2216 { "-a", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "a boolean switch", 0},
2217 { "-b", eslARG_NONE,"default", NULL, NULL, NULL, NULL, NULL, "another boolean switch", 0},
2218 { "-n", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "an integer argument", 0},
2219 { "-s", eslARG_STRING, "hi!", NULL, NULL, NULL, NULL, NULL, "a string argument", 0},
2220 { "-x", eslARG_REAL, "1.0", NULL, NULL, NULL, NULL, NULL, "a real-valued argument", 0},
2221 { "--file", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "long option, filename arg", 0},
2222 { "--char", eslARG_CHAR, "", NULL, NULL, NULL, NULL, NULL, "long option, char arg", 0},
2223 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
2224 };
2225 static char usage[] = "Usage: ./example [-options] <arg>";
2226
2227 int
2228 main(int argc, char **argv)
2229 {
2230 ESL_GETOPTS *go;
2231 char *arg;
2232
2233 if ((go = esl_getopts_Create(options)) == NULL) esl_fatal("Bad options structure\n");
2234 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK) esl_fatal("Failed to parse command line: %s\n", go->errbuf);
2235 if (esl_opt_VerifyConfig(go) != eslOK) esl_fatal("Failed to parse command line: %s\n", go->errbuf);
2236
2237 if (esl_opt_GetBoolean(go, "-h") == TRUE) {
2238 printf("%s\n where options are:", usage);
2239 esl_opt_DisplayHelp(stdout, go, 0, 2, 80); /* 0=all docgroups; 2=indentation; 80=width */
2240 return 0;
2241 }
2242
2243 if (esl_opt_ArgNumber(go) != 1) esl_fatal("Incorrect number of command line arguments.\n%s\n", usage);
2244 arg = esl_opt_GetArg(go, 1);
2245
2246 printf("Option -a: %s\n", esl_opt_GetBoolean(go, "-a") ? "on" : "off");
2247 printf("Option -b: %s\n", esl_opt_GetBoolean(go, "-b") ? "on" : "off");
2248 printf("Option -n: %d\n", esl_opt_GetInteger(go, "-n"));
2249 printf("Option -s: %s\n", esl_opt_GetString( go, "-s"));
2250 printf("Option -x: %f\n", esl_opt_GetReal( go, "-x"));
2251 if (esl_opt_IsUsed(go, "--file")) printf("Option --file: %s\n", esl_opt_GetString(go, "--file"));
2252 else printf("Option --file: (not set)\n");
2253 printf("Option --char: %c\n", esl_opt_GetChar(go, "--char"));
2254 printf("Cmdline arg: %s\n", arg);
2255
2256 esl_getopts_Destroy(go);
2257 return 0;
2258 }
2259 /*::cexcerpt::getopts_example::end::*/
2260 #endif /*eslGETOPTS_EXAMPLE*/
2261
2262 /* Using <esl_getopts_CreateDefaultApp()> implements a standard series
2263 * of events, including how the -h (help) option is handled.
2264 * Compile:
2265 gcc -g -Wall -o getopts_example2 -I. -DeslGETOPTS_EXAMPLE2 esl_getopts.c easel.c
2266 */
2267 #ifdef eslGETOPTS_EXAMPLE2
2268 /*::cexcerpt::getopts_example2::begin::*/
2269 #include <stdio.h>
2270 #include "easel.h"
2271 #include "esl_getopts.h"
2272
2273 static ESL_OPTIONS options[] = {
2274 /* name type default env range toggles reqs incomp help docgroup*/
2275 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
2276 { "-a", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "a boolean switch", 0},
2277 { "-n", eslARG_INT, "42",NULL, NULL, NULL, NULL, NULL, "an integer", 0},
2278 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
2279 };
2280 static char banner[] = "example of using simplest getopts creation";
2281 static char usage[] = "[-options] <arg1> <arg2>";
2282
2283 int
2284 main(int argc, char **argv)
2285 {
2286 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 2, argc, argv, banner, usage);
2287 char *arg1 = esl_opt_GetArg(go, 1);
2288 char *arg2 = esl_opt_GetArg(go, 2);
2289 int a = esl_opt_GetBoolean(go, "-a");
2290 int n = esl_opt_GetInteger(go, "-n");
2291
2292 printf("arg 1: %s\n", arg1);
2293 printf("arg 2: %s\n", arg2);
2294 printf("option a: %s\n", (a ? "true" : "false"));
2295 printf("option n: %d\n", n);
2296
2297 esl_getopts_Destroy(go);
2298 return 0;
2299 }
2300 /*::cexcerpt::getopts_example2::end::*/
2301 #endif /*eslGETOPTS_EXAMPLE2*/
2302 /*-------------- end of examples ---------------------*/
2303
2304
2305
2306