Skip to content

Commit

Permalink
Merge pull request #54 from cofyc/fix-subcommands
Browse files Browse the repository at this point in the history
subcommand: must pass ARGPARSE_STOP_AT_NON_OPTION to argparse_init in main program
  • Loading branch information
cofyc-bot authored Feb 11, 2022
2 parents ef7b3a9 + 4c25394 commit c8f11ab
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
27 changes: 22 additions & 5 deletions tests/subcommands.c
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,32 @@ static const char *const usages[] = {

struct cmd_struct {
const char *cmd;
int len;
int (*fn) (int, const char **);
const char *help;
};

int
cmd_foo(int argc, const char **argv)
{
printf("executing subcommand foo\n");
printf("argc: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("argv[%d]: %s\n", i, *(argv + i));
}
int force = 0;
int test = 0;
const char *path = NULL;
struct argparse_option options[] = {
OPT_HELP(),
OPT_BOOLEAN('f', "force", &force, "force to do", NULL, 0, 0),
OPT_BOOLEAN('t', "test", &test, "test only", NULL, 0, 0),
OPT_STRING('p', "path", &path, "path to read", NULL, 0, 0),
OPT_END(),
};
struct argparse argparse;
argparse_init(&argparse, options, usages, 0);
argc = argparse_parse(&argparse, argc, argv);
printf("after argparse_parse:\n");
printf("argc: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("argv[%d]: %s\n", i, *(argv + i));
}
Expand All @@ -38,8 +55,8 @@ cmd_bar(int argc, const char **argv)
}

static struct cmd_struct commands[] = {
{"foo", 3, cmd_foo, NULL},
{"bar", 3, cmd_bar, NULL},
{"foo", cmd_foo},
{"bar", cmd_bar},
};

int
Expand All @@ -50,7 +67,7 @@ main(int argc, const char **argv)
OPT_HELP(),
OPT_END(),
};
argparse_init(&argparse, options, usages, 0);
argparse_init(&argparse, options, usages, ARGPARSE_STOP_AT_NON_OPTION);
argc = argparse_parse(&argparse, argc, argv);
if (argc < 1) {
argparse_usage(&argparse);
Expand Down
16 changes: 15 additions & 1 deletion tests/subcommands.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,18 @@
plan_no_plan

is "$(./subcommands foo)" 'executing subcommand foo
argv[0]: foo'
argc: 1
argv[0]: foo
after argparse_parse:
argc: 0'

is "$(./subcommands foo -t -p /path/to/file arg1)" 'executing subcommand foo
argc: 5
argv[0]: foo
argv[1]: -t
argv[2]: -p
argv[3]: /path/to/file
argv[4]: arg1
after argparse_parse:
argc: 1
argv[0]: arg1'

0 comments on commit c8f11ab

Please sign in to comment.