Skip to content

Commit 4c25394

Browse files
committed
subcommand: must pass ARGPARSE_STOP_AT_NON_OPTION to argparse_init in main program
1 parent ef7b3a9 commit 4c25394

File tree

2 files changed

+37
-6
lines changed

2 files changed

+37
-6
lines changed

tests/subcommands.c

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,32 @@ static const char *const usages[] = {
1212

1313
struct cmd_struct {
1414
const char *cmd;
15-
int len;
1615
int (*fn) (int, const char **);
17-
const char *help;
1816
};
1917

2018
int
2119
cmd_foo(int argc, const char **argv)
2220
{
2321
printf("executing subcommand foo\n");
22+
printf("argc: %d\n", argc);
23+
for (int i = 0; i < argc; i++) {
24+
printf("argv[%d]: %s\n", i, *(argv + i));
25+
}
26+
int force = 0;
27+
int test = 0;
28+
const char *path = NULL;
29+
struct argparse_option options[] = {
30+
OPT_HELP(),
31+
OPT_BOOLEAN('f', "force", &force, "force to do", NULL, 0, 0),
32+
OPT_BOOLEAN('t', "test", &test, "test only", NULL, 0, 0),
33+
OPT_STRING('p', "path", &path, "path to read", NULL, 0, 0),
34+
OPT_END(),
35+
};
36+
struct argparse argparse;
37+
argparse_init(&argparse, options, usages, 0);
38+
argc = argparse_parse(&argparse, argc, argv);
39+
printf("after argparse_parse:\n");
40+
printf("argc: %d\n", argc);
2441
for (int i = 0; i < argc; i++) {
2542
printf("argv[%d]: %s\n", i, *(argv + i));
2643
}
@@ -38,8 +55,8 @@ cmd_bar(int argc, const char **argv)
3855
}
3956

4057
static struct cmd_struct commands[] = {
41-
{"foo", 3, cmd_foo, NULL},
42-
{"bar", 3, cmd_bar, NULL},
58+
{"foo", cmd_foo},
59+
{"bar", cmd_bar},
4360
};
4461

4562
int
@@ -50,7 +67,7 @@ main(int argc, const char **argv)
5067
OPT_HELP(),
5168
OPT_END(),
5269
};
53-
argparse_init(&argparse, options, usages, 0);
70+
argparse_init(&argparse, options, usages, ARGPARSE_STOP_AT_NON_OPTION);
5471
argc = argparse_parse(&argparse, argc, argv);
5572
if (argc < 1) {
5673
argparse_usage(&argparse);

tests/subcommands.sh

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,18 @@
44
plan_no_plan
55

66
is "$(./subcommands foo)" 'executing subcommand foo
7-
argv[0]: foo'
7+
argc: 1
8+
argv[0]: foo
9+
after argparse_parse:
10+
argc: 0'
11+
12+
is "$(./subcommands foo -t -p /path/to/file arg1)" 'executing subcommand foo
13+
argc: 5
14+
argv[0]: foo
15+
argv[1]: -t
16+
argv[2]: -p
17+
argv[3]: /path/to/file
18+
argv[4]: arg1
19+
after argparse_parse:
20+
argc: 1
21+
argv[0]: arg1'

0 commit comments

Comments
 (0)