ProgramOptionsTestHelper.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright 2015-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <iostream>
  17. #include <glog/logging.h>
  18. #include <folly/Conv.h>
  19. #include <folly/experimental/ProgramOptions.h>
  20. DEFINE_bool(flag_bool_true, true, "Bool with true default value");
  21. DEFINE_bool(flag_bool_false, false, "Bool with false default value");
  22. DEFINE_int32(flag_int, 42, "Integer flag");
  23. DEFINE_string(flag_string, "foo", "String flag");
  24. namespace po = ::boost::program_options;
  25. namespace {
  26. template <class T>
  27. void print(const po::variables_map& vm, const std::string& name) {
  28. auto& v = vm[name];
  29. printf("%s %s\n", name.c_str(), folly::to<std::string>(v.as<T>()).c_str());
  30. }
  31. } // namespace
  32. int main(int argc, char* argv[]) {
  33. po::options_description desc;
  34. auto styleEnv = getenv("PROGRAM_OPTIONS_TEST_STYLE");
  35. CHECK(styleEnv) << "PROGRAM_OPTIONS_TEST_STYLE is required";
  36. bool gnuStyle = !strcmp(styleEnv, "GNU");
  37. CHECK(gnuStyle || !strcmp(styleEnv, "GFLAGS"))
  38. << "Invalid value for PROGRAM_OPTIONS_TEST_STYLE";
  39. // clang-format off
  40. desc.add(getGFlags(
  41. gnuStyle ? folly::ProgramOptionsStyle::GNU :
  42. folly::ProgramOptionsStyle::GFLAGS));
  43. desc.add_options()
  44. ("help,h", "help");
  45. // clang-format on
  46. po::variables_map vm;
  47. auto result = folly::parseNestedCommandLine(argc, argv, desc);
  48. po::store(result.options, vm);
  49. po::notify(vm);
  50. if (vm.count("help")) {
  51. std::cout << desc;
  52. return 1;
  53. }
  54. print<bool>(vm, gnuStyle ? "flag-bool-true" : "flag_bool_true");
  55. print<bool>(vm, gnuStyle ? "flag-bool-false" : "flag_bool_false");
  56. print<int32_t>(vm, gnuStyle ? "flag-int" : "flag_int");
  57. print<std::string>(vm, gnuStyle ? "flag-string" : "flag_string");
  58. if (result.command) {
  59. printf("command %s\n", result.command->c_str());
  60. }
  61. for (auto& arg : result.rest) {
  62. printf("arg %s\n", arg.c_str());
  63. }
  64. return 0;
  65. }