forked from EddyRivasLab/easel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
esl_getopts.c
2306 lines (2053 loc) · 86.3 KB
/
esl_getopts.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Implements a somewhat more powerful command line getopt interface
* than the standard UNIX/POSIX call.
*
* Contents:
* 1. The ESL_GETOPTS object.
* 2. Setting and testing a configuration.
* 3. Retrieving option settings and command line args.
* 4. Formatting option help.
* 5. Private functions.
* 6. Test driver.
* 7. Examples.
*
* xref STL8/p152; STL9/p5.
*/
#include <esl_config.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "easel.h"
#include "esl_getopts.h"
/* Forward declarations of private functions. */
static int set_option(ESL_GETOPTS *g, int opti, char *optarg,
int setby, int do_alloc);
static int get_optidx_exactly(const ESL_GETOPTS *g, char *optname, int *ret_opti);
static int get_optidx_abbrev(ESL_GETOPTS *g, char *optname, int n,
int *ret_opti);
static int esl_getopts(ESL_GETOPTS *g, int *ret_opti, char **ret_optarg);
static int process_longopt(ESL_GETOPTS *g, int *ret_opti, char **ret_optarg);
static int process_stdopt(ESL_GETOPTS *g, int *ret_opti, char **ret_optarg);
static int verify_type_and_range(ESL_GETOPTS *g, int i, char *val, int setby);
static int verify_integer_range(char *arg, char *range);
static int verify_real_range(char *arg, char *range);
static int verify_char_range(char *arg, char *range);
static int parse_rangestring(char *range, char c, char **ret_lowerp,
int *ret_geq, char **ret_upperp, int *ret_leq);
static int process_optlist(ESL_GETOPTS *g, char **ret_s, int *ret_opti);
/*****************************************************************
*# 1. The <ESL_GETOPTS> object
*****************************************************************/
/* Function: esl_getopts_Create()
* Synopsis: Create a new <ESL_GETOPTS> object.
*
* Purpose: Creates an <ESL_GETOPTS> object, given the
* array of valid options <opt> (NULL-element-terminated).
* Sets default values for all config
* options (as defined in <opt>).
*
* Returns: ptr to the new <ESL_GETOPTS> object.
*
* Throws: NULL on failure, including allocation failures or
* an invalid <ESL_OPTIONS> structure.
*/
ESL_GETOPTS *
esl_getopts_Create(const ESL_OPTIONS *opt)
{
ESL_GETOPTS *g = NULL;
int status;
int i;
ESL_ALLOC(g, sizeof(ESL_GETOPTS));
g->opt = opt;
g->argc = 0;
g->argv = NULL;
g->optind = 1;
g->nfiles = 0;
g->val = NULL;
g->setby = NULL;
g->valloc = NULL;
g->optstring = NULL;
g->spoof = NULL;
g->spoof_argv= NULL;
g->errbuf[0] = '\0';
/* Figure out the number of options.
*
* Using the NULL-terminated structure array is a design decision.
* Alternatively, the caller could provide us with noptions, and use
* a #define noptions (sizeof(options) / sizeof(ESL_GETOPTS)) idiom.
* Note that we can't use sizeof() here, because now <opt> is just a
* pointer.
*
* A drawback of requiring NULL termination is, what happens when
* the caller forgets? Thus the check for a leading '-' on all
* options; if we start straying into memory, that check should
* catch us.
*/
g->nopts = 0;
while (g->opt[g->nopts].name != NULL) {
if (g->opt[g->nopts].name[0] != '-')
ESL_XEXCEPTION(eslEINVAL, "option %d didn't start with '-';\nyou may have forgotten to NULL-terminate the ESL_OPTIONS array", g->nopts);
g->nopts++;
}
/* Set default values for all options.
* Note the valloc[] setting: we only need to dup strings
* into allocated space if the value is volatile memory, and
* that only happens in config files; not in defaults, cmdline,
* or environment.
*/
ESL_ALLOC(g->val, sizeof(char *) * g->nopts);
ESL_ALLOC(g->setby, sizeof(int) * g->nopts);
ESL_ALLOC(g->valloc, sizeof(int) * g->nopts);
for (i = 0; i < g->nopts; i++)
{
g->val[i] = g->opt[i].defval;
g->setby[i] = eslARG_SETBY_DEFAULT;
g->valloc[i] = 0;
}
/* Verify type/range of the defaults, even though it's
* an application error (not user error) if they're invalid.
*/
for (i = 0; i < g->nopts; i++)
if (verify_type_and_range(g, i, g->val[i], eslARG_SETBY_DEFAULT) != eslOK)
ESL_XEXCEPTION(eslEINVAL, "%s\n", g->errbuf);
return g;
ERROR:
esl_getopts_Destroy(g);
return NULL;
}
/* Function: esl_getopts_CreateDefaultApp()
* Synopsis: Initialize a standard Easel application.
*
* Purpose: Carry out the usual sequence of events in initializing a
* small Easel-based application: parses the command line,
* process the <-h> option to produce a (single-sectioned)
* help page, and check that the number of command line
* options is right.
*
* <options> is an array of <ESL_OPTIONS> structures describing
* the options, terminated by an all-<NULL> structure.
*
* <nargs> is the number of commandline arguments
* expected. If the number of commandline arguments isn't
* equal to this, an error message is printed, with the
* <usage> string, and <exit()> is called. If <nargs> is
* -1, this check isn't done; if your program deliberately
* has a variable number of commandline arguments (i.e.
* if the number is unknown at compile time), pass -1
* for <nargs>.
*
* <argc> and <argv> are the command line
* arguments (number and pointer array) from <main()>.
*
* <banner> is an optional one-line description of the
* program's function, such as <"compare RNA structures">.
* When the <-h> help option is selected, this description
* will be combined with the program's name (the tail of
* <argv[0]>) and Easel's copyright and license information
* to give a header like:
*
* \begin{cchunk}
* # esl-compstruct :: compare RNA structures
* # Easel 0.1 (February 2005)
* # Copyright (C) 2004-2007 HHMI Janelia Farm Research Campus
* # Freely licensed under the Janelia Software License.
* # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* \end{cchunk}
*
* <usage> is an optional one-line description of command
* line usage (without the command name), such as
* \begin{cchunk}
* [options] <trusted file> <test file>
* \end{cchunk}
* On errors, or
* on the help page, this usage string is combined with
* the program's name to give a usage line like:
*
* \begin{cchunk}
* Usage: esl-compstruct [options] <trusted file> <test file>
* \end{cchunk}
*
* <banner> and <usage> are optional, meaning that either
* can be provided as <NULL> and they won't be shown.
*
* Returns: a pointer to a new <ESL_GETOPTS> object, which contains
* all the option settings and command line arguments.
*
* On command line errors, this routine exits with abnormal
* (1) status.
*
* If the <-h> help option is seen, this routine exits with
* normal (0) status after printing a help page.
*
*/
ESL_GETOPTS *
esl_getopts_CreateDefaultApp(const ESL_OPTIONS *options, int nargs, int argc, char **argv, char *banner, char *usage)
{
ESL_GETOPTS *go = NULL;
go = esl_getopts_Create(options);
if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK ||
esl_opt_VerifyConfig(go) != eslOK)
{
printf("Failed to parse command line: %s\n", go->errbuf);
if (usage != NULL) esl_usage(stdout, argv[0], usage);
printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
exit(1);
}
if (esl_opt_GetBoolean(go, "-h") == TRUE)
{
if (banner != NULL) esl_banner(stdout, argv[0], banner);
if (usage != NULL) esl_usage (stdout, argv[0], usage);
puts("\nOptions:");
esl_opt_DisplayHelp(stdout, go, 0, 2, 80);
exit(0);
}
if (nargs != -1 && esl_opt_ArgNumber(go) != nargs)
{
puts("Incorrect number of command line arguments.");
esl_usage(stdout, argv[0], usage);
printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
exit(1);
}
return go;
}
/* Function: esl_getopts_Reuse()
* Synopsis: Reset application state to default.
*
* Purpose: Reset application configuration <g> to initial defaults,
* as if it were newly created (before any
* processing of environment, config files, or
* command line).
*
* Returns: <eslOK> on success.
*
* Throws: (no abnormal error conditions)
*
* Xref: J4/24.
*/
int
esl_getopts_Reuse(ESL_GETOPTS *g)
{
int i;
/* Restore defaults for all options */
for (i = 0; i < g->nopts; i++)
{
if (g->valloc[i] > 0) { free(g->val[i]); }
g->val[i] = g->opt[i].defval;
g->setby[i] = eslARG_SETBY_DEFAULT;
g->valloc[i] = 0;
}
if (g->spoof != NULL) free(g->spoof);
if (g->spoof_argv != NULL) free(g->spoof_argv);
g->argc = 0;
g->argv = NULL;
g->optind = 1;
g->nfiles = 0;
g->optstring = NULL;
g->spoof = NULL;
g->spoof_argv = NULL;
g->errbuf[0] = '\0';
return eslOK;
}
/* Function: esl_getopts_Destroy()
* Synopsis: Destroys an <ESL_GETOPTS> object.
*
* Purpose: Free's a created <ESL_GETOPTS> object.
*
* Returns: void.
*/
void
esl_getopts_Destroy(ESL_GETOPTS *g)
{
int i;
if (g != NULL)
{
if (g->val != NULL)
{
/* A few of our vals may have been allocated.
*/
for (i = 0; i < g->nopts; i++)
if (g->valloc[i] > 0)
free(g->val[i]);
free(g->val);
}
if (g->setby != NULL) free(g->setby);
if (g->valloc != NULL) free(g->valloc);
if (g->spoof != NULL) free(g->spoof);
if (g->spoof_argv != NULL) free(g->spoof_argv);
free(g);
}
}
/* Function: esl_getopts_Dump()
* Synopsis: Dumps a summary of a <ESL_GETOPTS> configuration.
*
* Purpose: Dump the state of <g> to an output stream
* <ofp>, often stdout or stderr.
*/
void
esl_getopts_Dump(FILE *ofp, ESL_GETOPTS *g)
{
int i, j;
if (g->argv != NULL)
{
fprintf(ofp, "argv[0]: %s\n", g->argv[0]);
for (i = 1, j = g->optind; j < g->argc; j++, i++)
fprintf(ofp, "argument %2d (argv[%2d]): %s\n", i, j, g->argv[j]);
fputc('\n', ofp);
}
fprintf(ofp, "%12s %12s %9s\n", "Option", "Setting", "Set by");
fprintf(ofp, "------------ ------------ ---------\n");
for (i = 0; i < g->nopts; i++)
{
fprintf(ofp, "%-12s ", g->opt[i].name);
if (g->opt[i].type == eslARG_NONE) fprintf(ofp, "%-12s ", g->val[i] == NULL ? "off" : "on");
else fprintf(ofp, "%-12s ", g->val[i]);
if (g->setby[i] == eslARG_SETBY_DEFAULT) fprintf(ofp, "(default) ");
else if (g->setby[i] == eslARG_SETBY_CMDLINE) fprintf(ofp, "cmdline ");
else if (g->setby[i] == eslARG_SETBY_ENV) fprintf(ofp, "environ ");
else if (g->setby[i] >= eslARG_SETBY_CFGFILE) fprintf(ofp, "cfgfile ");
fprintf(ofp, "\n");
}
return;
}
/* Function: esl_getopts_CreateOptsline()
*
* Synopsis: Creates a string that contains a set of command-line
* options that could be provided to the original program to
* generate an equivalent getopts object as the one
* passed to <esl_getopts_CreateOptsLine()>. This command line
* will contain text to set all options in the getopts object
* that were not at their default value, regardless of how
* those options were set (command-line argument, environment
* variable, or in a config file). It may thus differ from the
* actual command line that was passed to the program.
*
* Purpose: This function is ussed within hmmclient/hmmserver to generate
* commandline equivalents that can be passed from machine to
* machine to re-create the user's desired configuration.
*
* Returns: The generated string, or NULL if it was unable to create one
*/
char *
esl_getopts_CreateOptsLine(ESL_GETOPTS *g)
{
char *ret_string = (char *) malloc(256); // will grow/realloc as needed
char quotemark[2];
quotemark[0] = 34; //brutal hack to get a quotation mark into a string without the escape character
quotemark[1] = '\0';
if (ret_string == NULL) return(NULL);
int ret_length =256;
int used = 1;
ret_string[0] = '\0'; // Set this to a null string in case we don't find any commandiline arguments to return
int i, optsize;
for (i=0; i < g->nopts; i++){
if (g->setby[i] != eslARG_SETBY_DEFAULT && !((g->opt[i].type == eslARG_NONE) && (g->val[i] == 0))){
// We need to handle this option because it has a non-default value and isn't false
// Unless this is an option that doesn't take an argument and has a value of FALSE. In that case, it must have been
// toggled false by some other argument, so ignore it
optsize = strlen(g->opt[i].name) +2; //+1 for space after option name
if(g->opt[i].type != eslARG_NONE){ //Need an argument to the option
optsize+=(strlen(g->val[i])) + 1; // +1 for space after name or terminator character
if(g->opt[i].type ==eslARG_STRING){
optsize += 2; //quotes around strings
}
}
while(used + optsize > ret_length){
ret_string = realloc(ret_string, ret_length *2);
ret_length *=2;
if(ret_string == 0){
return(NULL);
}
}
//Now that we know we have space, add the options string for this option and its value to the commandline
strcat(ret_string, " ");
strcat(ret_string, g->opt[i].name);
if(g->opt[i].type != eslARG_NONE){
strcat(ret_string, " ");
if(g->opt[i].type== eslARG_STRING){
strcat(ret_string, quotemark);
}
strcat(ret_string, g->val[i]);
if(g->opt[i].type== eslARG_STRING){
strcat(ret_string, quotemark);
}
}
used += optsize;
}
}
return(ret_string);
}
/*****************************************************************
*# 2. Setting and testing a configuration
*****************************************************************/
/* Function: esl_opt_ProcessConfigfile()
* Synopsis: Parses options in a config file.
*
* Purpose: Given an open configuration file <fp> (and
* its name <filename>, for error reporting),
* parse it and set options in <g> accordingly.
* Anything following a <\#> in the file is a
* comment. Blank (or all-comment) lines are
* ignored. Data lines contain one option and
* its optional argument: for example <--foo arg>
* or <-a>. All option arguments are type and
* range checked, as specified in <g>.
*
* Returns: <eslOK> on success.
*
* Returns <eslESYNTAX> on parse or format error in the
* file, or f option argument fails a type or range check,
* or if an option is set twice by the same config file.
* In any of these "normal" (user) error cases, <g->errbuf>
* is set to a useful error message to indicate the error.
*
* Throws: <eslEMEM> on allocation problem.
*/
int
esl_opt_ProcessConfigfile(ESL_GETOPTS *g, char *filename, FILE *fp)
{
char *buf = NULL;
int n = 0;
char *s;
char *optname; /* tainted: from user's input file */
char *optarg; /* tainted: from user's input file */
char *comment;
int line;
int opti;
int status;
line = 0;
while ((status = esl_fgets(&buf, &n, fp)) != eslEOF)
{
if (status != eslOK) return status; /* esl_fgets() failed (EMEM) */
line++;
optname = NULL;
optarg = NULL;
/* First token is the option, e.g. "--foo"
*/
s = buf;
esl_strtok(&s, " \t\n", &optname);
if (optname == NULL) continue; /* blank line */
if (*optname == '#') continue; /* comment line */
if (*optname != '-')
ESL_FAIL(eslESYNTAX, g->errbuf,
"Parse failed at line %d of cfg file %.24s (saw %.24s, not an option)\n",
line, filename, optname);
/* Second token, if present, is the arg
*/
if (*s == '"') esl_strtok(&s, "\"", &optarg); /* quote-delimited arg */
else esl_strtok(&s, " \t\n", &optarg); /* space-delimited arg */
/* Anything else on the line had better be a comment
*/
esl_strtok(&s, " \t\n", &comment);
if (comment != NULL && *comment != '#')
ESL_FAIL(eslESYNTAX, g->errbuf,
"Parse failed at line %d of cfg file %.24s (saw %.24s, not a comment)\n",
line, filename, comment);
/* Now we've got an optname and an optional optarg;
* figure out what option this is.
*/
if (get_optidx_exactly(g, optname, &opti) != eslOK)
ESL_FAIL(eslESYNTAX, g->errbuf,
"%.24s is not a recognized option (config file %.24s, line %d)\n",
optname, filename, line);
/* Set that option.
* Pass TRUE to set_option's do_alloc flag, because our buffer
* is volatile memory that's going away soon - set_option needs
* to strdup the arg, not just point to it.
*/
status = set_option(g, opti, optarg,
eslARG_SETBY_CFGFILE+g->nfiles,
TRUE);
if (status != eslOK) return status;
}
if (buf != NULL) free(buf);
g->nfiles++;
return eslOK;
}
/* Function: esl_opt_ProcessEnvironment()
* Synopsis: Parses options in the environment.
*
* Purpose: For any option defined in <g> that can be modified
* by an environment variable, check the environment
* and set that option accordingly. The value provided
* by the environment is type and range checked.
* When an option is turned on that has other options
* toggle-tied to it, those options are turned off.
* An option's state may only be changed once by the
* environment (even indirectly thru toggle-tying);
* else an error is generated.
*
* Returns: <eslOK> on success, and <g> is loaded with all
* options specified in the environment.
*
* Returns <eslEINVAL> on user input problems,
* including type/range check failures, and
* sets <g->errbuf> to a useful error message.
*
* Throws: <eslEMEM> on allocation problem.
*/
int
esl_opt_ProcessEnvironment(ESL_GETOPTS *g)
{
int i;
char *optarg;
int status;
for (i = 0; i < g->nopts; i++)
if (g->opt[i].envvar != NULL &&
(optarg = getenv(g->opt[i].envvar)) != NULL)
{
status = set_option(g, i, optarg, eslARG_SETBY_ENV, FALSE);
if (status != eslOK) return status;
}
return eslOK;
}
/* Function: esl_opt_ProcessCmdline()
* Synopsis: Parses options from the command line.
*
* Purpose: Process a command line (<argc> and <argv>), parsing out
* and setting application options in <g>. Option arguments
* are type and range checked before they are set, if type
* and range information was set when <g> was created.
* When an option is set, if it has any other options
* "toggle-tied" to it, those options are also turned off.
*
* Any given option can only change state (on/off) once
* per command line; trying to set the same option more than
* once generates an error.
*
* On successful return, <g> contains settings of all
* command line options and their option arguments, for
* subsequent retrieval by <esl_opt_Get*()>
* functions. <g> also contains an <optind> state variable
* pointing to the next <argv[]> element that is not an
* option. <esl_opt_GetArg()> needs this to know
* where the options end and command line arguments begin
* in <argv[0]>.
*
* The parser starts with <argv[1]> and reads <argv[]> elements
* in order until it reaches an element that is not an option;
* at this point, all subsequent <argv[]> elements are
* interpreted as arguments to the application.
*
* Any <argv[]> element encountered in the command line that
* starts with <- > is an option, except <- > or <-- > by
* themselves. <- > by itself is interpreted as a command
* line argument (usually meaning ``read from stdin instead
* of a filename''). <-- > by itself is interpreted as
* ``end of options''; all subsequent <argv[]> elements are
* interpreted as command-line arguments even if they
* begin with <- >.
*
* Returns: <eslOK> on success. <g> is loaded with
* all option settings specified on the cmdline.
* Returns <eslEINVAL> on any cmdline parsing problem,
* including option argument type/range check failures,
* and sets <g->errbuf> to a useful error message for
* the user.
*
* Throws: <eslEMEM> on allocation problem.
*/
int
esl_opt_ProcessCmdline(ESL_GETOPTS *g, int argc, char **argv)
{
int opti;
char *optarg;
int status, setstatus;
g->argc = argc;
g->argv = argv;
g->optind = 1; /* start at argv[1] */
g->optstring = NULL; /* not in a -abc optstring yet */
/* Walk through each option in the command line using esl_getopts(),
* which advances g->optind as the index of the next argv element we need
* to look at.
*/
while ((status = esl_getopts(g, &opti, &optarg)) == eslOK)
{
setstatus = set_option(g, opti, optarg, eslARG_SETBY_CMDLINE, FALSE);
if (setstatus != eslOK) return setstatus;
}
if (status == eslEOD) return eslOK;
else return status;
}
/* Function: esl_opt_ProcessSpoof()
* Synopsis: Parses a string as if it were a command line.
*
* Purpose: Process the string <cmdline> as if it were a
* complete command line.
*
* Essentially the same as <esl_opt_ProcessCmdline()>
* except that whitespace-delimited tokens first need to be
* identified in the <cmdline> first, then passed as
* <argc>,<argv> to <esl_opt_ProcessCmdline()>.
*
* Returns: <eslOK> on success, and <g> is loaded with the
* application configuration.
*
* Returns <eslEINVAL> on any parsing problem, and sets
* <g->errbuf> to an informative error message.
*
* Throws: <eslEMEM> on allocation failure.
*
* Xref: J4/24.
*/
int
esl_opt_ProcessSpoof(ESL_GETOPTS *g, const char *cmdline)
{
int argc = 0;
char *s = NULL;
void *p;
char *tok;
int status;
if (g->spoof != NULL || g->spoof_argv != NULL)
ESL_XFAIL(eslEINVAL, g->errbuf, "cannot process more than one spoofed command line");
if ((status = esl_strdup(cmdline, -1, &(g->spoof))) != eslOK) goto ERROR;
s = g->spoof;
/* old version
while (esl_strtok(&s, " \t\n", &tok) == eslOK)
{
argc++;
ESL_RALLOC(g->spoof_argv, p, sizeof(char *) * argc);
g->spoof_argv[argc-1] = tok;
}
*/
while(*s != '\0'){
int status2;
if(*s == '\"'){ //token begins with a quote, must end with one or EOL
status2 = esl_strtok(&s, "\"", &tok);
}
else{
status2 = esl_strtok(&s, " \t\n", &tok);
}
if(status2 != eslOK){
break; // done parsing tokens
}
argc++;
ESL_RALLOC(g->spoof_argv, p, sizeof(char *) * argc);
g->spoof_argv[argc-1] = tok;
}
status = esl_opt_ProcessCmdline(g, argc, g->spoof_argv);
return status;
ERROR:
if (g->spoof != NULL) { free(g->spoof); g->spoof = NULL; }
if (g->spoof_argv != NULL) { free(g->spoof_argv); g->spoof_argv = NULL; }
return status;
}
/* Function: esl_opt_VerifyConfig()
* Synopsis: Validates configuration after options are set.
*
* Purpose: Given a <g> that we think is fully configured now --
* from config file(s), environment, and command line --
* verify that the configuration is self-consistent:
* for every option that is set, make sure that any
* required options are also set, and that no
* incompatible options are set. ``Set'' means
* the configured value is non-default and non-NULL (including booleans),
* and ``not set'' means the value is default or NULL. (That is,
* we don't go solely by <setby>, which refers to who
* determined the state of an option, even if
* it is turned off.)
*
* Returns: <eslOK> on success.
* <eslESYNTAX> if a required option is not set, or
* if an incompatible option is set; in this case, sets
* <g->errbuf> to contain a useful error message for
* the user.
*
* Throws: <eslEINVAL> if something's wrong with the <ESL_OPTIONS>
* structure itself -- a coding error in the application.
*/
int
esl_opt_VerifyConfig(ESL_GETOPTS *g)
{
int i,reqi,incompati;
char *s;
int status;
/* For all options that are set (not in default configuration,
* and turned on with non-NULL vals),
* verify that all their required_opts are set.
*/
for (i = 0; i < g->nopts; i++)
{
if (g->setby[i] != eslARG_SETBY_DEFAULT && g->val[i] != NULL)
{
s = g->opt[i].required_opts;
while ((status = process_optlist(g, &s, &reqi)) != eslEOD)
{
if (status != eslOK) ESL_EXCEPTION(eslEINVAL, "something's wrong with format of optlist: %s\n", s);
if (g->val[reqi] == NULL)
{
if (g->setby[i] >= eslARG_SETBY_CFGFILE)
ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s (set by cfg file %d) requires (or has no effect without) option(s) %.24s",
g->opt[i].name, g->setby[i]-2, g->opt[i].required_opts);
else if (g->setby[i] == eslARG_SETBY_ENV)
ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s (set by env var %s) requires (or has no effect without) option(s) %.24s",
g->opt[i].name, g->opt[i].envvar, g->opt[i].required_opts);
else
ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s requires (or has no effect without) option(s) %.24s",
g->opt[i].name, g->opt[i].required_opts);
}
}
}
}
/* For all options that are set (turned on with non-NULL vals),
* verify that no incompatible options are set to non-default
* values (notice the setby[incompati] check)
*/
for (i = 0; i < g->nopts; i++)
{
if (g->setby[i] != eslARG_SETBY_DEFAULT && g->val[i] != NULL)
{
s = g->opt[i].incompat_opts;
while ((status = process_optlist(g, &s, &incompati)) != eslEOD)
{
if (status != eslOK) ESL_EXCEPTION(eslEINVAL, "something's wrong with format of optlist: %s\n", s);
if (incompati != i && (g->setby[incompati] != eslARG_SETBY_DEFAULT && g->val[incompati] != NULL))
{
if (g->setby[i] >= eslARG_SETBY_CFGFILE)
ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s (set by cfg file %d) is incompatible with option(s) %.24s",
g->opt[i].name, g->setby[i]-2, g->opt[i].incompat_opts);
else if (g->setby[i] == eslARG_SETBY_ENV)
ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s (set by env var %s) is incompatible with option(s) %.24s",
g->opt[i].name, g->opt[i].envvar, g->opt[i].incompat_opts);
else
ESL_FAIL(eslESYNTAX, g->errbuf, "Option %.24s is incompatible with option(s) %.24s",
g->opt[i].name, g->opt[i].incompat_opts);
}
}
}
}
return eslOK;
}
/* Function: esl_opt_ArgNumber()
* Synopsis: Returns number of command line arguments.
*
* Purpose: Returns the number of command line arguments.
*
* Caller must have already called
* <esl_opt_ProcessCmdline()>, in order for all the options
* to be parsed first. Everything left on the command line
* is taken to be an argument.
*/
int
esl_opt_ArgNumber(const ESL_GETOPTS *g)
{
return ((g)->argc - (g)->optind);
}
/* Function: esl_opt_SpoofCmdline()
* Synopsis: Create faux command line from current option configuration.
*
* Purpose: Given the current configuration state of the application
* <g>, create a command line that would recreate the same
* state by itself (without any environment or config file
* settings), and return it in <*ret_cmdline>.
*
* Returns: <eslOK> on success. The <*ret_cmdline> is allocated here,
* and caller is responsible for freeing it.
*
* Throws: <eslEMEM> on allocation error, and <*ret_cmdline> is <NULL>.
*
* Xref: J4/24
*/
int
esl_opt_SpoofCmdline(const ESL_GETOPTS *g, char **ret_cmdline)
{
char *cmdline = NULL;
char *p = NULL;
int ntot = 0;
int n;
int i, j;
int status;
/* Application name/path */
ntot = strlen(g->argv[0]) + 1; // +1 for the space
ESL_ALLOC(cmdline, sizeof(char) * (ntot+1)); // +1 for the \0
snprintf(cmdline, ntot+1, "%s ", g->argv[0]);
/* Options */
for (i = 0; i < g->nopts; i++)
if (g->setby[i] != eslARG_SETBY_DEFAULT)
{
if (g->opt[i].type == eslARG_NONE) n = strlen(g->opt[i].name) + 1;
else n = (strlen(g->opt[i].name) + strlen(g->val[i])) + 2;
ESL_RALLOC(cmdline, p, sizeof(char) * (ntot + n + 1));
if (g->opt[i].type == eslARG_NONE) snprintf(cmdline + ntot, n+1, "%s ", g->opt[i].name);
else snprintf(cmdline + ntot, n+1, "%s %s ", g->opt[i].name, g->val[i]);
ntot += n;
}
/* Arguments */
for (j = g->optind; j < g->argc; j++)
{
n = strlen(g->argv[j]) + 1;
ESL_RALLOC(cmdline, p, sizeof(char) * (ntot + n + 1));
snprintf(cmdline + ntot, n+1, "%s ", g->argv[j]);
ntot += n;
}
/* Terminate */
cmdline[ntot] = '\0';
*ret_cmdline = cmdline;
return eslOK;
ERROR:
if (cmdline != NULL) free(cmdline);
*ret_cmdline = NULL;
return status;
}
/*****************************************************************
*# 3. Retrieving option settings and command line args
*****************************************************************/
/* Function: esl_opt_IsDefault()
* Synopsis: Returns <TRUE> if option remained at default setting.
*
* Purpose: Returns <TRUE> if option <optname> is in its
* default state; returns <FALSE> if <optname> was
* changed on the command line, in the environment, or in
* a configuration file.
*/
int
esl_opt_IsDefault(const ESL_GETOPTS *g, char *optname)
{
int opti;
if (get_optidx_exactly(g, optname, &opti) != eslOK) esl_fatal("no such option %s\n", optname);
if (g->setby[opti] == eslARG_SETBY_DEFAULT) return TRUE;
if (g->val[opti] == NULL && g->opt[opti].defval == NULL) return TRUE;
if (esl_strcmp(g->opt[opti].defval, g->val[opti]) == 0) return TRUE; /* option may have been set but restored to original default value */
return FALSE;
}
/* Function: esl_opt_IsOn()
* Synopsis: Returns <TRUE> if option is set to a non-<NULL> value.
*
* Purpose: Returns <TRUE> if option is on (set to a non-<NULL>
* value).
*
* This is most useful when using integer-, real-, char-,
* or string-valued options also as boolean switches, where
* they can either be OFF, or they can be turned ON by
* having a value. Caller can test <esl_opt_IsOn()> to see
* if the option's active at all, then use
* <esl_opt_GetString()> or whatever to extract the option
* value.
*
* For a boolean option, the result is identical to
* <esl_opt_GetBoolean()>.
*
* Xref: J4/83.
*/
int
esl_opt_IsOn(const ESL_GETOPTS *g, char *optname)
{
int opti;
if (get_optidx_exactly(g, optname, &opti) != eslOK) esl_fatal("no such option %s\n", optname);
if (g->val[opti] == NULL) return FALSE;
else return TRUE;
}
/* Function: esl_opt_IsUsed()
* Synopsis: Returns <TRUE> if option is on, and this is not the default.
*
* Purpose: Returns <TRUE> if option <optname> is in use: it has been
* set to a non-default value, and that value correspond to
* the option being "on" (a non-<NULL> value).
*
* This is used in printing application headers, where
* we want to report all the options that are in effect that
* weren't already on by default.
*
* Xref: J4/83
*/
int
esl_opt_IsUsed(const ESL_GETOPTS *g, char *optname)
{
int opti;
if (get_optidx_exactly(g, optname, &opti) != eslOK) esl_fatal("no such option %s\n", optname);
if (esl_opt_IsDefault(g, optname)) return FALSE;
if (g->val[opti] == NULL) return FALSE;
return TRUE;
}
/* Function: esl_opt_GetSetter()
* Synopsis: Returns code for who set this option.
*
* Purpose: For a processed options object <g>, return the code
* for who set option <optname>. This code is <eslARG_SETBY_DEFAULT>,
* <eslARG_SETBY_CMDLINE>, <eslARG_SETBY_ENV>, or it
* is $\geq$ <eslARG_SETBY_CFGFILE>. If the option
* was configured by a config file, the file number (the order
* of <esl_opt_ProcessConfigFile()> calls) is encoded in codes
* $\geq <eslARG_SETBY_CFGFILE>$ as
* file number $=$ <code> - <eslARG_SETBY_CFGFILE> + 1.
*/
int
esl_opt_GetSetter(const ESL_GETOPTS *g, char *optname)
{
int opti;
if (get_optidx_exactly(g, optname, &opti) != eslOK) esl_fatal("no such option %s\n", optname);
return g->setby[opti];
}
/* Function: esl_opt_GetBoolean()
* Synopsis: Retrieve <TRUE>/<FALSE> for a boolean option.
*
* Purpose: Retrieves the configured TRUE/FALSE value for option <optname>
* from <g>.
*/
int
esl_opt_GetBoolean(const ESL_GETOPTS *g, char *optname)
{
int opti;
if (get_optidx_exactly(g, optname, &opti) == eslENOTFOUND)
esl_fatal("no such option %s\n", optname);
if (g->opt[opti].type != eslARG_NONE)
esl_fatal("option %s is not a boolean; code called _GetBoolean", optname);
if (g->val[opti] == NULL) return FALSE;
else return TRUE;
}
/* Function: esl_opt_GetInteger()
* Synopsis: Retrieve value of an integer option.
*
* Purpose: Retrieves the configured value for option <optname>
* from <g>.
*/
int
esl_opt_GetInteger(const ESL_GETOPTS *g, char *optname)
{
int opti;
if (get_optidx_exactly(g, optname, &opti) == eslENOTFOUND)
esl_fatal("no such option %s\n", optname);