/* * Copyright © 2021-2022 Nick Bowler * * Test helper application to verify help_print_optstring operation. * * Command-line arguments are collected to create the options to be formatted. * There are six basic forms: * * --long-option-only * --long-option-with-argument arg * --long-option-with-optional-argument [arg] * --short-option -s arg * --short-option-with-argument -s arg * --short-option-with-optional-argument -s [arg] * * Adding an argument of '&' to any form will set the "flag" member of * the option structure to a non-null value. * * Based on these arguments, a suitable 'struct option' is constructed and * passed to help_print_optstring. Then a tab character is printed, followed * by the return value of help_print_optsring (via printf %d). Then further * arguments are considered to output more options. * * Initially, the "l" value passed to help_print_optstring is 20. This can be * changed at any point by a numeric command-line argument, which will set a * new value that applies to all subsequent calls until it is changed again. * * License WTFPL2: Do What The Fuck You Want To Public License, version 2. * This is free software: you are free to do what the fuck you want to. * There is NO WARRANTY, to the extent permitted by law. */ #include "help.h" #include "tap.h" #include #include #include #include #include #include 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; opt.flag = NULL; } 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] == '&') { static int dummy; opt.flag = &dummy; } 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; }