CLI11
C++11 Command Line Interface Parser
Config.hpp
1 #pragma once
2 
3 // Distributed under the 3-Clause BSD License. See accompanying
4 // file LICENSE or https://github.com/CLIUtils/CLI11 for details.
5 
6 #include <algorithm>
7 #include <fstream>
8 #include <iostream>
9 #include <string>
10 
11 #include "CLI/App.hpp"
12 #include "CLI/ConfigFwd.hpp"
13 #include "CLI/StringTools.hpp"
14 
15 namespace CLI {
16 
17 inline std::string
18 ConfigINI::to_config(const App *app, bool default_also, bool write_description, std::string prefix) const {
19  std::stringstream out;
20  for(const Option *opt : app->get_options({})) {
21 
22  // Only process option with a long-name and configurable
23  if(!opt->get_lnames().empty() && opt->get_configurable()) {
24  std::string name = prefix + opt->get_lnames()[0];
25  std::string value;
26 
27  // Non-flags
28  if(opt->get_type_size() != 0) {
29 
30  // If the option was found on command line
31  if(opt->count() > 0)
32  value = detail::ini_join(opt->results());
33 
34  // If the option has a default and is requested by optional argument
35  else if(default_also && !opt->get_default_str().empty())
36  value = opt->get_default_str();
37  // Flag, one passed
38  } else if(opt->count() == 1) {
39  value = "true";
40 
41  // Flag, multiple passed
42  } else if(opt->count() > 1) {
43  value = std::to_string(opt->count());
44 
45  // Flag, not present
46  } else if(opt->count() == 0 && default_also) {
47  value = "false";
48  }
49 
50  if(!value.empty()) {
51  if(write_description && opt->has_description()) {
52  if(static_cast<int>(out.tellp()) != 0) {
53  out << std::endl;
54  }
55  out << "; " << detail::fix_newlines("; ", opt->get_description()) << std::endl;
56  }
57 
58  // Don't try to quote anything that is not size 1
59  if(opt->get_items_expected() != 1)
60  out << name << "=" << value << std::endl;
61  else
62  out << name << "=" << detail::add_quotes_if_needed(value) << std::endl;
63  }
64  }
65  }
66 
67  for(const App *subcom : app->get_subcommands({}))
68  out << to_config(subcom, default_also, write_description, prefix + subcom->get_name() + ".");
69 
70  return out.str();
71 }
72 
73 } // namespace CLI
Definition: App.hpp:29
std::vector< App * > get_subcommands() const
Definition: App.hpp:1405
Creates a command line program, with very few defaults.
Definition: App.hpp:59
std::vector< const Option * > get_options(const std::function< bool(const Option *)> filter={}) const
Get the list of options (user facing function, so returns raw pointers), has optional filter function...
Definition: App.hpp:1549
std::string to_config(const App *, bool default_also, bool write_description, std::string prefix) const override
Convert an app into a configuration.
Definition: Config.hpp:18
Definition: Option.hpp:206