]> git.draconx.ca Git - dxcommon.git/blob - t/helpopt.c
Add common option formatting routines.
[dxcommon.git] / t / helpopt.c
1 /*
2  * Read some text from standard input and format it with help_print_desc,
3  * for testing.  Each pair of program arguments is converted to an int and
4  * passed as the two integer arguments to help_print_desc.
5  */
6 #include "help.h"
7 #include "tap.h"
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <limits.h>
13 #include <errno.h>
14
15 #include <getopt.h>
16
17 static char buf[1000];
18
19 int arg_to_int(const char *s)
20 {
21         char *end;
22         long val;
23
24         errno = 0;
25         val = strtol(s, &end, 0);
26         if (*end != 0)
27                 tap_bail_out("%s: numeric argument expected", s);
28         else if (val < INT_MIN || val > INT_MAX || errno == ERANGE)
29                 tap_bail_out("%s: %s", s, strerror(ERANGE));
30         else if (errno)
31                 tap_bail_out("%s: %s", s, strerror(errno));
32
33         return val;
34 }
35
36 void print_opt(struct option *opt, const char *argname, int w)
37 {
38         w = help_print_optstring(opt, argname, w);
39         printf("\t%d\n", w);
40 }
41
42 int main(int argc, char **argv)
43 {
44         struct option opt = {0};
45         const char *argname = 0;
46         int i, w = 20;
47
48         for (i = 1; i < argc; i++) {
49                 if (argv[i][0] == '-' && argv[i][1] == '-') {
50                         if (opt.name)
51                                 print_opt(&opt, argname, w);
52                         opt.val = UCHAR_MAX+1;
53                         opt.has_arg = 0;
54                         opt.name = argv[i]+2;
55                 } else if (argv[i][0] == '-') {
56                         opt.val = argv[i][1];
57                 } else if (argv[i][0] == '[') {
58                         char *c;
59
60                         argname = argv[i]+1;
61                         if ((c = strchr(argname, ']')))
62                                 *c = 0;
63                         opt.has_arg = 2;
64                 } else if (argv[i][0] >= '0' && argv[i][0] <= '9') {
65                         w = arg_to_int(argv[i]);
66                 } else {
67                         argname = argv[i];
68                         opt.has_arg = 1;
69                 }
70         }
71
72         if (opt.name)
73                 print_opt(&opt, argname, w);
74
75         return 0;
76 }