Skip to content

Question: Can you implement subcomands using with this library? #34

Open

Description

@jr-tutor

Hi,

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

e.g.

git add *
git --help clone
etc.

Thank you

Activity

  1. cofyc commented on Sep 7, 2020

    @cofyc
    Owner

    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
    
  2. a-random-lemurian commented on Feb 9, 2022

    @a-random-lemurian
    Contributor

    Are there plans to add subcommand support to the library?

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

  3. cofyc commented on Feb 10, 2022

    @cofyc
    Owner

    no, however you can follow this example

  4. a-random-lemurian commented on Feb 10, 2022

    @a-random-lemurian
    Contributor

    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

  5. cofyc commented on Feb 10, 2022

    @cofyc
    Owner
  6. a-random-lemurian commented on Feb 10, 2022

    @a-random-lemurian
    Contributor

    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.

  7. cofyc commented on Feb 11, 2022

    @cofyc
    Owner

    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.

  8. cofyc commented on Feb 11, 2022

    @cofyc
    Owner

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions