2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/experimental/ProgramOptions.h>
19 #include <unordered_map>
20 #include <unordered_set>
22 #include <boost/version.hpp>
23 #include <glog/logging.h>
25 #include <folly/Conv.h>
26 #include <folly/Portability.h>
27 #include <folly/portability/GFlags.h>
29 namespace po = ::boost::program_options;
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.
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.
46 explicit GFlagInfo(gflags::CommandLineFlagInfo info)
47 : info_(std::move(info)),
50 void set(const T& value) {
55 auto strValue = folly::to<std::string>(value);
56 auto msg = gflags::SetCommandLineOption(
60 throw po::invalid_option_value(strValue);
67 CHECK(gflags::GetCommandLineOption(info_.name.c_str(), &str));
68 return folly::to<T>(str);
71 const gflags::CommandLineFlagInfo& info() const { return info_; }
74 gflags::CommandLineFlagInfo info_;
79 class GFlagValueSemanticBase : public po::value_semantic {
81 explicit GFlagValueSemanticBase(std::shared_ptr<GFlagInfo<T>> info)
82 : info_(std::move(info)) { }
84 std::string name() const override { return "arg"; }
85 #if BOOST_VERSION >= 105900
86 bool adjacent_tokens_only() const override { return false; }
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,
97 auto val = info_->get();
103 void parse(boost::any& valueStore,
104 const std::vector<std::string>& tokens,
105 bool /* utf8 */) const override;
108 virtual T parseValue(const std::vector<std::string>& tokens) const = 0;
109 virtual void transform(T& /* val */) const {}
111 mutable std::shared_ptr<GFlagInfo<T>> info_;
115 void GFlagValueSemanticBase<T>::parse(boost::any& valueStore,
116 const std::vector<std::string>& tokens,
117 bool /* utf8 */) const {
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());
126 this->info_->set(val);
131 class GFlagValueSemantic : public GFlagValueSemanticBase<T> {
133 explicit GFlagValueSemantic(std::shared_ptr<GFlagInfo<T>> info)
134 : GFlagValueSemanticBase<T>(std::move(info)) { }
136 unsigned min_tokens() const override { return 1; }
137 unsigned max_tokens() const override { return 1; }
139 T parseValue(const std::vector<std::string>& tokens) const override {
140 DCHECK(tokens.size() == 1);
141 return folly::to<T>(tokens.front());
145 class BoolGFlagValueSemantic : public GFlagValueSemanticBase<bool> {
147 explicit BoolGFlagValueSemantic(std::shared_ptr<GFlagInfo<bool>> info)
148 : GFlagValueSemanticBase<bool>(std::move(info)) { }
150 unsigned min_tokens() const override { return 0; }
151 unsigned max_tokens() const override { return 0; }
153 bool parseValue(const std::vector<std::string>& tokens) const override {
154 DCHECK(tokens.empty());
159 class NegativeBoolGFlagValueSemantic : public BoolGFlagValueSemantic {
161 explicit NegativeBoolGFlagValueSemantic(std::shared_ptr<GFlagInfo<bool>> info)
162 : BoolGFlagValueSemantic(std::move(info)) { }
165 void transform(bool& val) const override {
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
175 auto pos = gFlagOverrides.find(name);
176 return pos != gFlagOverrides.end() ? pos->second : name;
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);
188 case ProgramOptionsStyle::GFLAGS:
190 case ProgramOptionsStyle::GNU:
191 std::replace(name.begin(), name.end(), '_', '-');
196 new GFlagValueSemantic<T>(gflagInfo),
197 info.description.c_str());
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;
210 case ProgramOptionsStyle::GFLAGS:
211 negationPrefix = "no";
213 case ProgramOptionsStyle::GNU:
214 std::replace(name.begin(), name.end(), '_', '-');
215 negationPrefix = "no-";
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());
228 typedef void(*FlagAdder)(gflags::CommandLineFlagInfo&&,
229 po::options_description&,
230 ProgramOptionsStyle);
232 const std::unordered_map<std::string, FlagAdder> gFlagAdders = {
233 #define X(NAME, TYPE) \
234 {NAME, addGFlag<TYPE>},
238 X("uint64", uint64_t)
240 X("string", std::string)
246 po::options_description getGFlags(ProgramOptionsStyle style) {
247 static const std::unordered_set<std::string> gSkipFlags{
260 "tab_completion_columns",
261 "tab_completion_word",
264 po::options_description desc("GFlags");
266 std::vector<gflags::CommandLineFlagInfo> allFlags;
267 gflags::GetAllFlags(&allFlags);
269 for (auto& f : allFlags) {
270 if (gSkipFlags.count(f.name)) {
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);
283 NestedCommandLineParseResult doParseNestedCommandLine(
284 po::command_line_parser&& parser,
285 const po::options_description& desc) {
286 NestedCommandLineParseResult result;
288 result.options = parser.options(desc).allow_unregistered().run();
290 bool setCommand = true;
291 for (auto& opt : result.options.options) {
292 auto& tokens = opt.original_tokens;
293 auto tokensStart = tokens.begin();
295 if (setCommand && opt.position_key != -1) {
296 DCHECK(tokensStart != tokens.end());
297 result.command = *(tokensStart++);
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.
305 // program --wtf foo bar
307 // Is "foo" an argument to "--wtf", or the command name?
309 result.rest.insert(result.rest.end(), tokensStart, tokens.end());
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);
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);