]> git.ozlabs.org Git - ccan/blob - ccan/opt/test/utils.c
899056ee84f0043f8b28fde8deaeeb5d0c775261
[ccan] / ccan / opt / test / utils.c
1 #define _GNU_SOURCE
2 #include <ccan/tap/tap.h>
3 #include <stdarg.h>
4 #include <stdlib.h>
5 #include <ccan/opt/opt.h>
6 #include <getopt.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include "utils.h"
10
11 unsigned int test_cb_called;
12 char *test_noarg(void *arg)
13 {
14         test_cb_called++;
15         return NULL;
16 }
17
18 char *test_arg(const char *optarg, void *arg)
19 {
20         test_cb_called++;
21         ok1(strcmp(optarg, arg) == 0);
22         return NULL;
23 }
24
25 char *err_output = NULL;
26
27 static void save_err_output(const char *fmt, ...)
28 {
29         va_list ap;
30         char *p;
31
32         va_start(ap, fmt);
33         vasprintf(&p, fmt, ap);
34         va_end(ap);
35
36         if (err_output) {
37                 err_output = realloc(err_output,
38                                      strlen(err_output) + strlen(p) + 1);
39                 strcat(err_output, p);
40                 free(p);
41         } else
42                 err_output = p;
43 }       
44
45 /* FIXME: This leaks, BTW. */
46 bool parse_args(int *argc, char ***argv, ...)
47 {
48         char **a;
49         va_list ap;
50
51         va_start(ap, argv);
52         *argc = 1;
53         a = malloc(sizeof(*a) * (*argc + 1));
54         a[0] = (*argv)[0];
55         while ((a[*argc] = va_arg(ap, char *)) != NULL) {
56                 (*argc)++;
57                 a = realloc(a, sizeof(*a) * (*argc + 1));
58         }
59         *argv = a;
60         /* Re-set before parsing. */
61         optind = 0;
62
63         return opt_parse(argc, *argv, save_err_output);
64 }
65
66 struct opt_table short_table[] = {
67         /* Short opts, different args. */
68         { OPT_WITHOUT_ARG(NULL, 'a', test_noarg, "a"), "Description of a" },
69         { OPT_WITH_ARG(NULL, 'b', test_arg, "b"), "Description of b" },
70         OPT_ENDTABLE
71 };
72
73 struct opt_table long_table[] = {
74         /* Long opts, different args. */
75         { OPT_WITHOUT_ARG("ddd", 0, test_noarg, "ddd"), "Description of ddd" },
76         { OPT_WITH_ARG("eee", 0, test_arg, "eee"), "Description of eee" },
77         OPT_ENDTABLE
78 };
79
80 struct opt_table long_and_short_table[] = {
81         /* Short and long, different args. */
82         { OPT_WITHOUT_ARG("ggg", 'g', test_noarg, "ggg"),
83           "Description of ggg" },
84         { OPT_WITH_ARG("hhh", 'h', test_arg, "hhh"), "Description of hhh"},
85         OPT_ENDTABLE
86 };
87
88 /* Sub-table test. */
89 struct opt_table subtables[] = {
90         /* Short and long, no description */
91         { OPT_WITH_ARG("jjj", 'j', test_arg, "jjj") },
92         OPT_SUBTABLE(short_table, NULL),
93         OPT_SUBTABLE(long_table, "long table options"),
94         OPT_SUBTABLE(long_and_short_table, opt_table_hidden),
95         OPT_ENDTABLE
96 };