config_arg.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "config_arg.hpp"
  2. namespace smartbotic::common {
  3. namespace {
  4. // Returns the value part of "--config=/etc/x.json" style arguments, or an empty
  5. // string when the argument does not carry one.
  6. std::string valueAfterEquals(const std::string& argument, const std::string& flag) {
  7. const std::string prefix = flag + "=";
  8. if (argument.rfind(prefix, 0) == 0) {
  9. return argument.substr(prefix.size());
  10. }
  11. return {};
  12. }
  13. } // namespace
  14. ConfigArg parseConfigArg(int argc, char* argv[], const std::filesystem::path& default_path) {
  15. ConfigArg result;
  16. result.path = default_path;
  17. result.explicitly_given = false;
  18. for (int i = 1; i < argc; ++i) {
  19. const std::string argument = argv[i];
  20. if (argument == "--config" || argument == "-c") {
  21. // The value is the next argument. Without one this is a malformed
  22. // command line, so leave the default in place rather than treating
  23. // the flag itself as a path.
  24. if (i + 1 < argc) {
  25. result.path = argv[i + 1];
  26. result.explicitly_given = true;
  27. ++i;
  28. }
  29. continue;
  30. }
  31. const std::string equals_value =
  32. !valueAfterEquals(argument, "--config").empty()
  33. ? valueAfterEquals(argument, "--config")
  34. : valueAfterEquals(argument, "-c");
  35. if (!equals_value.empty()) {
  36. result.path = equals_value;
  37. result.explicitly_given = true;
  38. continue;
  39. }
  40. // A bare first argument is the original calling convention and stays
  41. // supported. Anything beginning with '-' is some other flag and is not
  42. // a path.
  43. if (i == 1 && !argument.empty() && argument[0] != '-') {
  44. result.path = argument;
  45. result.explicitly_given = true;
  46. }
  47. }
  48. return result;
  49. }
  50. } // namespace smartbotic::common