goptions
Loading...
Searching...
No Matches
goptions.cc
Go to the documentation of this file.
1
13
14// goptions
15#include "goptions.h"
16#include "goptionsConventions.h"
17#include "gversion.h"
18
19// gemc
20#include "gutilities.h"
21
22// c++
23#include <algorithm>
24#include <iostream>
25#include <cstring>
26#include <cctype>
27#include <cstdlib>
28#include <filesystem>
29
30using namespace std;
31
32namespace {
33// Parse a human-friendly boolean token used for switches (-switch=value and YAML switch values).
34// Accepts, case-insensitively: true/1/yes/y/on and false/0/no/n/off. Returns false if @p raw is
35// not a recognized token, leaving @p out untouched.
36bool parse_bool_token(const std::string& raw, bool& out) {
37 std::string v = raw;
38 std::transform(v.begin(), v.end(), v.begin(),
39 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
40 if (v == "true" || v == "1" || v == "yes" || v == "y" || v == "on") { out = true; return true; }
41 if (v == "false" || v == "0" || v == "no" || v == "n" || v == "off") { out = false; return true; }
42 return false;
43}
44
45std::string geant4_installation() {
46 const char* path_environment = std::getenv("PATH");
47 if (path_environment == nullptr) {
48 return "geant4-config not found (PATH is not set)";
49 }
50
51 const std::string path = path_environment;
52 std::size_t start = 0;
53 while (start <= path.size()) {
54 const std::size_t end = path.find(':', start);
55 const std::string directory = path.substr(start, end - start);
56 const auto candidate = std::filesystem::path(directory.empty() ? "." : directory) / "geant4-config";
57 std::error_code error;
58 if (std::filesystem::is_regular_file(candidate, error)) {
59 auto resolved = std::filesystem::canonical(candidate, error);
60 if (error) {
61 resolved = candidate;
62 }
63 return resolved.parent_path().parent_path().string();
64 }
65 if (end == std::string::npos) {
66 break;
67 }
68 start = end + 1;
69 }
70
71 return "geant4-config not found in PATH";
72}
73}
74
75// See goptions.h for full constructor API documentation.
76/*
77 * Parsing precedence implemented here:
78 * 1. YAML file(s), applied in argv order
79 * 2. Command-line tokens override YAML values
80 *
81 * Notes:
82 * - "help <option>" is treated as an immediate action and exits after printing.
83 * - Dot-notation routes structured updates to the owning option via GOption::set_sub_option_value().
84 */
85GOptions::GOptions(int argc, char* argv[], const GOptions& user_defined_options) {
86 executableName = gutilities::getFileFromPath(argv[0]);
87 executableCallingDir = gutilities::getDirFromPath(argv[0]);
88 installDir = gutilities::executable_path().parent_path().string();
89 cout << endl;
90
91 // Add user-defined options.
92 addGOptions(user_defined_options);
93
94 // switches for all everyone
95 defineSwitch("gui", "run with the graphical user interface (Qt window)");
96 defineSwitch("i", "drop into the interactive Geant4 terminal session (non-GUI mode)");
98 GVariable("conf_yaml", "saved_configuration", "infix for the YAML file that records the resolved options"),
99 "On exit the resolved configuration is written to <executable>.<conf_yaml>.yaml,\n"
100 "so the default value produces, for example, gemc.saved_configuration.yaml.\n \n"
101 "Example: -conf_yaml=run12 -> saves to gemc.run12.yaml\n \n");
102
103 // add test timeout for the tests
104 defineOption(GVariable("tt", 500, "GUI test timeout (ms)"),
105 "Milliseconds a GUI-based test waits before it auto-closes, so the module\n"
106 "example/test programs can run unattended in CI.\n \n"
107 "Example: -tt=1000\n \n");
108
109 // version is a special option, not settable by the user
110 // it is set by the gversion.h file
111 // we add it here so it can be saved to the yaml file
112 vector<GVariable> version = {
113 {"release", gversion, "release version number"},
114 {"release_date", grelease_date, "release date"},
115 {"Reference", greference, "article reference"},
116 {"Homepage", gweb, "homepage"},
117 {"Author", gauthor, "author"}
118 };
119 defineOption(goptions::GVERSION_STRING, "version information", version,
120 "Version information. Not settable by user.");
121
122 // verbosity option: convention used across modules consuming verbosity levels
123 string help = "Levels: \n \n";
124 help += " - 0: (default) = shush\n";
125 help += " - 1: log detailed information\n";
126 help += " - 2: log extra detailed information\n \n";
127 help += "Each key names a class or module; run 'help verbosity' to list the available keys.\n \n";
128 help += "Example (one key): -verbosity.gemc=1\n";
129 help += "Example (several keys): -verbosity=\"[{gemc: 1}, {<another_key>: 2}]\"\n \n";
130 help += "Equivalent YAML:\n";
131 help += " verbosity:\n";
132 help += " - gemc: 1\n";
133 help += " - <another_key>: 2\n \n";
134 defineOption("verbosity", "Sets the log verbosity for various classes", option_verbosity_names, help);
135
136 // debug option: boolean or integer, depending on consumer expectations
137 help = "Debug information Types: \n \n";
138 help += " - false: (default): do not print debug information\n";
139 help += " - true: print debug information\n\n";
140 help += "Each key names a class or module; run 'help debug' to list the available keys.\n \n";
141 help += "Example (on/off): -debug.gemc=true\n";
142 help += "Example (several keys): -debug=\"[{gemc: true}, {<another_key>: 1}]\"\n \n";
143 help += "Equivalent YAML:\n";
144 help += " debug:\n";
145 help += " - gemc: true\n \n";
146 defineOption("debug", "Sets the debug level for various classes", option_verbosity_names, help);
147
148 // Process help/version command-line arguments.
149 // These are handled early and exit immediately (they do not proceed to parse YAML/options).
150 for (int i = 1; i < argc; i++) {
151 if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--h") == 0 ||
152 strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "--help") == 0) {
153 printHelp();
154 }
155 else if (strcmp(argv[i], "-hweb") == 0) {
156 printWebHelp();
157 }
158 else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--v") == 0 ||
159 strcmp(argv[i], "-version") == 0 || strcmp(argv[i], "--version") == 0) {
160 print_version();
161 exit(EXIT_SUCCESS);
162 }
163 else if (strcmp(argv[i], "help") == 0) {
164 // "gemc help <topic>" shows topic help; bare "gemc help" shows the general help index.
165 if (i + 1 < argc) { printOptionOrSwitchHelp(argv[i + 1]); }
166 else { printHelp(); }
167 exit(EXIT_SUCCESS);
168 }
169 else if (strcmp(argv[i], "search") == 0) {
170 // "gemc search <value>" lists options/switches whose name or description contains <value>.
171 if (i + 1 < argc) { printSearch(argv[i + 1]); }
172 else { printHelp(); }
173 exit(EXIT_SUCCESS);
174 }
175 }
176
177 // finds and parse the yaml files
178 // YAML file tokens are treated as inputs, not as "invalid command-line arguments".
179 yaml_files = findYamls(argc, argv);
180 for (auto& yaml_file : yaml_files) {
181 cout << " Parsing " << yaml_file << endl;
182 setOptionsValuesFromYamlFile(yaml_file);
183 }
184
185 // Parse command-line arguments (supports both standard YAML–style and dot–notation).
186 for (int i = 1; i < argc; i++) {
187 string candidate = argv[i];
188 if (candidate.empty()) continue;
189
190 // Skip YAML file tokens: they were already handled above.
191 if (find(yaml_files.begin(), yaml_files.end(), candidate) != yaml_files.end()) continue;
192
193 if (candidate[0] == '-') {
194 string argStr = candidate.substr(1);
195 size_t eqPos = argStr.find('=');
196
197 if (eqPos != string::npos) {
198 string keyPart = argStr.substr(0, eqPos);
199 string valuePart = argStr.substr(eqPos + 1);
200
201 // Switch with an explicit boolean value: -gui=false / -gui=true. This gives the
202 // CLI a way to turn a switch off, honoring the documented CLI-over-YAML precedence.
203 if (switches.find(keyPart) != switches.end()) {
204 bool on = false;
205 if (parse_bool_token(valuePart, on)) { on ? switches[keyPart].turnOn() : switches[keyPart].turnOff(); }
206 else {
207 cerr << "The switch " << keyPart << " accepts only true/false/yes/no/on/off/1/0." << endl;
209 }
210 continue;
211 }
212
213 // Strip outer quotes if present (e.g., -gstreamer="[...]")
214 if (!valuePart.empty() && valuePart.front() == '"' && valuePart.back() == '"') {
215 valuePart = valuePart.substr(1, valuePart.length() - 2);
216 }
217
218 // Dot-notation targets a subkey in a structured option (e.g., verbosity.gemc).
219 size_t dotPos = keyPart.find('.');
220 if (dotPos != string::npos) {
221 string mainOption = keyPart.substr(0, dotPos);
222 string subOption = keyPart.substr(dotPos + 1);
223
224 if (doesOptionExist(mainOption)) {
225 auto it = getOptionIterator(mainOption);
226 it->set_sub_option_value(subOption, valuePart);
227 }
228 else {
229 cerr << "The option " << mainOption << " is not known to this system." << endl;
231 }
232 }
233 else {
234 // Standard option syntax: -name=value
235 if (doesOptionExist(keyPart)) {
236 setOptionValuesFromCommandLineArgument(keyPart, valuePart);
237 }
238 else {
239 cerr << "The option " << keyPart << " is not known to this system." << endl;
241 }
242 }
243 }
244 else {
245 // Treat as a switch: -gui, -i, etc.
246 const string& possibleSwitch = argStr;
247 if (switches.find(possibleSwitch) != switches.end()) {
248 switches[possibleSwitch].turnOn();
249 }
250 else {
251 cerr << "The switch " << possibleSwitch << " is not known to this system." << endl;
253 }
254 }
255 }
256 else {
257 cerr << "The command-line argument \"" << candidate << "\" is not valid." << endl;
259 }
260 }
261
262 // Always print version information.
263 print_version();
264
265 // Save the final configuration to a YAML file.
266 string yamlConf_filename = executableName + "." + getRequiredScalarString("conf_yaml") + ".yaml";
267 cout << " Saving options to " << yamlConf_filename << endl << endl;
268 yamlConf = new std::ofstream(yamlConf_filename);
269 saveOptions();
270}
271
272// Implementation note: public API docs are in goptions.h (avoid duplicate \param blocks).
273void GOptions::defineSwitch(const std::string& name, const std::string& description, bool default_status) {
274 if (switches.find(name) == switches.end()) {
275 switches[name] = GSwitch(description, default_status);
276 }
277 else {
278 std::cerr << guts::FATALERRORL << "The " << guts::YELLOWHHL << name << guts::RSTHHR
279 << " switch is already present." << std::endl;
281 }
282}
283
284// Implementation note: public API docs are in goptions.h (avoid duplicate \param blocks).
285void GOptions::defineOption(const GVariable& gvar, const std::string& help) {
286 if (doesOptionExist(gvar.name)) {
287 std::cerr << guts::FATALERRORL << "The " << guts::YELLOWHHL << gvar.name << guts::RSTHHR
288 << " option is already present." << std::endl;
290 }
291 else {
292 goptions.emplace_back(gvar, help);
293 }
294}
295
296// Implementation note: public API docs are in goptions.h (avoid duplicate \param blocks).
297void GOptions::defineOption(const std::string& name, const std::string& description,
298 const std::vector<GVariable>& gvars,
299 const std::string& help) {
300 if (doesOptionExist(name)) {
301 std::cerr << guts::FATALERRORL << "The " << guts::YELLOWHHL << name << guts::RSTHHR
302 << " option is already present." << std::endl;
304 }
305 else {
306 goptions.emplace_back(name, description, gvars, help);
307 }
308}
309
310// Implementation note: public API docs are in goptions.h (avoid duplicate \param blocks).
311int GOptions::getRequiredScalarInt(const std::string& tag) const {
312 auto it = getOptionIterator(tag);
313 if (it == goptions.end()) {
314 cerr << guts::FATALERRORL << "The option " << guts::YELLOWHHL << tag << guts::RSTHHR
315 << " was not found." << endl;
317 }
318 const YAML::Node node = it->value.begin()->second;
319 if (!node.IsDefined() || node.IsNull()) {
320 cerr << guts::FATALERRORL << "The required option " << guts::YELLOWHHL << tag << guts::RSTHHR
321 << " was not provided." << endl;
323 }
324 return node.as<int>();
325}
326
327std::optional<int> GOptions::getOptionalScalarInt(const std::string& tag) const {
328 auto it = getOptionIterator(tag);
329 if (it == goptions.end()) {
330 cerr << guts::FATALERRORL << "The option " << guts::YELLOWHHL << tag << guts::RSTHHR
331 << " was not found." << endl;
333 }
334 const YAML::Node node = it->value.begin()->second;
335 if (!node.IsDefined() || node.IsNull()) return std::nullopt;
336 return node.as<int>();
337}
338
339// Implementation note: public API docs are in goptions.h (avoid duplicate \param blocks).
340double GOptions::getRequiredScalarDouble(const std::string& tag) const {
341 auto it = getOptionIterator(tag);
342 if (it == goptions.end()) {
343 cerr << guts::FATALERRORL << "The option " << guts::YELLOWHHL << tag << guts::RSTHHR
344 << " was not found." << endl;
346 }
347 const YAML::Node node = it->value.begin()->second;
348 if (!node.IsDefined() || node.IsNull()) {
349 cerr << guts::FATALERRORL << "The required option " << guts::YELLOWHHL << tag << guts::RSTHHR
350 << " was not provided." << endl;
352 }
353 return node.as<double>();
354}
355
356std::optional<double> GOptions::getOptionalScalarDouble(const std::string& tag) const {
357 auto it = getOptionIterator(tag);
358 if (it == goptions.end()) {
359 cerr << guts::FATALERRORL << "The option " << guts::YELLOWHHL << tag << guts::RSTHHR
360 << " was not found." << endl;
362 }
363 const YAML::Node node = it->value.begin()->second;
364 if (!node.IsDefined() || node.IsNull()) return std::nullopt;
365 return node.as<double>();
366}
367
368std::string GOptions::getRequiredScalarString(const std::string& tag) const {
369 auto it = getOptionIterator(tag);
370 if (it == goptions.end()) {
371 cerr << guts::FATALERRORL << "The option " << guts::YELLOWHHL << tag << guts::RSTHHR
372 << " was not found." << endl;
374 }
375 const YAML::Node node = it->value.begin()->second;
376 if (!node.IsDefined() || node.IsNull()) {
377 cerr << guts::FATALERRORL << "The required option " << guts::YELLOWHHL << tag << guts::RSTHHR
378 << " was not provided." << endl;
380 }
381 return node.as<std::string>();
382}
383
384// Implementation note: public API docs are in goptions.h (avoid duplicate \param blocks).
385std::optional<std::string> GOptions::getOptionalScalarString(const std::string& tag) const {
386 auto it = getOptionIterator(tag);
387 if (it == goptions.end()) {
388 std::cerr << guts::FATALERRORL << "The option " << guts::YELLOWHHL << tag << guts::RSTHHR
389 << " was not found." << std::endl;
391 }
392 const YAML::Node node = it->value.begin()->second;
393 if (!node.IsDefined() || node.IsNull()) return std::nullopt;
394 return node.as<std::string>();
395}
396
397
398// Private method: see header. Kept undocumented here to avoid duplicate param docs.
399void GOptions::printOptionOrSwitchHelp(const std::string& tag) const {
400 auto switchIt = switches.find(tag);
401 if (switchIt != switches.end()) {
402 cout << guts::KGRN << "-" << tag << guts::RST << ": " << switchIt->second.getDescription() << endl << endl;
403 cout << guts::TPOINTITEM << "Default value is " << (switchIt->second.getStatus() ? "on" : "off") << endl
404 << endl;
405 exit(EXIT_SUCCESS);
406 }
407 for (const auto& goption : goptions) {
408 if (goption.name == tag) {
409 goption.printHelp(true);
410 exit(EXIT_SUCCESS);
411 }
412 }
413 cerr << guts::FATALERRORL << "The " << guts::YELLOWHHL << tag << guts::RSTHHR
414 << " option is not known to this system." << endl;
416}
417
418// Private method: see header. Kept undocumented here to avoid duplicate param docs.
419void GOptions::printSearch(const std::string& tag) const {
420 // Case-insensitive substring match against switch/option names and descriptions.
421 auto to_lower = [](string s) {
422 transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); });
423 return s;
424 };
425 const string needle = to_lower(tag);
426 auto matches = [&](const string& a, const string& b) {
427 return to_lower(a).find(needle) != string::npos || to_lower(b).find(needle) != string::npos;
428 };
429
430 long int fill_width = string(goptions::HELPFILLSPACE).size() + 1;
431 cout.fill('.');
432 cout << guts::KGRN << guts::KBOLD << " Options and switches matching \"" << tag << "\":" << guts::RST
433 << endl
434 << endl;
435
436 bool found = false;
437 for (auto& s : switches) {
438 if (matches(s.first, s.second.getDescription())) {
439 found = true;
440 cout << guts::KGRN << " " << left;
441 cout.width(fill_width);
442 cout << "-" + s.first + guts::RST + " " << ": " << s.second.getDescription() << endl;
443 }
444 }
445 for (auto& option : goptions) {
446 if (option.name != goptions::GVERSION_STRING && matches(option.name, option.description)) {
447 found = true;
448 option.printHelp(false);
449 }
450 }
451 if (!found) { cout << guts::TPOINTITEM << "no match found." << endl; }
452 cout << endl
453 << " Use " << guts::KGRN << "help <value>" << guts::RST << " for the detailed help of a single option."
454 << endl
455 << endl;
456}
457
458// Private method: see header. Kept undocumented here to avoid duplicate param docs.
459vector<string> GOptions::findYamls(int argc, char* argv[]) {
460 vector<string> yaml_files;
461 auto ends_with = [](const string& s, const string& suffix) {
462 return s.size() >= suffix.size() &&
463 s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0;
464 };
465 for (int i = 1; i < argc; i++) {
466 string arg = argv[i];
467 // Match a trailing .yaml/.yml extension, not any substring, so option values such as
468 // -prefix=run.yaml.bak are not mistaken for input files (and silently dropped).
469 if (ends_with(arg, ".yaml") || ends_with(arg, ".yml")) yaml_files.push_back(arg);
470 }
471 return yaml_files;
472}
473
474// checks if the option exists
475// Public API docs are in goptions.h; doxygen param docs are kept only there.
476bool GOptions::doesOptionExist(const std::string& tag) const {
477 // [&tag] ensures we're referencing the original tag passed to the function
478 return std::any_of(goptions.begin(), goptions.end(),
479 [&tag](const auto& option) {
480 return option.name == tag;
481 });
482}
483
484// Private method: behavior described in header and top-of-file overview.
485void GOptions::setOptionsValuesFromYamlFile(const std::string& yaml) {
486 YAML::Node config;
487 try {
488 config = YAML::LoadFile(yaml);
489 }
490 catch (YAML::BadFile& e) {
491 cerr << guts::FATALERRORL << "Cannot open yaml file " << guts::YELLOWHHL << yaml << guts::RSTHHR
492 << ". Check the path and spelling." << endl;
494 }
495 catch (YAML::ParserException& e) {
496 cerr << guts::FATALERRORL << "Error parsing " << guts::YELLOWHHL << yaml << guts::RSTHHR
497 << " yaml file." << endl;
498 cerr << e.what() << endl;
499 cerr << "Try validating the yaml file with an online yaml validator, e.g., https://www.yamllint.com" << endl;
501 }
502
503 for (auto it = config.begin(); it != config.end(); ++it) {
504 auto option_name = it->first.as<std::string>();
505 auto option_it = getOptionIterator(option_name);
506
507 // If it is not an option, it may still be a switch.
508 if (option_it == goptions.end()) {
509 if (switches.find(option_name) == switches.end()) {
510 cerr << guts::FATALERRORL << "The option or switch " << guts::YELLOWHHL << option_name << guts::RSTHHR
511 << " is not known to this system." << endl;
513 }
514 else {
515 // A bare key (null value) means "present" -> on; an explicit boolean value is honored,
516 // so a default-on switch can be turned off from YAML (e.g. print_summary: false).
517 bool on = true;
518 if (it->second.IsScalar() && !parse_bool_token(it->second.as<std::string>(), on)) {
519 cerr << guts::FATALERRORL << "The switch " << guts::YELLOWHHL << option_name << guts::RSTHHR
520 << " accepts only true/false/yes/no/on/off/1/0." << endl;
522 }
523 on ? switches[option_name].turnOn() : switches[option_name].turnOff();
524 }
525 }
526 else {
527 YAML::NodeType::value type = it->second.Type();
528 switch (type) {
529 case YAML::NodeType::Scalar:
530 option_it->set_scalar_value(it->second.as<std::string>());
531 break;
532 case YAML::NodeType::Sequence:
533 option_it->set_value(it->second);
534 break;
535 case YAML::NodeType::Map:
536 option_it->set_value(it->second);
537 break;
538 default:
539 break;
540 }
541 }
542 }
543}
544
545// Private method: behavior described in header and top-of-file overview.
546void GOptions::setOptionValuesFromCommandLineArgument(const std::string& optionName,
547 const std::string& possibleYamlNode) {
548 auto option_it = getOptionIterator(optionName);
549 if (possibleYamlNode.empty()) {
550 option_it->set_scalar_value("");
551 return;
552 }
553
554 YAML::Node node = YAML::Load(possibleYamlNode);
555
556 if (node.Type() == YAML::NodeType::Scalar) {
557 option_it->set_scalar_value(possibleYamlNode);
558 }
559 else {
560 option_it->set_value(node);
561 }
562}
563
564void GOptions::setOptionValueFromString(const std::string& optionName,
565 const std::string& possibleYamlNode) {
566 setOptionValuesFromCommandLineArgument(optionName, possibleYamlNode);
567}
568
569// Private method (private API): do not \ref; use \c getOptionIterator() in docs if needed.
570std::vector<GOption>::iterator GOptions::getOptionIterator(const std::string& name) {
571 return std::find_if(goptions.begin(), goptions.end(),
572 [&name](GOption& option) { return option.name == name; });
573}
574
575// Private method (private API): do not \ref; use \c getOptionIterator() in docs if needed.
576std::vector<GOption>::const_iterator GOptions::getOptionIterator(const std::string& name) const {
577 return std::find_if(goptions.begin(), goptions.end(),
578 [&name](const GOption& option) { return option.name == name; });
579}
580
581// Implementation note: public API docs are in goptions.h (avoid duplicate \param blocks).
582bool GOptions::getSwitch(const std::string& tag) const {
583 auto it = switches.find(tag);
584 if (it != switches.end()) {
585 return it->second.getStatus();
586 }
587 else {
588 std::cerr << guts::FATALERRORL << "The switch " << guts::YELLOWHHL << tag << guts::RSTHHR
589 << " was not found." << std::endl;
591 }
592}
593
594// Implementation note: public API docs are in goptions.h (avoid duplicate \param blocks).
595YAML::Node GOptions::getOptionMapInNode(const string& option_name, const string& map_key) const {
596 auto sequence_node = getOptionNode(option_name);
597
598 for (auto seq_item : sequence_node) {
599 for (auto map_item = seq_item.begin(); map_item != seq_item.end(); ++map_item) {
600 if (map_item->first.as<string>() == map_key) {
601 return map_item->second;
602 }
603 }
604 }
605
606 cerr << guts::FATALERRORL << "The key " << guts::YELLOWHHL << map_key << guts::RSTHHR
607 << " was not found in " << guts::YELLOWHHL << option_name << guts::RSTHHR << endl;
609}
610
611// Template documentation lives in the header to avoid duplicate \param blocks.
612template <typename T>
613T GOptions::get_variable_in_option(const YAML::Node& node, const std::string& variable_name, const T& default_value) {
614 if (node[variable_name]) {
615 return node[variable_name].as<T>();
616 }
617 return default_value;
618}
619
620template <typename T>
621T GOptions::get_required_variable_in_option(const YAML::Node& node, const std::string& variable_name) {
622 if (!node[variable_name] || node[variable_name].IsNull()) {
623 std::cerr << guts::FATALERRORL << "The mandatory key " << guts::YELLOWHHL << variable_name
624 << guts::RSTHHR << " was not provided." << std::endl;
626 }
627 return node[variable_name].as<T>();
628}
629
630template <typename T>
632 const YAML::Node& node, const std::string& variable_name) {
633 if (!node[variable_name] || node[variable_name].IsNull()) return std::nullopt;
634 return node[variable_name].as<T>();
635}
636
637// Explicit template instantiations.
638template int GOptions::get_variable_in_option<int>(const YAML::Node& node, const std::string& variable_name,
639 const int& default_value);
640template double GOptions::get_variable_in_option<double>(const YAML::Node& node, const std::string& variable_name,
641 const double& default_value);
642template string GOptions::get_variable_in_option<string>(const YAML::Node& node, const std::string& variable_name,
643 const string& default_value);
644template bool GOptions::get_variable_in_option<bool>(const YAML::Node& node, const std::string& variable_name,
645 const bool& default_value);
646template int GOptions::get_required_variable_in_option<int>(const YAML::Node&, const std::string&);
647template double GOptions::get_required_variable_in_option<double>(const YAML::Node&, const std::string&);
648template string GOptions::get_required_variable_in_option<string>(const YAML::Node&, const std::string&);
649template bool GOptions::get_required_variable_in_option<bool>(const YAML::Node&, const std::string&);
650template std::optional<int> GOptions::get_optional_variable_in_option<int>(
651 const YAML::Node&, const std::string&);
652template std::optional<double> GOptions::get_optional_variable_in_option<double>(const YAML::Node&,
653 const std::string&);
654template std::optional<string> GOptions::get_optional_variable_in_option<string>(const YAML::Node&,
655 const std::string&);
656
657// Implementation note: public API docs are in goptions.h (avoid duplicate \param blocks).
658int GOptions::getVerbosityFor(const std::string& tag) const {
659 YAML::Node verbosity_node = getOptionNode("verbosity");
660 for (auto v : verbosity_node) {
661 if (v.begin()->first.as<string>() == tag) {
662 return v.begin()->second.as<int>();
663 }
664 }
665
666 // not found. error
667 std::cerr << guts::KRED << " Invalid verbosity or debug requested: " << tag << guts::RST << std::endl;
669}
670
671// Implementation note: public API docs are in goptions.h (avoid duplicate \param blocks).
672int GOptions::getDebugFor(const std::string& tag) const {
673 YAML::Node debug_node = getOptionNode("debug");
674 for (auto d : debug_node) {
675 if (d.begin()->first.as<string>() == tag) {
676 YAML::Node valNode = d.begin()->second;
677 if (valNode.IsScalar()) {
678 auto s = valNode.as<string>();
679 if (s == "true") return 1;
680 if (s == "false") return 0;
681 }
682 try {
683 return valNode.as<int>();
684 }
685 catch (const YAML::BadConversion&) {
686 std::cerr << "Invalid debug value for " << tag << std::endl;
688 }
689 }
690 }
691 // not found. error
692 std::cerr << guts::KRED << " Invalid verbosity or debug requested: " << tag << guts::RST << std::endl;
694}
695
696// Private method: no Doxygen block here to avoid duplicate \param docs.
697void GOptions::printHelp() const {
698 long int fill_width = string(goptions::HELPFILLSPACE).size() + 1;
699 cout.fill('.');
700 cout << guts::KGRN << guts::KBOLD << " " << executableName << guts::RST << " [options] [yaml files]" << endl
701 << endl;
702 cout << " Switches: " << endl << endl;
703 for (auto& s : switches) {
704 string help = "-" + s.first + guts::RST + " ";
705 cout << guts::KGRN << " " << left;
706 cout.width(fill_width);
707 cout << help;
708 cout << ": " << s.second.getDescription() << endl;
709 }
710 cout << endl;
711 cout << " Options: " << endl << endl;
712 for (auto& option : goptions) {
713 option.printHelp(false);
714 }
715 cout << endl;
716 cout << endl << " Help / Search / Introspection: " << endl << endl;
717 vector<string> helps = {
718 string("-h, --h, -help, --help") + guts::RST,
719 string("print this help and exit"),
720 string("-hweb") + guts::RST,
721 string("print this help in web format and exit"),
722 string("-v, --v, -version, --version") + guts::RST,
723 string("print the version and exit\n"),
724 string("help <value>") + guts::RST,
725 string("print detailed help for option <value> and exit"),
726 string("search <value>") + guts::RST,
727 string("list all options/switches whose name or description contains <value> and exit\n")
728 };
729 unsigned half_help = helps.size() / 2;
730 for (unsigned i = 0; i < half_help; i++) {
731 cout << guts::KGRN << " " << left;
732 cout.width(fill_width);
733 cout << helps[i * 2] << ": " << helps[i * 2 + 1] << endl;
734 }
735 cout << endl;
736 cout << " Note: command line options overwrite YAML file(s)." << endl << endl;
737 exit(EXIT_SUCCESS);
738}
739
740// Private method: no Doxygen block here to avoid duplicate \param docs.
741void GOptions::printWebHelp() const {
742 exit(EXIT_SUCCESS);
743}
744
745// Private method: no Doxygen block here to avoid duplicate \param docs.
746void GOptions::saveOptions() const {
747 for (auto& s : switches) {
748 string status = s.second.getStatus() ? "true" : "false";
749 *yamlConf << s.first + ": " + status << "," << endl;
750 }
751 for (const auto& option : goptions) {
752 option.saveOption(yamlConf);
753 }
754 yamlConf->close();
755}
756
757// Private method: no Doxygen block here to avoid duplicate \param docs.
758void GOptions::print_version() {
759 string asterisks = "*******************************************************************";
760 cout << endl << asterisks << endl;
761 cout << " " << guts::KGRN << guts::KBOLD << executableName << guts::RST << " version: " << guts::KGRN
762 << gversion << guts::RST << endl;
763 cout << " Called from: " << guts::KGRN << executableCallingDir << guts::RST << endl;
764 cout << " Install: " << guts::KGRN << installDir << guts::RST << endl;
765 cout << " Geant4 Installation: " << guts::KGRN << geant4_installation() << guts::RST << endl;
766 cout << " Released on: " << guts::KGRN << grelease_date << guts::RST << endl;
767
768 // Report the plugin search path when one was provided, either through the
769 // -plugin_path option (or a plugin_path: YAML key) or the GEMC_PLUGIN_PATH
770 // environment variable.
771 string plugin_path = doesOptionExist("plugin_path")
772 ? getOptionalScalarString("plugin_path").value_or("")
773 : "";
774 const char* plugin_env = std::getenv("GEMC_PLUGIN_PATH");
775 if (!plugin_path.empty() || (plugin_env != nullptr && plugin_env[0] != '\0')) {
776 string combined = plugin_path;
777 if (plugin_env != nullptr && plugin_env[0] != '\0') {
778 if (!combined.empty()) combined += ':';
779 combined += plugin_env;
780 }
781 cout << " Plugin path: " << guts::KGRN << combined << guts::RST << endl;
782 }
783
784 cout << " GEMC Reference: " << guts::KGRN << greference << guts::RST << endl;
785 cout << " GEMC Homepage: " << guts::KGRN << gweb << guts::RST << endl;
786 cout << " Author: " << guts::KGRN << gauthor << guts::RST << endl << endl;
787 cout << asterisks << endl << endl;
788}
789
790// Operator documentation is provided in goptions.h; do not duplicate it here.
791GOptions& operator+=(GOptions& gopts, const GOptions& goptions_to_add) {
792 gopts.addGOptions(goptions_to_add);
793 return gopts;
794}
Stores one configuration option (scalar or structured), including schema defaults and current value.
Definition goption.h:120
Parses, stores, and exposes command-line options and YAML configuration values.
Definition goptions.h:47
bool getSwitch(const std::string &tag) const
Retrieves the status of a switch.
Definition goptions.cc:582
double getRequiredScalarDouble(const std::string &tag) const
Retrieves the required value of a scalar double option.
Definition goptions.cc:340
YAML::Node getOptionNode(const std::string &tag) const
Retrieves the YAML node for the specified option.
Definition goptions.h:221
void setOptionValueFromString(const std::string &optionName, const std::string &possibleYamlNode)
Updates an option value from a YAML-formatted string.
Definition goptions.cc:564
GOptions()
Default constructor.
Definition goptions.h:57
void defineOption(const GVariable &gvar, const std::string &help)
Defines and adds a scalar option.
Definition goptions.cc:285
YAML::Node getOptionMapInNode(const std::string &option_name, const std::string &map_key) const
Retrieves a map entry value from a structured option stored as a sequence of maps.
Definition goptions.cc:595
T get_variable_in_option(const YAML::Node &node, const std::string &variable_name, const T &default_value)
Retrieves a typed variable from a YAML node within an option.
Definition goptions.cc:613
bool doesOptionExist(const std::string &tag) const
Checks if an option exists.
Definition goptions.cc:476
void addGOptions(const GOptions &src)
Merges options and switches from another GOptions : into this one.
Definition goptions.h:315
std::optional< std::string > getOptionalScalarString(const std::string &tag) const
Retrieves the optional value of a scalar string option.
Definition goptions.cc:385
std::optional< double > getOptionalScalarDouble(const std::string &tag) const
Definition goptions.cc:356
std::optional< T > get_optional_variable_in_option(const YAML::Node &node, const std::string &variable_name)
Definition goptions.cc:631
std::string getRequiredScalarString(const std::string &tag) const
Retrieves the required value of a scalar string option.
Definition goptions.cc:368
int getDebugFor(const std::string &tag) const
Retrieves the debug level for the specified tag.
Definition goptions.cc:672
std::optional< int > getOptionalScalarInt(const std::string &tag) const
Definition goptions.cc:327
int getVerbosityFor(const std::string &tag) const
Retrieves the verbosity level for the specified tag.
Definition goptions.cc:658
T get_required_variable_in_option(const YAML::Node &node, const std::string &variable_name)
Definition goptions.cc:621
void defineSwitch(const std::string &name, const std::string &description, bool default_status=false)
Defines and adds a command-line switch.
Definition goptions.cc:273
std::vector< GVariable > option_verbosity_names
Schema entries used to define the verbosity and debug structured options.
Definition goptions.h:349
int getRequiredScalarInt(const std::string &tag) const
Retrieves the required value of a scalar integer option.
Definition goptions.cc:311
Represents a boolean command-line switch with a description and a status.
Definition gswitch.h:28
Conventions, constants, and error codes for the GOptions : / GOption : subsystem.
GOptions & operator+=(GOptions &gopts, const GOptions &goptions_to_add)
Overloaded operator to add options and switches from one GOptions : to another.
Definition goptions.cc:791
Public interface for GOptions : the YAML + command-line configuration manager.
constexpr int EC__NOOPTIONFOUND
Option/switch/key not found, or invalid command-line token.
constexpr int EC__DEFINED_SWITCHALREADYPRESENT
Attempted to define a switch name more than once.
constexpr int EC__BAD_CONVERSION
YAML value could not be converted to requested type.
constexpr int EC__YAML_PARSING_ERROR
YAML file failed to parse (syntax error or parser failure).
constexpr int EC__MANDATORY_NOT_FILLED
Mandatory structured option key missing.
constexpr char GVERSION_STRING[]
Reserved option tag used to store version information.
constexpr int EC__DEFINED_OPTION_ALREADY_PRESENT
Attempted to define an option name more than once.
constexpr char HELPFILLSPACE[]
Padding used when printing option/switch help.
std::filesystem::path executable_path()
string getDirFromPath(const std::string &path)
string getFileFromPath(const std::string &path)
constexpr char YELLOWHHL[]
constexpr char RST[]
constexpr char FATALERRORL[]
constexpr char RSTHHR[]
constexpr char KGRN[]
constexpr char KRED[]
constexpr char TPOINTITEM[]
constexpr char KBOLD[]
Describes a schema entry: key name, default value, and user-facing description.
Definition goption.h:35
std::string name
Variable name (option name for scalar options, schema key name for structured options).
Definition goption.h:36