Make gflags and boost::program_options play nice with each other
[folly.git] / folly / experimental / test / ProgramOptionsTestHelper.cpp
1 /*
2  * Copyright 2015 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
17 #include <iostream>
18 #include <folly/Conv.h>
19 #include <folly/experimental/ProgramOptions.h>
20 #include <glog/logging.h>
21
22 DEFINE_bool(flag_bool_true, true, "Bool with true default value");
23 DEFINE_bool(flag_bool_false, false, "Bool with false default value");
24 DEFINE_int32(flag_int, 42, "Integer flag");
25 DEFINE_string(flag_string, "foo", "String flag");
26
27 namespace po = ::boost::program_options;
28
29 namespace {
30 template <class T>
31 void print(const po::variables_map& vm, const std::string& name) {
32   auto& v = vm[name];
33   printf("%s %s\n",
34          name.c_str(),
35          folly::to<std::string>(v.as<T>()).c_str());
36 }
37 }  // namespace
38
39 int main(int argc, char *argv[]) {
40   po::options_description desc;
41   auto styleEnv = getenv("PROGRAM_OPTIONS_TEST_STYLE");
42
43   CHECK(styleEnv) << "PROGRAM_OPTIONS_TEST_STYLE is required";
44   bool gnuStyle = !strcmp(styleEnv, "GNU");
45   CHECK(gnuStyle || !strcmp(styleEnv, "GFLAGS"))
46     << "Invalid value for PROGRAM_OPTIONS_TEST_STYLE";
47
48   desc.add(getGFlags(
49       gnuStyle ? folly::ProgramOptionsStyle::GNU :
50       folly::ProgramOptionsStyle::GFLAGS));
51   desc.add_options()
52     ("help,h", "help");
53
54   po::variables_map vm;
55   auto result = folly::parseNestedCommandLine(argc, argv, desc);
56   po::store(result.options, vm);
57   po::notify(vm);
58
59   if (vm.count("help")) {
60     std::cout << desc;
61     return 1;
62   }
63
64   print<bool>(vm, gnuStyle ? "flag-bool-true" : "flag_bool_true");
65   print<bool>(vm, gnuStyle ? "flag-bool-false" : "flag_bool_false");
66   print<int32_t>(vm, gnuStyle ? "flag-int" : "flag_int");
67   print<std::string>(vm, gnuStyle ? "flag-string" : "flag_string");
68
69   if (result.command) {
70     printf("command %s\n", result.command->c_str());
71   }
72
73   for (auto& arg : result.rest) {
74     printf("arg %s\n", arg.c_str());
75   }
76
77   return 0;
78 }