Skip to content

Alternative implementation for subparsers #11

@limwz01

Description

@limwz01

Sorry this came late, but I recently (in Feb!) also made an implementation for subparsers, so I thought I'd share it still. It's at https://github.com/limwz01/argparse_mf/tree/with_subparsers with the commit limwz01@fccc210 . It takes a slightly different approach, but it is slightly more general, allowing specifying main options as well, something like prog --main_option subparser --sub_option.

Here's the subparsers' sample in my version:

#include <iostream>

#include "argparse/argparse.hpp"

using namespace std;

struct CommitArgs : public argparse::Args {
    bool &all                       = flag("a,all", "Tell the command to automatically stage files that have been modified and deleted, but new files you have not told git about are not affected.");
    std::string &message            = kwarg("m,message", "Use the given <msg> as the commit message.");
};

struct PushArgs : public argparse::Args {
    std::string &source             = arg("Source repository").set_default("origin");
    std::string &destination        = arg("Destination repository").set_default("master");

    void welcome() override {
        std::cout << "Push code changes to remote" << std::endl;
    }

};

struct MyArgs : public argparse::Args {
    bool &version                   = flag("v,version", "Print version");

    CommitArgs &commit              = subparser("commit", "commit changes to repository");
    PushArgs &push                  = subparser("push", "push changes to remote");
};

int main(int argc, char* argv[]) {
    auto args = argparse::parse<MyArgs>(argc, argv);

    if (args.version) {
        std::cout << "argparse_subcomands version 1.0.0" << std::endl;
        return 0;
    }
    
    args.print();
    
    if (args.commit.get_is_parsed()) {
        std::cout << "running commit with the with the following message: " << args.commit.message << std::endl;
    } else if (args.push.get_is_parsed()) {
        std::cout << "running push with the following parameters" << std::endl;
        args.push.print();
    }

    return 0;
}

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