p-ranav / argparse

Argument Parser for Modern C++
MIT License
2.72k stars 250 forks source link

is_subcommand_used doesn't work if same argument is added to parent and child #327

Open MartyMcFlyInTheSky opened 9 months ago

MartyMcFlyInTheSky commented 9 months ago

I think that's a bug. Consider this small program:

#include <iostream>
#include <filesystem>
#include <fstream> /* ifstream */
#include <string>
#include <cstdint> /* uint16_t */
#include <argparse/argparse.hpp>

int main(int argc, char* argv[]) {

    // Parse parameters with subcommands
    argparse::ArgumentParser program("dbclient");
    // !! remove the below argument then it works..
    program.add_argument("config_file_path")
        .default_value<std::filesystem::path>(DEFAULT_CONFIG_PATH)
        .required();  // Make positional arguments mandatory

        argparse::ArgumentParser push_command("push");  // Create the program object
        push_command.add_description("Uploads data specified in the given config file to the database.");
        push_command.add_argument("config_file_path")
            .default_value<std::filesystem::path>(DEFAULT_CONFIG_PATH)
            .required();  // Make positional arguments mandatory

        argparse::ArgumentParser pull_command("pull");  // Create the program object
        pull_command.add_description("Downloads data given by the database to the specified output directory.");
        pull_command.add_argument("config_file_path")
            .default_value<std::filesystem::path>(DEFAULT_CONFIG_PATH)
            .required();  // Make positional arguments mandatory

    program.add_subparser(push_command);
    program.add_subparser(pull_command);

    program.parse_args(argc, argv); // Parse the arguments

    if (program.is_subcommand_used(push_command)) {
        std::cout << "Push command used" << std::endl;
    } else if (program.is_subcommand_used(pull_command)) {
        std::cout << "Pull command used" << std::endl;
    } else {
        std::cout << "No command used apparently" << std::endl;
    }

}

If i start this with main push it will output "No command used apparently". I would have expected it to print "Push command used". It works if I remove the add_argument to the program, it will correctly print "Push command used".