-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclp.c
1592 lines (1306 loc) · 42.6 KB
/
clp.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
/*
* Copyright (c) 2015-2016,2021 Greg Becker. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: clp.c 386 2016-01-27 13:25:47Z greg $
*/
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <stdarg.h>
#include <inttypes.h>
#include <float.h>
#include <assert.h>
#include <ctype.h>
#include <getopt.h>
#include <math.h>
#include <sys/file.h>
#include <sys/param.h>
#include "clp.h"
#ifndef clp_suftab_default
#define clp_suftab_default clp_suftab_combo
#endif
/* International System of Units suffixes...
*/
struct clp_suftab clp_suftab_si = {
.list = "kMGTPEZY",
.mult = { 1e3, 1e6, 1e9, 1e12, 1e15, 1e18, 1e21, 1e24 }
};
/* International Electrotechnical Commission suffixes...
*/
struct clp_suftab clp_suftab_iec = {
.list = "KMGTPEZY",
.mult = { 0x1p10, 0x1p20, 0x1p30, 0x1p40, 0x1p50, 0x1p60, 0x1p70, 0x1p80 }
};
struct clp_suftab clp_suftab_combo = {
.list = "kmgtpezyKMGTPEZYbw",
.mult = {
0x1p10, 0x1p20, 0x1p30, 0x1p40, 0x1p50, 0x1p60, 0x1p70, 0x1p80,
1e3, 1e6, 1e9, 1e12, 1e15, 1e18, 1e21, 1e24,
512, sizeof(int)
}
};
struct clp_suftab clp_suftab_none = {
.list = ""
};
struct clp_suftab clp_suftab_time = {
.list = "smhdwyc",
.mult = { 1, 60, 3600, 86400, 86400 * 7, 86400 * 365, 86400 * 365 * 100ul }
};
struct clp_posparam clp_posparam_none[] = {
{ .name = NULL }
};
#ifdef CLP_DEBUG
static int clp_debug;
/* Called via the dprint() macro..
*/
static void
clp_dprint_impl(const char *file, int line, const char *func, const char *fmt, ...)
{
va_list ap;
if (file && func)
fprintf(stdout, " +%-4d %-6s %-12s ", line, file, func);
va_start(ap, fmt);
vfprintf(stdout, fmt, ap);
va_end(ap);
}
/* dprint() prints a debug message to stdout if (clp_debug >= lvl).
*/
#define clp_dprint(_lvl, ...) \
do { \
if (clp_debug >= (_lvl)) { \
clp_dprint_impl(__FILE__, __LINE__, __func__, __VA_ARGS__); \
} \
} while (0)
#else
#define clp_dprint(_lvl, ...) do { } while (0)
#endif /* CLP_DEBUG */
/* Render an error message for emission at the end of clp_parsev().
*
* If on entry clp->errbuf[0] is a punctuation character (e.g., ",")
* then clp->errbuf will be saved and then appended to the string
* produced by the given format. If on entry clp->errbuf[0] is NUL
* and errno is set then strerror() will be appended to the string
* produced by the given format.
*/
void
clp_eprint(struct clp *clp, const char *fmt, ...)
{
char suffix[sizeof(clp->errbuf) - 8];
int xerrno = errno;
va_list ap;
size_t n;
if (clp->errbuf[0] && !ispunct(clp->errbuf[0]))
return;
strncpy(suffix, clp->errbuf, sizeof(suffix) - 1);
suffix[sizeof(suffix) - 1] = '\000';
va_start(ap, fmt);
n = vsnprintf(clp->errbuf, sizeof(clp->errbuf), fmt, ap);
va_end(ap);
if (n < sizeof(clp->errbuf)) {
snprintf(clp->errbuf + n, sizeof(clp->errbuf) - n, "%s%s",
xerrno && !suffix[0] ? ": " : "",
xerrno && !suffix[0] ? strerror(xerrno) : suffix);
}
errno = xerrno;
}
static bool
clp_optopt_valid(int c)
{
return isgraph(c) && !strchr(":?-", c);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
/* An option's conversion procedure is called each time the option is seen on
* the command line. The conversions for bool, string, open, fopen, and incr
* require special handling, while those for simple integer types (int, long,
* int64_t, ...) are handled by functions generated via CLP_CVT_TMPL().
*
* Note: These functions are not type safe, but are typically invoked by clp
* from a type-safe context.
*/
int
clp_cvt_bool(struct clp *clp, const char *optarg, int flags, void *parms, void *dst)
{
bool *result = dst;
*result = ! *result;
return 0;
}
int
clp_cvt_string(struct clp *clp, const char *optarg, int flags, void *parms, void *dst)
{
char **result = dst;
if (!result) {
errno = EINVAL;
return EX_DATAERR;
}
*result = strdup(optarg);
return *result ? 0 : EX_OSERR;
}
int
clp_cvt_open(struct clp *clp, const char *optarg, int flags, void *parms, void *dst)
{
int *result = dst;
if (!result) {
errno = EINVAL;
return EX_DATAERR;
}
*result = open(optarg, flags ? flags : O_RDONLY, 0644);
return (*result >= 0) ? 0 : EX_NOINPUT;
}
int
clp_cvt_fopen(struct clp *clp, const char *optarg, int flags, void *parms, void *dst)
{
const char *mode = parms ? parms : "r";
FILE **result = dst;
if (!result) {
errno = EINVAL;
return EX_DATAERR;
}
*result = fopen(optarg, mode);
return *result ? 0 : EX_NOINPUT;
}
int
clp_cvt_incr(struct clp *clp, const char *optarg, int flags, void *parms, void *dst)
{
int *result = dst;
if (!result) {
errno = EINVAL;
return EX_DATAERR;
}
*result += 1;
return 0;
}
/* The following macros will explode into a bunch of conversion functions.
* With any luck the unused functions will be eliminated by the linker.
*/
CLP_CVT_TMPL(char, char, CHAR_MIN, CHAR_MAX, clp_suftab_default);
CLP_CVT_TMPL(u_char, u_char, 0, UCHAR_MAX, clp_suftab_default);
CLP_CVT_TMPL(short, short, SHRT_MIN, SHRT_MAX, clp_suftab_default);
CLP_CVT_TMPL(u_short, u_short, 0, USHRT_MAX, clp_suftab_default);
CLP_CVT_TMPL(int, int, INT_MIN, INT_MAX, clp_suftab_default);
CLP_CVT_TMPL(u_int, u_int, 0, UINT_MAX, clp_suftab_default);
CLP_CVT_TMPL(long, long, LONG_MIN, LONG_MAX, clp_suftab_default);
CLP_CVT_TMPL(u_long, u_long, 0, ULONG_MAX, clp_suftab_default);
CLP_CVT_TMPL(float, float, -FLT_MAX, FLT_MAX, clp_suftab_default);
CLP_CVT_TMPL(double, double, -DBL_MAX, DBL_MAX, clp_suftab_default);
CLP_CVT_TMPL(int8_t, int8_t, INT8_MIN, INT8_MAX, clp_suftab_default);
CLP_CVT_TMPL(uint8_t, uint8_t, 0, UINT8_MAX, clp_suftab_default);
CLP_CVT_TMPL(int16_t, int16_t, INT16_MIN, INT16_MAX, clp_suftab_default);
CLP_CVT_TMPL(uint16_t, uint16_t, 0, UINT16_MAX, clp_suftab_default);
CLP_CVT_TMPL(int32_t, int32_t, INT32_MIN, INT32_MAX, clp_suftab_default);
CLP_CVT_TMPL(uint32_t, uint32_t, 0, UINT32_MAX, clp_suftab_default);
CLP_CVT_TMPL(int64_t, int64_t, INT64_MIN, INT64_MAX, clp_suftab_default);
CLP_CVT_TMPL(uint64_t, uint64_t, 0, UINT64_MAX, clp_suftab_default);
CLP_CVT_TMPL(intmax_t, intmax_t, INTMAX_MIN, INTMAX_MAX, clp_suftab_default);
CLP_CVT_TMPL(uintmax_t, uintmax_t, 0, UINTMAX_MAX, clp_suftab_default);
CLP_CVT_TMPL(intptr_t, intptr_t, INTPTR_MIN, INTPTR_MAX, clp_suftab_default);
CLP_CVT_TMPL(uintptr_t, uintptr_t, 0, UINTPTR_MAX, clp_suftab_default);
CLP_CVT_TMPL(size_t, size_t, 0, SIZE_MAX, clp_suftab_default);
CLP_CVT_TMPL(time_t, time_t, 0, LONG_MAX, clp_suftab_time);
CLP_GET_TMPL(bool, bool);
CLP_GET_TMPL(incr, int);
CLP_GET_TMPL(open, int);
CLP_GET_TMPL(fopen, FILE *);
CLP_GET_TMPL(string, char *);
int
clp_cvt_subcmd(struct clp *clp, const char *str, int flags, void *parms, void *dst)
{
struct clp_subcmd *subcmd = parms;
struct clp_subcmd *match = NULL;
if (subcmd) {
for (; subcmd->name; ++subcmd) {
char *pc = strstr(subcmd->name, str);
if (!pc || pc != subcmd->name)
continue;
if (match) {
clp_eprint(clp, "ambiguous subcommand '%s', use -h for help", str);
errno = EINVAL;
return EX_USAGE;
}
match = subcmd; // found a full or partial match
}
}
if (!match) {
clp_eprint(clp, "invalid subcommand '%s', use -h for help", str);
errno = EINVAL;
return EX_USAGE;
}
*(void **)dst = match;
return 0;
}
int
clp_action_subcmd(struct clp_posparam *param)
{
struct clp_subcmd *subcmd = *(void **)param->cvtdst;
int rc;
rc = clp_parsev(param->argc, param->argv, subcmd->optionv, subcmd->posparamv);
return rc ?: -1;
}
#pragma GCC diagnostic pop
struct clp_option *
clp_find(int c, struct clp_option *optionv)
{
if (optionv) {
struct clp_option *o;
for (o = optionv; o->optopt > 0; ++o) {
if (o->optopt == c)
return o;
}
}
return NULL;
}
struct clp_option *
clp_given(int c, struct clp_option *optionv, void *dst)
{
struct clp_option *o = clp_find(c, optionv);
if (o && o->given) {
if (dst && o->getfunc)
o->getfunc(o, dst);
return o;
}
return NULL;
}
/* Return true if the two specified options are mutually exclusive.
*/
int
clp_excludes2(const struct clp_option *l, const struct clp_option *r)
{
if (l && r && l != r) {
if (l->excludes) {
if (l->excludes[0] == '^') {
if (!strchr(l->excludes, r->optopt)) {
return true;
}
} else {
if (l->excludes[0] == '*' || strchr(l->excludes, r->optopt)) {
return true;
}
}
}
if (r->excludes) {
if (r->excludes[0] == '^') {
if (!strchr(r->excludes, l->optopt)) {
return true;
}
} else {
if (r->excludes[0] == '*' || strchr(r->excludes, l->optopt)) {
return true;
}
}
}
if (l->paramv && r->paramv && l->paramv != r->paramv) {
return true;
}
}
return false;
}
/* Return the opt letter of any option that is mutually exclusive
* with the specified option and which appeared on the command line
* at least the specified number of times.
*/
struct clp_option *
clp_excludes(struct clp_option *first, const struct clp_option *option, int given)
{
struct clp_option *o;
for (o = first; o->optopt > 0; ++o) {
if (o->given >= given && clp_excludes2(option, o)) {
return o;
}
}
return NULL;
}
/* Trim leading white space from given string. Returns NULL
* if resulting string is zero length. Typically, str is
* either NULL or a zero length string on entry.
*/
static const char *
clp_trim(const char *str)
{
while (str && isspace(str[0]))
++str;
return (str && !str[0] ? NULL : str);
}
/* Return the count of leading open brackets, and the given name copied
* to buf[] and stripped of brackets and leading/trailing white space.
*/
int
clp_unbracket(const char *name, char *buf, size_t bufsz)
{
char *bufbase = buf;
int obrackets = 0;
if (!name || !buf || bufsz < 1) {
abort();
}
// Count open brackets up to first non-space character.
while (isspace(*name) || *name == '[') {
obrackets += (*name == '[');
++name;
}
strncpy(buf, name, bufsz - 1);
buf[bufsz - 1] = '\000';
// Terminate buf at first bracket
while (*buf && *buf != ']' && *buf != '[')
++buf;
*buf = '\000';
// Eliminate trailing white space
while (buf-- > bufbase && isspace(*buf))
*buf = '\000';
return obrackets;
}
static struct clp_subcmd *
clp_subcmd(const struct clp_posparam *param)
{
struct clp_subcmd *subcmd = NULL;
if (param && param->cvtsubcmd)
subcmd = param->cvtparms;
return (subcmd && subcmd->name) ? subcmd : NULL;
}
/* Lexical string comparator for qsort (e.g., AaBbCcDd...)
*/
static int
clp_string_cmp(const void *lhs, const void *rhs)
{
const char *l = (const char *)lhs;
const char *r = (const char *)rhs;
int lc = tolower(*l);
int rc = tolower(*r);
if (lc == rc) {
return (isupper(*l) ? -1 : 1);
}
return (lc - rc);
}
/* Print just the usage line, i.e., lines of the general form
* "usage: progname [options] args..."
*/
void
clp_usage(struct clp *clp, const struct clp_option *limit)
{
struct clp_posparam *paramv = clp->paramv;
char excludes_buf[clp->optionc + 1];
char optarg_buf[clp->optionc * 16];
char opt_buf[clp->optionc + 1];
char *pc_optarg, *pc_opt, *pc;
struct clp_posparam *param;
struct clp_option *o;
char *pc_excludes;
FILE *fp = stdout;
if (limit) {
bool limit_excl_all = limit->excludes && strchr("*^", limit->excludes[0]);
if (!limit_excl_all && !limit->paramv) {
return;
}
if (limit->paramv) {
paramv = limit->paramv;
}
}
pc_excludes = excludes_buf;
pc_optarg = optarg_buf;
pc_opt = opt_buf;
/* Build three lists of option characters:
*
* 1) excludes_buf[] contains all the options that might exclude
* or be excluded by another option that share the same parameter vector.
*
* 2) optarg_buf[] contains all the options not in (1) that require
* an argument.
*
* 3) opt_buf[] contains all the rest not covered by (1) or (2).
*
* Note: if 'limit' is not NULL, then only options that share
* the same paramv or have a NULL paramv may appear in one of
* the three lists.
*/
for (o = clp->optionv; o->optopt > 0; ++o) {
if (!clp_optopt_valid(o->optopt))
continue;
o->help = clp_trim(o->help);
if (limit) {
if (clp_excludes2(limit, o)) {
continue;
}
} else if (o->paramv) {
continue;
}
if (o != limit && o->help) {
if (o->excludes) {
*pc_excludes++ = o->optopt;
} else {
struct clp_option *x = clp_excludes(clp->optionv, o, 0);
if (x && x->paramv == o->paramv) {
*pc_excludes++ = o->optopt;
} else if (o->argname) {
*pc_optarg++ = o->optopt;
} else {
*pc_opt++ = o->optopt;
}
}
}
}
*pc_excludes = '\000';
*pc_optarg = '\000';
*pc_opt = '\000';
qsort(opt_buf, strlen(opt_buf), 1, clp_string_cmp);
qsort(optarg_buf, strlen(optarg_buf), 1, clp_string_cmp);
qsort(excludes_buf, strlen(excludes_buf), 1, clp_string_cmp);
if (limit)
clp_dprint(1, " limit -%c:\n", limit->optopt);
clp_dprint(1, " has excludes: %s\n", excludes_buf);
clp_dprint(1, " has optarg: %s\n", optarg_buf);
clp_dprint(1, " bool opts: %s\n", opt_buf);
/* Now print out the usage line in the form of:
*
* usage: basename [mandatory-opt] [bool-opts] [opts-with-args] [excl-opts] [posparams...]
*/
/* [mandatory-opt]
*/
fprintf(fp, "usage: %s", clp->basename);
if (limit) {
fprintf(fp, " -%c", limit->optopt);
}
/* [bool-opts]
*/
if (opt_buf[0]) {
fprintf(fp, " [-%s]", opt_buf);
}
/* [opts-with-args]
*/
for (pc = optarg_buf; *pc; ++pc) {
o = clp_find(*pc, clp->optionv);
if (o) {
fprintf(fp, " [-%c %s]", o->optopt, o->argname);
}
}
/* Generate the mutually exclusive option usage message...
* [excl-args]
*/
if (excludes_buf[0]) {
char *listv[clp->optionc + 1];
int listc = 0;
char *cur;
int i;
/* Build a vector of strings where each string contains
* mutually exclusive options.
*/
for (cur = excludes_buf; *cur; ++cur) {
struct clp_option *l = clp_find(*cur, clp->optionv);
char buf[1024], *pc_buf;
pc_buf = buf;
for (pc = excludes_buf; *pc; ++pc) {
if (cur == pc) {
*pc_buf++ = *pc;
} else {
struct clp_option *r = clp_find(*pc, clp->optionv);
if (clp_excludes2(l, r)) {
*pc_buf++ = *pc;
}
}
}
*pc_buf = '\000';
listv[listc++] = strdup(buf);
}
/* Eliminate duplicate strings.
*/
for (i = 0; i < listc; ++i) {
int j;
for (j = i + 1; j < listc; ++j) {
if (listv[i] && listv[j]) {
if (0 == strcmp(listv[i], listv[j])) {
free(listv[j]);
listv[j] = NULL;
}
}
}
}
/* Ensure that all options within a list are mutually exclusive.
*/
for (i = 0; i < listc; ++i) {
if (listv[i]) {
for (pc = listv[i]; *pc; ++pc) {
struct clp_option *l = clp_find(*pc, clp->optionv);
char *pc2;
for (pc2 = listv[i]; *pc2; ++pc2) {
if (pc2 != pc) {
struct clp_option *r = clp_find(*pc2, clp->optionv);
if (!clp_excludes2(l, r)) {
free(listv[i]);
listv[i] = NULL;
goto next;
}
}
}
}
}
next:
continue;
}
/* Now, print out the remaining strings of mutually exclusive options.
*/
for (i = 0; i < listc; ++i) {
if (listv[i]) {
const char *bar = " [";
for (pc = listv[i]; *pc; ++pc) {
o = clp_find(*pc, clp->optionv);
if (o->argname) {
fprintf(fp, "%s-%c %s", bar, *pc, o->argname);
} else {
fprintf(fp, "%s-%c", bar, *pc);
}
bar = " | ";
}
fprintf(fp, "]");
}
}
}
/* Finally, print out all the positional parameters.
* [posparams...]
*/
if (paramv) {
int noptional = 0;
for (param = paramv; param->name; ++param) {
char namebuf[128];
int isopt;
isopt = clp_unbracket(param->name, namebuf, sizeof(namebuf));
if (isopt) {
++noptional;
}
fprintf(fp, "%s%s", isopt ? " [" : " ", namebuf);
if (param[1].name) {
isopt = clp_unbracket(param[1].name, namebuf, sizeof(namebuf));
}
/* If we're at the end of the list or the next parameter
* is not optional then print all the closing brackets.
*/
if (!param[1].name || !isopt) {
for (; noptional > 0; --noptional) {
fputc(']', fp);
}
}
}
}
fprintf(fp, "%s\n", paramv ? "" : " [args...]");
}
int
clp_version(struct clp_option *option)
{
printf("%s\n", (char *)option->cvtdst);
return 0;
}
/* Lexical option comparator for qsort (e.g., AaBbCcDd...)
*/
static int
clp_help_cmp(const void *lhs, const void *rhs)
{
struct clp_option const *l = *(struct clp_option * const *)lhs;
struct clp_option const *r = *(struct clp_option * const *)rhs;
int lc = tolower(l->optopt);
int rc = tolower(r->optopt);
if (lc == rc) {
return (isupper(l->optopt) ? -1 : 1);
}
return (lc - rc);
}
/* Print the entire help message, for example:
*
* usage: prog [-v] [-i intarg] src... dst
* usage: prog -h
* usage: prog -V
* -h print this help list
* -i intarg specify an integer argument
* -V print version
* -v increase verbosity
* src... specify one or more source files
* dst specify destination directory
*/
int
clp_help(struct clp_option *opthelp)
{
struct clp_posparam *paramv, *param;
struct clp_option *option;
int subcmd_width, width;
int longhelp, optionc;
struct clp *clp;
FILE *fp;
/* opthelp is the option that triggered clp into calling clp_help().
* Ususally -h, but the user could have changed it...
*/
if (!opthelp) {
return 0;
}
clp = opthelp->clp;
/* Create an array of pointers to options and sort it.
*/
struct clp_option *optionv[clp->optionc];
int i;
for (i = optionc = 0; i < clp->optionc; ++i) {
struct clp_option *o = clp->optionv + i;
if (clp_optopt_valid(o->optopt))
optionv[optionc++] = o;
}
qsort(optionv, optionc, sizeof(optionv[0]), clp_help_cmp);
/* Print the default usage line.
*/
fp = opthelp->priv ? opthelp->priv : stdout;
clp_usage(clp, NULL);
/* Print usage lines for each option that has positional parameters
* different than the default usage.
* Also, determine the width of the longest combination of option
* argument and long option names.
*/
longhelp = (opthelp->longidx >= 0);
width = 0;
for (i = 0; i < optionc; ++i) {
int len = 0;
option = optionv[i];
if (!option->help) {
continue;
}
clp_usage(clp, option);
if (option->argname) {
len += strlen(option->argname) + 1;
}
if (longhelp && option->longopt) {
len += strlen(option->longopt) + 4;
}
if (len > width) {
width = len;
}
}
/* Print a line of help for each option.
*/
for (i = 0; i < optionc; ++i) {
char buf[width + 8];
option = optionv[i];
if (!option->help)
continue;
buf[0] = '\000';
if (longhelp && option->longopt) {
strcat(buf, ", --");
strcat(buf, option->longopt);
}
if (option->argname) {
strcat(buf, " ");
strcat(buf, option->argname);
}
fprintf(fp, "-%c%-*s %s\n", option->optopt, width, buf, option->help);
}
/* Determine the width of the longest positional parameter name.
*/
subcmd_width = 0;
width = 0;
for (paramv = clp->params; paramv; paramv = paramv->next) {
for (param = paramv; param->name; ++param) {
struct clp_subcmd *subcmd = clp_subcmd(param);
char namebuf[width + 128];
int namelen;
for (; subcmd && subcmd->name; ++subcmd) {
subcmd->help = clp_trim(subcmd->help);
if (subcmd->help) {
namelen = strlen(namebuf);
if (namelen > subcmd_width) {
subcmd_width = namelen;
}
}
}
param->help = clp_trim(param->help);
if (!param->help)
continue;
clp_unbracket(param->name, namebuf, sizeof(namebuf));
namelen = strlen(namebuf);
if (namelen > width) {
width = namelen;
}
}
}
if (!clp->paramv)
fprintf(fp, "%-*s %s\n", width, "args...", "zero or more positional arguments");
/* Print a line of help for each positional paramter.
*/
for (paramv = clp->params; paramv; paramv = paramv->next) {
for (param = paramv; param->name; ++param) {
struct clp_subcmd *subcmd;
char namebuf[width + 1];
char *comma = "";
clp_unbracket(param->name, namebuf, sizeof(namebuf));
param->help = clp_trim(param->help);
subcmd = clp_subcmd(param);
if (!subcmd) {
if (param->help)
fprintf(fp, "%-*s %s\n", width, namebuf, param->help);
continue;
}
/* Print subcommand help. If caller didn't provide a help
* string for the subcommand posparam then we build one
* from the list of subcommands.
*/
if (param->help) {
fprintf(fp, "%s %s\n", namebuf, param->help);
} else {
fprintf(fp, "%s one of {", namebuf);
for (subcmd = param->cvtparms; subcmd->name; ++subcmd) {
subcmd->help = clp_trim(subcmd->help);
if (subcmd->help) {
fprintf(fp, "%s%s", comma, subcmd->name);
comma = ", ";
}
}
fprintf(fp, "}\n");
}
for (subcmd = param->cvtparms; subcmd->name; ++subcmd) {
if (subcmd->help)
fprintf(fp, " %-*s %s\n", subcmd_width, subcmd->name, subcmd->help);
}
}
}
return 0;
}
/* Determine the minimum and maximum number of arguments that the
* given posparam vector could consume.
*/
void
clp_posparam_minmax(struct clp_posparam *paramv, int *posminp, int *posmaxp)
{
struct clp_posparam *param;
if (!paramv || !posminp || !posmaxp) {
abort();
}
*posminp = 0;
*posmaxp = 0;
for (param = paramv; param->name; ++param) {
struct clp_subcmd *subcmd = clp_subcmd(param);
char namebuf[128];
int isoptional;
int len;
isoptional = clp_unbracket(param->name, namebuf, sizeof(namebuf));
param->posmin = isoptional ? 0 : 1;
len = strlen(namebuf);
if (len >= 3 && 0 == strncmp(namebuf + len - 3, "...", 3)) {
param->posmax = 1024;
} else {
param->posmax = subcmd ? 1024 : 1;
}
*posminp += param->posmin;
*posmaxp += param->posmax;
if (subcmd)
break;
}
}
static int