biojppm / c4conf

YAML-based configuration data trees, with override facilities including command line arguments.
MIT License
19 stars 2 forks source link

How to handle arguments without "dashes" #3

Closed MartijnKuipers closed 1 year ago

MartijnKuipers commented 1 year ago

Not an issue with the code, it serves my needs very well. Thanks!

However I want to have a command line like

./program input-file.yaml -c 4

How would I go about to parse an argument that doesn't start with '-' or '--' ? Should I parse it before passing on the argc/argv combo to c4conf?

Kind regards, Martijn

biojppm commented 1 year ago

Thanks for the kind words.

I'm replying on my phone and it's hard to be sure at the moment.

But if I remember correctly, only the arguments registered into c4conf are looked at, and the rest are silently ignored. After c4conf completes, the registered arguments are filtered out and no longer in argc/argv, so you only have the remaining args. At this point you can do further processing.

And of course, you definitely can also do it before calling into c4conf.

In short, you should be able to do it either before or after. Pick what suits you best.

MartijnKuipers commented 1 year ago

Obrigado João!

It was much easier than I anticipated. Basically what I did was:

`
c4::conf::Workspace ws(tree_result); ws.prepare_add_file(default_filename);

auto configs = parse_opts<std::vector<c4::conf::ParsedOpt>>(&argc, &argv, conf_specs, std::size(conf_specs));
if (argc == 1) {    // No input file given, check for version or help arguments
    ws.apply_opts(configs);
    return 0;
}
if (argc == 2) {    // Only a single input file allowed, so after parse_opts, this should be 2
    ws.prepare_add_file(argv[1]);
    ws.add_file(default_filename);
    ws.add_file(argv[1]);
    ws.apply_opts(configs);
    std::cout << c4::yml::emitrs_yaml<std::string>(tree_result);
    return 1;
}
std::cout << "Unknown parameters" << std::endl;

` This allows me to:

  1. Read a defaults file
  2. "Merge" the input file with the defaults file (input file takes precedence)
  3. Command line options take precedence over defaults and input file

From my side, feel free to close this.

biojppm commented 1 year ago

Thanks! That's exactly the intended use case.