]> git.draconx.ca Git - dxcommon.git/blobdiff - t/helpopt.c
Add common option formatting routines.
[dxcommon.git] / t / helpopt.c
diff --git a/t/helpopt.c b/t/helpopt.c
new file mode 100644 (file)
index 0000000..303e13a
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * Read some text from standard input and format it with help_print_desc,
+ * for testing.  Each pair of program arguments is converted to an int and
+ * passed as the two integer arguments to help_print_desc.
+ */
+#include "help.h"
+#include "tap.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <errno.h>
+
+#include <getopt.h>
+
+static char buf[1000];
+
+int arg_to_int(const char *s)
+{
+       char *end;
+       long val;
+
+       errno = 0;
+       val = strtol(s, &end, 0);
+       if (*end != 0)
+               tap_bail_out("%s: numeric argument expected", s);
+       else if (val < INT_MIN || val > INT_MAX || errno == ERANGE)
+               tap_bail_out("%s: %s", s, strerror(ERANGE));
+       else if (errno)
+               tap_bail_out("%s: %s", s, strerror(errno));
+
+       return val;
+}
+
+void print_opt(struct option *opt, const char *argname, int w)
+{
+       w = help_print_optstring(opt, argname, w);
+       printf("\t%d\n", w);
+}
+
+int main(int argc, char **argv)
+{
+       struct option opt = {0};
+       const char *argname = 0;
+       int i, w = 20;
+
+       for (i = 1; i < argc; i++) {
+               if (argv[i][0] == '-' && argv[i][1] == '-') {
+                       if (opt.name)
+                               print_opt(&opt, argname, w);
+                       opt.val = UCHAR_MAX+1;
+                       opt.has_arg = 0;
+                       opt.name = argv[i]+2;
+               } else if (argv[i][0] == '-') {
+                       opt.val = argv[i][1];
+               } else if (argv[i][0] == '[') {
+                       char *c;
+
+                       argname = argv[i]+1;
+                       if ((c = strchr(argname, ']')))
+                               *c = 0;
+                       opt.has_arg = 2;
+               } else if (argv[i][0] >= '0' && argv[i][0] <= '9') {
+                       w = arg_to_int(argv[i]);
+               } else {
+                       argname = argv[i];
+                       opt.has_arg = 1;
+               }
+       }
+
+       if (opt.name)
+               print_opt(&opt, argname, w);
+
+       return 0;
+}