CLI11  1.9.0
Config.hpp
Go to the documentation of this file.
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 namespace detail {
18 
19 inline std::string convert_arg_for_ini(const std::string &arg) {
20  if(arg.empty()) {
21  return std::string(2, '"');
22  }
23  // some specifically supported strings
24  if(arg == "true" || arg == "false" || arg == "nan" || arg == "inf") {
25  return arg;
26  }
27  // floating point conversion can convert some hex codes, but don't try that here
28  if(arg.compare(0, 2, "0x") != 0 && arg.compare(0, 2, "0X") != 0) {
29  double val;
30  if(detail::lexical_cast(arg, val)) {
31  return arg;
32  }
33  }
34  // just quote a single non numeric character
35  if(arg.size() == 1) {
36  return std::string("'") + arg + '\'';
37  }
38  // handle hex, binary or octal arguments
39  if(arg.front() == '0') {
40  if(arg[1] == 'x') {
41  if(std::all_of(arg.begin() + 2, arg.end(), [](char x) {
42  return (x >= '0' && x <= '9') || (x >= 'A' && x <= 'F') || (x >= 'a' && x <= 'f');
43  })) {
44  return arg;
45  }
46  } else if(arg[1] == 'o') {
47  if(std::all_of(arg.begin() + 2, arg.end(), [](char x) { return (x >= '0' && x <= '7'); })) {
48  return arg;
49  }
50  } else if(arg[1] == 'b') {
51  if(std::all_of(arg.begin() + 2, arg.end(), [](char x) { return (x == '0' || x == '1'); })) {
52  return arg;
53  }
54  }
55  }
56  if(arg.find_first_of('"') == std::string::npos) {
57  return std::string("\"") + arg + '"';
58  } else {
59  return std::string("'") + arg + '\'';
60  }
61 }
62 
64 inline std::string
65 ini_join(const std::vector<std::string> &args, char sepChar = ',', char arrayStart = '[', char arrayEnd = ']') {
66  std::string joined;
67  if(args.size() > 1 && arrayStart != '\0') {
68  joined.push_back(arrayStart);
69  }
70  std::size_t start = 0;
71  for(const auto &arg : args) {
72  if(start++ > 0) {
73  joined.push_back(sepChar);
74  if(isspace(sepChar) == 0) {
75  joined.push_back(' ');
76  }
77  }
78  joined.append(convert_arg_for_ini(arg));
79  }
80  if(args.size() > 1 && arrayEnd != '\0') {
81  joined.push_back(arrayEnd);
82  }
83  return joined;
84 }
85 
86 inline std::vector<std::string> generate_parents(const std::string &section, std::string &name) {
87  std::vector<std::string> parents;
88  if(detail::to_lower(section) != "default") {
89  if(section.find('.') != std::string::npos) {
90  parents = detail::split(section, '.');
91  } else {
92  parents = {section};
93  }
94  }
95  if(name.find('.') != std::string::npos) {
96  std::vector<std::string> plist = detail::split(name, '.');
97  name = plist.back();
99  plist.pop_back();
100  parents.insert(parents.end(), plist.begin(), plist.end());
101  }
102 
103  // clean up quotes on the parents
104  for(auto &parent : parents) {
105  detail::remove_quotes(parent);
106  }
107  return parents;
108 }
109 
111 inline void checkParentSegments(std::vector<ConfigItem> &output, const std::string &currentSection) {
112 
113  std::string estring;
114  auto parents = detail::generate_parents(currentSection, estring);
115  if(!output.empty() && output.back().name == "--") {
116  std::size_t msize = (parents.size() > 1U) ? parents.size() : 2;
117  while(output.back().parents.size() >= msize) {
118  output.push_back(output.back());
119  output.back().parents.pop_back();
120  }
121 
122  if(parents.size() > 1) {
123  std::size_t common = 0;
124  std::size_t mpair = (std::min)(output.back().parents.size(), parents.size() - 1);
125  for(std::size_t ii = 0; ii < mpair; ++ii) {
126  if(output.back().parents[ii] != parents[ii]) {
127  break;
128  }
129  ++common;
130  }
131  if(common == mpair) {
132  output.pop_back();
133  } else {
134  while(output.back().parents.size() > common + 1) {
135  output.push_back(output.back());
136  output.back().parents.pop_back();
137  }
138  }
139  for(std::size_t ii = common; ii < parents.size() - 1; ++ii) {
140  output.emplace_back();
141  output.back().parents.assign(parents.begin(), parents.begin() + static_cast<std::ptrdiff_t>(ii) + 1);
142  output.back().name = "++";
143  }
144  }
145  } else if(parents.size() > 1) {
146  for(std::size_t ii = 0; ii < parents.size() - 1; ++ii) {
147  output.emplace_back();
148  output.back().parents.assign(parents.begin(), parents.begin() + static_cast<std::ptrdiff_t>(ii) + 1);
149  output.back().name = "++";
150  }
151  }
152 
153  // insert a section end which is just an empty items_buffer
154  output.emplace_back();
155  output.back().parents = std::move(parents);
156  output.back().name = "++";
157 }
158 } // namespace detail
159 
160 inline std::vector<ConfigItem> ConfigBase::from_config(std::istream &input) const {
161  std::string line;
162  std::string section = "default";
163 
164  std::vector<ConfigItem> output;
165  bool defaultArray = (arrayStart == '\0' || arrayStart == ' ') && arrayStart == arrayEnd;
166  char aStart = (defaultArray) ? '[' : arrayStart;
167  char aEnd = (defaultArray) ? ']' : arrayEnd;
168  char aSep = (defaultArray && arraySeparator == ' ') ? ',' : arraySeparator;
169 
170  while(getline(input, line)) {
171  std::vector<std::string> items_buffer;
172  std::string name;
173 
174  detail::trim(line);
175  std::size_t len = line.length();
176  if(len > 1 && line.front() == '[' && line.back() == ']') {
177  if(section != "default") {
178  // insert a section end which is just an empty items_buffer
179  output.emplace_back();
180  output.back().parents = detail::generate_parents(section, name);
181  output.back().name = "--";
182  }
183  section = line.substr(1, len - 2);
184  // deal with double brackets for TOML
185  if(section.size() > 1 && section.front() == '[' && section.back() == ']') {
186  section = section.substr(1, section.size() - 2);
187  }
188  if(detail::to_lower(section) == "default") {
189  section = "default";
190  } else {
191  detail::checkParentSegments(output, section);
192  }
193  continue;
194  }
195  if(len == 0) {
196  continue;
197  }
198  // comment lines
199  if(line.front() == ';' || line.front() == '#' || line.front() == commentChar) {
200  continue;
201  }
202 
203  // Find = in string, split and recombine
204  auto pos = line.find(valueDelimiter);
205  if(pos != std::string::npos) {
206  name = detail::trim_copy(line.substr(0, pos));
207  std::string item = detail::trim_copy(line.substr(pos + 1));
208  if(item.size() > 1 && item.front() == aStart && item.back() == aEnd) {
209  items_buffer = detail::split_up(item.substr(1, item.length() - 2), aSep);
210  } else if(defaultArray && item.find_first_of(aSep) != std::string::npos) {
211  items_buffer = detail::split_up(item, aSep);
212  } else if(defaultArray && item.find_first_of(' ') != std::string::npos) {
213  items_buffer = detail::split_up(item);
214  } else {
215  items_buffer = {item};
216  }
217  } else {
218  name = detail::trim_copy(line);
219  items_buffer = {"true"};
220  }
221  if(name.find('.') == std::string::npos) {
222  detail::remove_quotes(name);
223  }
224  // clean up quotes on the items
225  for(auto &it : items_buffer) {
227  }
228 
229  std::vector<std::string> parents = detail::generate_parents(section, name);
230 
231  if(!output.empty() && name == output.back().name && parents == output.back().parents) {
232  output.back().inputs.insert(output.back().inputs.end(), items_buffer.begin(), items_buffer.end());
233  } else {
234  output.emplace_back();
235  output.back().parents = std::move(parents);
236  output.back().name = std::move(name);
237  output.back().inputs = std::move(items_buffer);
238  }
239  }
240  if(section != "default") {
241  // insert a section end which is just an empty items_buffer
242  std::string ename;
243  output.emplace_back();
244  output.back().parents = detail::generate_parents(section, ename);
245  output.back().name = "--";
246  while(output.back().parents.size() > 1) {
247  output.push_back(output.back());
248  output.back().parents.pop_back();
249  }
250  }
251  return output;
252 }
253 
254 inline std::string
255 ConfigBase::to_config(const App *app, bool default_also, bool write_description, std::string prefix) const {
256  std::stringstream out;
257  std::string commentLead;
258  commentLead.push_back(commentChar);
259  commentLead.push_back(' ');
260 
261  std::vector<std::string> groups = app->get_groups();
262  bool defaultUsed = false;
263  groups.insert(groups.begin(), std::string("Options"));
264  if(write_description) {
265  out << commentLead << app->get_description() << '\n';
266  }
267  for(auto &group : groups) {
268  if(group == "Options" || group.empty()) {
269  if(defaultUsed) {
270  continue;
271  }
272  defaultUsed = true;
273  }
274  if(write_description && group != "Options" && !group.empty()) {
275  out << '\n' << commentLead << group << " Options\n";
276  }
277  for(const Option *opt : app->get_options({})) {
278 
279  // Only process option with a long-name and configurable
280  if(!opt->get_lnames().empty() && opt->get_configurable()) {
281  if(opt->get_group() != group) {
282  if(!(group == "Options" && opt->get_group().empty())) {
283  continue;
284  }
285  }
286  std::string name = prefix + opt->get_lnames()[0];
287  std::string value = detail::ini_join(opt->reduced_results(), arraySeparator, arrayStart, arrayEnd);
288 
289  if(value.empty() && default_also) {
290  if(!opt->get_default_str().empty()) {
291  value = detail::convert_arg_for_ini(opt->get_default_str());
292  } else if(opt->get_expected_min() == 0) {
293  value = "false";
294  }
295  }
296 
297  if(!value.empty()) {
298  if(write_description && opt->has_description()) {
299  out << '\n';
300  out << commentLead << detail::fix_newlines(commentLead, opt->get_description()) << '\n';
301  }
302  out << name << valueDelimiter << value << '\n';
303  }
304  }
305  }
306  }
307  auto subcommands = app->get_subcommands({});
308  for(const App *subcom : subcommands) {
309  if(subcom->get_name().empty()) {
310  if(write_description && !subcom->get_group().empty()) {
311  out << '\n' << commentLead << subcom->get_group() << " Options\n";
312  }
313  out << to_config(subcom, default_also, write_description, prefix);
314  }
315  }
316 
317  for(const App *subcom : subcommands) {
318  if(!subcom->get_name().empty()) {
319  if(subcom->get_configurable() && app->got_subcommand(subcom)) {
320  if(!prefix.empty() || app->get_parent() == nullptr) {
321  out << '[' << prefix << subcom->get_name() << "]\n";
322  } else {
323  std::string subname = app->get_name() + "." + subcom->get_name();
324  auto p = app->get_parent();
325  while(p->get_parent() != nullptr) {
326  subname = p->get_name() + "." + subname;
327  p = p->get_parent();
328  }
329  out << '[' << subname << "]\n";
330  }
331  out << to_config(subcom, default_also, write_description, "");
332  } else {
333  out << to_config(subcom, default_also, write_description, prefix + subcom->get_name() + ".");
334  }
335  }
336  }
337 
338  return out.str();
339 }
340 
341 } // namespace CLI
CLI::ConfigBase::arrayEnd
char arrayEnd
the character used to end an array '\0' is a default to not use
Definition: ConfigFwd.hpp:78
CLI::detail::generate_parents
std::vector< std::string > generate_parents(const std::string &section, std::string &name)
Definition: Config.hpp:86
CLI::App::get_options
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:1533
CLI::detail::split
std::vector< std::string > split(const std::string &s, char delim)
Split a string by a delim.
Definition: StringTools.hpp:39
CLI::detail::trim_copy
std::string trim_copy(const std::string &str)
Make a copy of the string and then trim it.
Definition: StringTools.hpp:133
CLI::App::got_subcommand
bool got_subcommand(const App *subcom) const
Check to see if given subcommand was selected.
Definition: App.hpp:1378
CLI::App::get_name
const std::string & get_name() const
Get the name of the current app.
Definition: App.hpp:1711
CLI::ConfigBase::arrayStart
char arrayStart
the character used to start an array '\0' is a default to not use
Definition: ConfigFwd.hpp:76
CLI::detail::lexical_cast
bool lexical_cast(const std::string &input, T &output)
Signed integers.
Definition: TypeTools.hpp:596
CLI
Definition: App.hpp:27
CLI::detail::split_up
std::vector< std::string > split_up(std::string str, char delimiter='\0')
Definition: StringTools.hpp:282
CLI::detail::ini_join
std::string ini_join(const std::vector< std::string > &args, char sepChar=',', char arrayStart='[', char arrayEnd=']')
Comma separated join, adds quotes if needed.
Definition: Config.hpp:65
CLI::detail::convert_arg_for_ini
std::string convert_arg_for_ini(const std::string &arg)
Definition: Config.hpp:19
CLI::ConfigBase::valueDelimiter
char valueDelimiter
the character used separate the name from the value
Definition: ConfigFwd.hpp:82
CLI::App::get_groups
std::vector< std::string > get_groups() const
Get the groups available directly from this option (in order)
Definition: App.hpp:1755
CLI::ConfigBase::to_config
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:255
CLI::ConfigBase::commentChar
char commentChar
the character used for comments
Definition: ConfigFwd.hpp:74
ConfigFwd.hpp
CLI::App::get_description
std::string get_description() const
Get the app or subcommand description.
Definition: App.hpp:1524
CLI::Option
Definition: Option.hpp:228
CLI::detail::to_lower
std::string to_lower(std::string str)
Return a lower case version of a string.
Definition: StringTools.hpp:196
App.hpp
CLI::detail::fix_newlines
std::string fix_newlines(const std::string &leader, std::string input)
Definition: StringTools.hpp:333
StringTools.hpp
CLI::detail::remove_quotes
std::string & remove_quotes(std::string &str)
remove quotes at the front and back of a string either '"' or '\''
Definition: StringTools.hpp:139
CLI::App::get_subcommands
std::vector< App * > get_subcommands() const
Definition: App.hpp:1340
CLI::detail::trim
std::string & trim(std::string &str)
Trim whitespace from string.
Definition: StringTools.hpp:127
CLI::App
Creates a command line program, with very few defaults.
Definition: App.hpp:61
CLI::ConfigBase::arraySeparator
char arraySeparator
the character used to separate elements in an array
Definition: ConfigFwd.hpp:80
CLI::ConfigBase::from_config
std::vector< ConfigItem > from_config(std::istream &input) const override
Convert a configuration into an app.
Definition: Config.hpp:160
CLI::App::get_parent
App * get_parent()
Get the parent of this subcommand (or nullptr if master app)
Definition: App.hpp:1705
CLI::detail::checkParentSegments
void checkParentSegments(std::vector< ConfigItem > &output, const std::string &currentSection)
assuming non default segments do a check on the close and open of the segments in a configItem struct...
Definition: Config.hpp:111