// // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2017 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #pragma once #include "td/utils/common.h" #include "td/utils/logging.h" #include "td/utils/Slice.h" #include "td/utils/Status.h" #include "td/utils/StringBuilder.h" #include #include #if !TD_WINDOWS #include #endif namespace td { class OptionsParser { public: class Option { public: enum Type { NoArg, Arg, OptionalArg }; Type type; char short_key; std::string long_key; std::string description; std::function arg_callback; }; void set_description(std::string description) { description_ = std::move(description); } void add_option(Option::Type type, char short_key, Slice long_key, Slice description, std::function callback) { options_.push_back(Option{type, short_key, long_key.str(), description.str(), std::move(callback)}); } void add_option(char short_key, Slice long_key, Slice description, std::function callback) { add_option(Option::Type::Arg, short_key, long_key, description, std::move(callback)); } void add_option(char short_key, Slice long_key, Slice description, std::function callback) { // Ouch. There must be some better way add_option(Option::Type::NoArg, short_key, long_key, description, std::bind([](std::function &func, Slice) { return func(); }, std::move(callback), std::placeholders::_1)); } Result run(int argc, char *argv[]) TD_WARN_UNUSED_RESULT { #if TD_WINDOWS return -1; #else // use getopt. long keys are not supported for now char buff[1024]; StringBuilder sb({buff, sizeof(buff)}); for (auto &opt : options_) { CHECK(opt.type != Option::OptionalArg); sb << opt.short_key; if (opt.type == Option::Arg) { sb << ":"; } } if (sb.is_error()) { return Status::Error("Can't parse options"); } CSlice short_options = sb.as_cslice(); vector