2 * Test helper application to verify help_print_optstring operation.
4 * Copyright © 2021-2022, 2024 Nick Bowler
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 * Command-line arguments are collected to create the options to be formatted.
22 * There are six basic forms:
25 * --long-option-with-argument arg
26 * --long-option-with-optional-argument [arg]
27 * --short-option -s arg
28 * --short-option-with-argument -s arg
29 * --short-option-with-optional-argument -s [arg]
31 * Adding an argument of '&' to any form will set the "flag" member of
32 * the option structure to a non-null value.
34 * Based on these arguments, a suitable 'struct option' is constructed and
35 * passed to help_print_optstring. Then a tab character is printed, followed
36 * by the return value of help_print_optsring (via printf %d). Then further
37 * arguments are considered to output more options.
39 * Initially, the "l" value passed to help_print_optstring is 20. This can be
40 * changed at any point by a numeric command-line argument, which will set a
41 * new value that applies to all subsequent calls until it is changed again.
53 #include "gnu_getopt.h"
55 int arg_to_int(const char *s
)
61 val
= strtol(s
, &end
, 0);
63 tap_bail_out("%s: numeric argument expected", s
);
64 else if (val
< INT_MIN
|| val
> INT_MAX
|| errno
== ERANGE
)
65 tap_bail_out("%s: %s", s
, strerror(ERANGE
));
67 tap_bail_out("%s: %s", s
, strerror(errno
));
72 void print_opt(struct option
*opt
, const char *argname
, int w
)
74 w
= help_print_optstring(opt
, argname
, w
);
78 int main(int argc
, char **argv
)
80 struct option opt
= {0};
81 const char *argname
= 0;
84 for (i
= 1; i
< argc
; i
++) {
85 if (argv
[i
][0] == '-' && argv
[i
][1] == '-') {
87 print_opt(&opt
, argname
, w
);
88 opt
.val
= UCHAR_MAX
+1;
92 } else if (argv
[i
][0] == '-') {
94 } else if (argv
[i
][0] == '[') {
98 if ((c
= strchr(argname
, ']')))
101 } else if (argv
[i
][0] == '&') {
104 } else if (argv
[i
][0] >= '0' && argv
[i
][0] <= '9') {
105 w
= arg_to_int(argv
[i
]);
113 print_opt(&opt
, argname
, w
);