Don't declare a variable for exceptions we discard
[folly.git] / folly / experimental / ProgramOptions.cpp
1 /*
2  * Copyright 2016 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 <folly/experimental/ProgramOptions.h>
18
19 #include <unordered_map>
20 #include <unordered_set>
21
22 #include <boost/version.hpp>
23 #include <glog/logging.h>
24
25 #include <folly/Conv.h>
26 #include <folly/Portability.h>
27 #include <folly/portability/GFlags.h>
28
29 namespace po = ::boost::program_options;
30
31 namespace folly {
32
33 namespace {
34
35 // Information about one GFlag. Handled via shared_ptr, as, in the case
36 // of boolean flags, two boost::program_options options (--foo and --nofoo)
37 // may share the same GFlag underneath.
38 //
39 // We're slightly abusing the boost::program_options interface; the first
40 // time we (successfully) parse a value that matches this GFlag, we'll set
41 // it and remember not to set it again; this prevents, for example, the
42 // default value of --foo from overwriting the GFlag if --nofoo is set.
43 template <class T>
44 class GFlagInfo {
45  public:
46   explicit GFlagInfo(gflags::CommandLineFlagInfo info)
47     : info_(std::move(info)),
48       isSet_(false) { }
49
50   void set(const T& value) {
51     if (isSet_) {
52       return;
53     }
54
55     auto strValue = folly::to<std::string>(value);
56     auto msg = gflags::SetCommandLineOption(
57         info_.name.c_str(),
58         strValue.c_str());
59     if (msg.empty()) {
60       throw po::invalid_option_value(strValue);
61     }
62     isSet_ = true;
63   }
64
65   T get() const {
66     std::string str;
67     CHECK(gflags::GetCommandLineOption(info_.name.c_str(), &str));
68     return folly::to<T>(str);
69   }
70
71   const gflags::CommandLineFlagInfo& info() const { return info_; }
72
73  private:
74   gflags::CommandLineFlagInfo info_;
75   bool isSet_;
76 };
77
78 template <class T>
79 class GFlagValueSemanticBase : public po::value_semantic {
80  public:
81   explicit GFlagValueSemanticBase(std::shared_ptr<GFlagInfo<T>> info)
82     : info_(std::move(info)) { }
83
84   std::string name() const override { return "arg"; }
85 #if BOOST_VERSION >= 105900
86   bool adjacent_tokens_only() const override { return false; }
87 #endif
88   bool is_composing() const override { return false; }
89   bool is_required() const override { return false; }
90   // We handle setting the GFlags from parse(), so notify() does nothing.
91   void notify(const boost::any& /* valueStore */) const override {}
92   bool apply_default(boost::any& valueStore) const override {
93     // We're using the *current* rather than *default* value here, and
94     // this is intentional; GFlags-using programs assign to FLAGS_foo
95     // before ParseCommandLineFlags() in order to change the default value,
96     // and we obey that.
97     auto val = info_->get();
98     this->transform(val);
99     valueStore = val;
100     return true;
101   }
102
103   void parse(boost::any& valueStore,
104              const std::vector<std::string>& tokens,
105              bool /* utf8 */) const override;
106
107  private:
108   virtual T parseValue(const std::vector<std::string>& tokens) const = 0;
109   virtual void transform(T& /* val */) const {}
110
111   mutable std::shared_ptr<GFlagInfo<T>> info_;
112 };
113
114 template <class T>
115 void GFlagValueSemanticBase<T>::parse(boost::any& valueStore,
116                                       const std::vector<std::string>& tokens,
117                                       bool /* utf8 */) const {
118   T val;
119   try {
120     val = this->parseValue(tokens);
121     this->transform(val);
122   } catch (const std::exception&) {
123     throw po::invalid_option_value(
124         tokens.empty() ? std::string() : tokens.front());
125   }
126   this->info_->set(val);
127   valueStore = val;
128 }
129
130 template <class T>
131 class GFlagValueSemantic : public GFlagValueSemanticBase<T> {
132  public:
133   explicit GFlagValueSemantic(std::shared_ptr<GFlagInfo<T>> info)
134     : GFlagValueSemanticBase<T>(std::move(info)) { }
135
136   unsigned min_tokens() const override { return 1; }
137   unsigned max_tokens() const override { return 1; }
138
139   T parseValue(const std::vector<std::string>& tokens) const override {
140     DCHECK(tokens.size() == 1);
141     return folly::to<T>(tokens.front());
142   }
143 };
144
145 class BoolGFlagValueSemantic : public GFlagValueSemanticBase<bool> {
146  public:
147   explicit BoolGFlagValueSemantic(std::shared_ptr<GFlagInfo<bool>> info)
148     : GFlagValueSemanticBase<bool>(std::move(info)) { }
149
150   unsigned min_tokens() const override { return 0; }
151   unsigned max_tokens() const override { return 0; }
152
153   bool parseValue(const std::vector<std::string>& tokens) const override {
154     DCHECK(tokens.empty());
155     return true;
156   }
157 };
158
159 class NegativeBoolGFlagValueSemantic : public BoolGFlagValueSemantic {
160  public:
161   explicit NegativeBoolGFlagValueSemantic(std::shared_ptr<GFlagInfo<bool>> info)
162     : BoolGFlagValueSemantic(std::move(info)) { }
163
164  private:
165   void transform(bool& val) const override {
166     val = !val;
167   }
168 };
169
170 const std::string& getName(const std::string& name) {
171   static const std::unordered_map<std::string, std::string> gFlagOverrides{
172       // Allow -v in addition to --v
173       {"v", "v,v"},
174   };
175   auto pos = gFlagOverrides.find(name);
176   return pos != gFlagOverrides.end() ? pos->second : name;
177 }
178
179 template <class T>
180 void addGFlag(gflags::CommandLineFlagInfo&& flag,
181               po::options_description& desc,
182               ProgramOptionsStyle style) {
183   auto gflagInfo = std::make_shared<GFlagInfo<T>>(std::move(flag));
184   auto& info = gflagInfo->info();
185   auto name = getName(info.name);
186
187   switch (style) {
188   case ProgramOptionsStyle::GFLAGS:
189     break;
190   case ProgramOptionsStyle::GNU:
191     std::replace(name.begin(), name.end(), '_', '-');
192     break;
193   }
194   desc.add_options()
195     (name.c_str(),
196      new GFlagValueSemantic<T>(gflagInfo),
197      info.description.c_str());
198 }
199
200 template <>
201 void addGFlag<bool>(gflags::CommandLineFlagInfo&& flag,
202                     po::options_description& desc,
203                     ProgramOptionsStyle style) {
204   auto gflagInfo = std::make_shared<GFlagInfo<bool>>(std::move(flag));
205   auto& info = gflagInfo->info();
206   auto name = getName(info.name);
207   std::string negationPrefix;
208
209   switch (style) {
210   case ProgramOptionsStyle::GFLAGS:
211     negationPrefix = "no";
212     break;
213   case ProgramOptionsStyle::GNU:
214     std::replace(name.begin(), name.end(), '_', '-');
215     negationPrefix = "no-";
216     break;
217   }
218
219   desc.add_options()
220     (name.c_str(),
221      new BoolGFlagValueSemantic(gflagInfo),
222      info.description.c_str())
223     ((negationPrefix + name).c_str(),
224      new NegativeBoolGFlagValueSemantic(gflagInfo),
225      folly::to<std::string>("(no) ", info.description).c_str());
226 }
227
228 typedef void(*FlagAdder)(gflags::CommandLineFlagInfo&&,
229                          po::options_description&,
230                          ProgramOptionsStyle);
231
232 const std::unordered_map<std::string, FlagAdder> gFlagAdders = {
233 #define X(NAME, TYPE) \
234   {NAME, addGFlag<TYPE>},
235   X("bool",   bool)
236   X("int32",  int32_t)
237   X("int64",  int64_t)
238   X("uint64", uint64_t)
239   X("double", double)
240   X("string", std::string)
241 #undef X
242 };
243
244 }  // namespace
245
246 po::options_description getGFlags(ProgramOptionsStyle style) {
247   static const std::unordered_set<std::string> gSkipFlags{
248       "flagfile",
249       "fromenv",
250       "tryfromenv",
251       "undefok",
252       "help",
253       "helpfull",
254       "helpshort",
255       "helpon",
256       "helpmatch",
257       "helppackage",
258       "helpxml",
259       "version",
260       "tab_completion_columns",
261       "tab_completion_word",
262   };
263
264   po::options_description desc("GFlags");
265
266   std::vector<gflags::CommandLineFlagInfo> allFlags;
267   gflags::GetAllFlags(&allFlags);
268
269   for (auto& f : allFlags) {
270     if (gSkipFlags.count(f.name)) {
271       continue;
272     }
273     auto pos = gFlagAdders.find(f.type);
274     CHECK(pos != gFlagAdders.end()) << "Invalid flag type: " << f.type;
275     (*pos->second)(std::move(f), desc, style);
276   }
277
278   return desc;
279 }
280
281 namespace {
282
283 NestedCommandLineParseResult doParseNestedCommandLine(
284     po::command_line_parser&& parser,
285     const po::options_description& desc) {
286   NestedCommandLineParseResult result;
287
288   result.options = parser.options(desc).allow_unregistered().run();
289
290   bool setCommand = true;
291   for (auto& opt : result.options.options) {
292     auto& tokens = opt.original_tokens;
293     auto tokensStart = tokens.begin();
294
295     if (setCommand && opt.position_key != -1) {
296       DCHECK(tokensStart != tokens.end());
297       result.command = *(tokensStart++);
298     }
299
300     if (opt.position_key != -1 || opt.unregistered) {
301       // If we see an unrecognized option before the first positional
302       // argument, assume we don't have a valid command name, because
303       // we don't know how to parse it otherwise.
304       //
305       // program --wtf foo bar
306       //
307       // Is "foo" an argument to "--wtf", or the command name?
308       setCommand = false;
309       result.rest.insert(result.rest.end(), tokensStart, tokens.end());
310     }
311   }
312
313   return result;
314 }
315
316 }  // namespace
317
318 NestedCommandLineParseResult parseNestedCommandLine(
319     int argc, const char* const argv[],
320     const po::options_description& desc) {
321   return doParseNestedCommandLine(po::command_line_parser(argc, argv), desc);
322 }
323
324 NestedCommandLineParseResult parseNestedCommandLine(
325     const std::vector<std::string>& cmdline,
326     const po::options_description& desc) {
327   return doParseNestedCommandLine(po::command_line_parser(cmdline), desc);
328 }
329
330 }  // namespaces