c++ - How to implement subcommands using Boost.Program_options? -


I want to implement sub commands in my program. I also need different logic options for various sub commands. What is the best way to use Boost.Program_options?

Submandings are used in programs such as SVN, GIT and APT-Mill.

For example, some of the sub-commands available in GIT:

  git position git push git git add git add   

My question is basically similar to this man:

If I understand the problem correctly You want to parse the command line options of the following form:

  [-Jenner-choice ...] CMD [- CMD-specific-choice ...]  < / Pre> 

Here is my example solution: I for clarity, I have no I am leaving the verification code, but hopefully you can see how it will be quite easy.

In this example, we have the "LS" sub-command, and possibly every other sub-order has some specific options, and additionally there are general options as well. So let's start parsing the general option and the name of the command.

  po :: options_description global ("Global Options"); Global.add_options () ("debug", "turn on debug output") ("command", po :: value   

Note that we have created a single position option for the command name, and multiple position options for command options.

Now we have branches on related command names and re-pars. Instead of going through the original argc and argv we now pass in an unfiltered options as an array of stars, the collect_unrecognized function can provide this - Remove all (conditional) commands we have to do and rearrange it with relevant options_description .

  std :: string cmd = vm ["command"]. As & lt; Std :: string & gt; (); If the (cmd == "ls") {// ls command has the following options: po :: options_description ls_desc ("ls option"); Ls_desc.add_options () ("hidden", "show hidden files") ("path", po :: value & lt; std :: string & gt; (), "in the path list"); // Collect all unfamiliar options from the first close. This will include the // (status) command name, so we have to erase it. Std :: vector & lt; Std :: string & gt; Opts = po :: collect_unrecognized (parsed.options, po :: include_positional); Opts.erase (opts.begin ()); // Parsing again ... po :: store (po :: command_line_parser (opts). Options (ls_desc) .run (), vm);   

Note that we use the same variables_map for the normal person for command-specific options, so that we can complete the related tasks.

The pieces of code here are from a consistent source file that contains some unit tests. You can get it on the abstract. Please feel free to download and play it.

Comments

Popular posts from this blog

php - How to filter values fetched from database on the basic of comma included? -

excel vba - How to delete Solver(SOLVER.XLAM) code -

c# - Add Image in a stackpanel based on textbox input -