argparse icon indicating copy to clipboard operation
argparse copied to clipboard

Question: Can you implement subcomands using with this library?

Open jr-tutor opened this issue 4 years ago • 8 comments

Hi,

does your library support subcomands such as used in GIT or Argparse?

e.g.

git add * git --help clone etc.

Thank you

jr-tutor avatar Sep 07 '20 09:09 jr-tutor

no builtin support, but it's easy to implement, e.g.

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

static struct cmd_struct commands[] = { 
    {"sub", 3, sub_cmd, NULL},
    ...
}

argc = argparse_parse(&argparse, argc, argv);
if (argc < 1) {
    // show help
}   

/* Try to run command with args provided. */
struct cmd_struct *cmd = NULL;
for (int i = 0; i < ARRAY_SIZE(commands); i++) {
    if (!strcmp(commands[i].cmd, argv[0])) {
        cmd = &commands[i];
    }   
}  

// run the command

cofyc avatar Sep 07 '20 10:09 cofyc

Are there plans to add subcommand support to the library?

P.S. Oh, there was a closed issue about subcommands.

a-random-lemurian avatar Feb 09 '22 15:02 a-random-lemurian

no, however you can follow this example

cofyc avatar Feb 10 '22 02:02 cofyc

no, however you can follow this example

that example just causes a segfault when I cmd->fn(argc, argv), what should I put in place of // run the command?

P.S I finally got a working example.... I'm gonna push it real quick P.S[2] Here's the working example https://github.com/a-random-lemurian/uselinux/blob/main/src/rmbloat/rmbloat.c

a-random-lemurian avatar Feb 10 '22 02:02 a-random-lemurian

I also create a full example here: https://github.com/cofyc/argparse/blob/master/tests/subcommands.c

cofyc avatar Feb 10 '22 08:02 cofyc

I also create a full example here: https://github.com/cofyc/argparse/blob/master/tests/subcommands.c

LGTM, but unfortunately it doesn't say anything about adding options to the subcommands themselves.

a-random-lemurian avatar Feb 10 '22 14:02 a-random-lemurian

If you need to parse arguments for subcommand, you can init and config argparse to parse arguments in the same way as in the main program.

cofyc avatar Feb 11 '22 02:02 cofyc

the example is updated, see the latest version.

Note that ARGPARSE_STOP_AT_NON_OPTION must be passed to argparse_init in the main program.

cofyc avatar Feb 11 '22 02:02 cofyc