| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- #include "config_arg.hpp"
- namespace smartbotic::common {
- namespace {
- // Returns the value part of "--config=/etc/x.json" style arguments, or an empty
- // string when the argument does not carry one.
- std::string valueAfterEquals(const std::string& argument, const std::string& flag) {
- const std::string prefix = flag + "=";
- if (argument.rfind(prefix, 0) == 0) {
- return argument.substr(prefix.size());
- }
- return {};
- }
- } // namespace
- ConfigArg parseConfigArg(int argc, char* argv[], const std::filesystem::path& default_path) {
- ConfigArg result;
- result.path = default_path;
- result.explicitly_given = false;
- for (int i = 1; i < argc; ++i) {
- const std::string argument = argv[i];
- if (argument == "--config" || argument == "-c") {
- // The value is the next argument. Without one this is a malformed
- // command line, so leave the default in place rather than treating
- // the flag itself as a path.
- if (i + 1 < argc) {
- result.path = argv[i + 1];
- result.explicitly_given = true;
- ++i;
- }
- continue;
- }
- const std::string equals_value =
- !valueAfterEquals(argument, "--config").empty()
- ? valueAfterEquals(argument, "--config")
- : valueAfterEquals(argument, "-c");
- if (!equals_value.empty()) {
- result.path = equals_value;
- result.explicitly_given = true;
- continue;
- }
- // A bare first argument is the original calling convention and stays
- // supported. Anything beginning with '-' is some other flag and is not
- // a path.
- if (i == 1 && !argument.empty() && argument[0] != '-') {
- result.path = argument;
- result.explicitly_given = true;
- }
- }
- return result;
- }
- } // namespace smartbotic::common
|