CLIUtils / CLI11

CLI11 is a command line parser for C++11 and beyond that provides a rich feature set with a simple and intuitive interface.
https://cliutils.github.io/CLI11/book/
Other
3.28k stars 345 forks source link

set_config() on a subcommand CLI::App* #1056

Open user-45-20 opened 1 month ago

user-45-20 commented 1 month ago

I'm trying to enable the use of configuration files at the subcommand level rather than using the global CLI::App instance. It doesn't seem to work as expected regardless of what I try:

#include <CLI/CLI.hpp>
#include <iostream>

int main(int argc, char **argv) {
    CLI::App app{"Main application"};

    auto sub = app.add_subcommand("sub");

    int sub_option;
    sub->add_option("--option", sub_option, "")->required();
    sub->set_config("--config");

    CLI11_PARSE(app, argc, argv);

    if(sub->parsed()) {
        std::cout << "Subcommand option: " << sub_option << std::endl;
    }

    return 0;
}
$ ./program sub --config config.ini
--option is required
Run with --help for more information.

I've tried two different config.ini files and I get the same behavior:

1.

[sub]
option=42

2.

option=42

If I instead do app.set_config() and then use config file (1) above, it works fine - but is there a way to define config files at the subcommand level instead?

phlptp commented 1 month ago

CLI is not currently setup to process config files for individual subcommands. It would be possible using a callback and execute sub->_process_config_file(..) with the config file from the option. This is what has been done the few times I have seen a need for it. But usually we let the top level handle the config files.

phlptp commented 1 month ago

It would also be possible to create your subcommand as an option group, then add an alias so it will act as a subcommand but still read as part of the main from the perspective of a config file.