ws_getopt: Cleaner better __getopt_msg()

This is more readable and the extra error checking is functionally
the same as the original upstream code too, that trigerred some
compiler warnings.

Add missing 'static' qualifier.

Add a test for 'ws_opterr'.
This commit is contained in:
João Valverde 2021-09-18 16:24:52 +01:00
parent 4941809359
commit b054286744
2 changed files with 47 additions and 4 deletions

View File

@ -391,6 +391,45 @@ void test_getopt_long_basic2(void)
free_argv(argv);
}
void test_getopt_opterr1(void)
{
char **argv;
int argc;
#ifdef _WIN32
g_test_skip("Not supported on Windows");
return;
#endif
if (g_test_subprocess()) {
const char *optstring = "ab";
argv = new_argv(&argc, "/bin/ls", "-a", "-z", "path", (char *)NULL);
ws_optind = 0;
ws_opterr = 1;
int opt;
opt = ws_getopt_long(argc, argv, optstring, NULL, NULL);
g_assert_cmpint(opt, ==, 'a');
opt = ws_getopt_long(argc, argv, optstring, NULL, NULL);
g_assert_cmpint(opt, ==, '?');
g_assert_cmpint(ws_optopt, ==, 'z');
opt = ws_getopt_long(argc, argv, optstring, NULL, NULL);
g_assert_cmpint(opt, ==, -1);
free_argv(argv);
return;
}
g_test_trap_subprocess(NULL, 0, 0);
g_test_trap_assert_passed();
g_test_trap_assert_stderr("/bin/ls: unrecognized option: z\n");
}
int main(int argc, char **argv)
{
int ret;
@ -417,6 +456,7 @@ int main(int argc, char **argv)
g_test_add_func("/ws_getopt/basic1", test_getopt_long_basic1);
g_test_add_func("/ws_getopt/basic2", test_getopt_long_basic2);
g_test_add_func("/ws_getopt/opterr1", test_getopt_opterr1);
ret = g_test_run();

View File

@ -37,12 +37,15 @@
char *ws_optarg;
int ws_optind=1, ws_opterr=1, ws_optopt, ws_optpos, ws_optreset=0;
void __getopt_msg(const char *a, const char *b, const char *c, size_t l)
static void __getopt_msg(const char *prog, const char *errstr,
const char *optbuf, size_t optsize)
{
FILE *f = stderr;
fputs(a, f);
fwrite(b, strlen(b), 1, f);
fwrite(c, 1, l, f);
if ((fputs(prog, f) < 0) ||
(fputs(errstr, f) < 0) ||
(fwrite(optbuf, sizeof(char), optsize, f) != optsize)) {
return;
}
putc('\n', f);
}