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