CommandLineParser.cpp 7.0 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "CommandLineParser.h"
#ifndef PADDLE_USE_GFLAGS
Y
Yu Yang 已提交
17
#include <stdlib.h>
Z
zhangjinchao01 已提交
18 19
#include <algorithm>
#include <iomanip>
Y
Yu Yang 已提交
20
#include <iostream>
Z
zhangjinchao01 已提交
21 22
#include <string>
#include <tuple>
Y
Yu Yang 已提交
23 24 25
#include <utility>
#include <vector>
#include "paddle/utils/StringUtil.h"
Z
zhangjinchao01 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

namespace paddle {

static constexpr int kStatusOK = 0;
static constexpr int kStatusInvalid = 1;
static constexpr int kStatusNotFound = 2;

/**
 * \brief: Convert a string to any type value.
 *
 * \note: It will specialize by type T that is supported.
 */
template <typename T>
bool StringToValue(const std::string& content, T* value) {
  bool ok;
  *value = str::toWithStatus<T>(content, &ok);
  return ok;
}

template <>
bool StringToValue<bool>(const std::string& content, bool* value) {
  std::string tmp = content;

Y
Yu Yang 已提交
49 50 51 52 53 54 55
  std::transform(tmp.begin(), tmp.end(), tmp.begin(), [](char in) -> char {
    if (in <= 'Z' && in >= 'A') {
      return in - ('Z' - 'z');
    } else {
      return in;
    }
  });  // tolower.
Z
zhangjinchao01 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

  if (tmp == "true" || tmp == "1") {
    *value = true;
    return true;
  } else if (tmp == "false" || tmp == "0") {
    *value = false;
    return true;
  } else {
    return false;
  }
}

template <>
bool StringToValue<std::string>(const std::string& content,
                                std::string* value) {
  *value = content;
  return true;
}

/**
 * \brief Parse argument "--blah=blah".
 *
 * \param argument: The command line argument string, such as "--blah=blah"
 * \param [out] extraInfo: The details error message for parse argument.
 * \return: kStatusOK, kStatusInvalid, kStatusNotFound
 */
template <typename T>
int ParseArgument(const std::string& argument, std::string* extraInfo) {
  for (auto& command :
       flags_internal::CommandLineFlagRegistry<T>::Instance()->commands) {
    std::string& name = command.name;
    T* value = command.value;

    std::string prefix = "--";
    prefix += name;
    prefix += "=";
    std::string content;
    if (str::startsWith(argument, prefix)) {
      content = argument.substr(prefix.size(), argument.size() - prefix.size());
    } else {
      prefix = "-";
      prefix += name;
      prefix += "=";
      if (str::startsWith(argument, prefix)) {
        content =
            argument.substr(prefix.size(), argument.size() - prefix.size());
      }
    }

    if (!content.empty()) {
      if (StringToValue(content, value)) {
        return kStatusOK;
      } else {
        *extraInfo = name;
        return kStatusInvalid;
      }
    }
  }
  return kStatusNotFound;
}

/**
 * @brief ParseBoolArgumentExtra
 * parse '--flag_name', '-flag_name' as true; '--noflag_name', '-noflag_name' as
 * false
 */
122 123
static int ParseBoolArgumentExtra(const std::string& argument,
                                  std::string* extraInfo) {
Z
zhangjinchao01 已提交
124 125 126 127 128 129
  (void)(extraInfo);  // unused extraInfo, just make api same.

  //! @warning: The order and content of prefixes is DESIGNED for parsing
  //! command line. The length of prefixes are 1, 2, 3, 4. The parse logic takes
  //! use of this fact. DO NOT CHANGE IT without reading how to parse command
  //! below.
130 131
  static const std::vector<std::pair<const char*, bool>> prefixes = {
      {"-", true}, {"--", true}, {"-no", false}, {"--no", false}};
Z
zhangjinchao01 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

  for (flags_internal::CommandLineFlagRegistry<bool>::Command& command :
       flags_internal::CommandLineFlagRegistry<bool>::Instance()->commands) {
    if (argument.size() > command.name.size()) {
      //! Use the length of prefix is 1, 2, 3, 4.
      size_t diff = argument.size() - command.name.size() - 1UL;
      if (diff < prefixes.size()) {
        const std::string& prefix = std::get<0>(prefixes[diff]);
        if (argument == prefix + command.name) {
          *command.value = std::get<1>(prefixes[diff]);
          return kStatusOK;
        }
      }
    }
  }
  return kStatusNotFound;
}

/**
 * \brief: Print command line arguments' usage with type T.
 */
template <typename T>
static void PrintTypeUsage() {
  for (auto& command :
       flags_internal::CommandLineFlagRegistry<T>::Instance()->commands) {
    std::string& name = command.name;
    name = "--" + name;  // Program will exit, so modify name is safe.
    std::string& desc = command.text;
    T& defaultValue = command.defaultValue;
    std::cerr << std::setw(20) << name << ": " << desc
              << "[default:" << defaultValue << "]." << std::endl;
  }
}

166
template <typename... TS>
Z
zhangjinchao01 已提交
167
static void PrintTypeUsages() {
168
  int unused[] = {0, (PrintTypeUsage<TS>(), 0)...};
Z
zhangjinchao01 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182
  (void)(unused);
}
/**
 * \brief: Print all usage, and exit(1)
 */
static void PrintUsageAndExit(const char* argv0) {
  std::cerr << "Program " << argv0 << " Flags: " << std::endl;
  PrintTypeUsages<bool, int32_t, std::string, double, int64_t, uint64_t>();
  exit(1);
}

/**
 * \brief: Print the error flags, usage, and exit.
 */
183 184
static void PrintParseError(const std::string& name,
                            const char* actualInput,
Z
zhangjinchao01 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
                            const char* arg0) {
  std::cerr << "Parse command flag " << name << " error! User input is "
            << actualInput << std::endl;
  PrintUsageAndExit(arg0);
}

void ParseCommandLineFlags(int* argc, char** argv, bool withHelp) {
  int unused_argc = 1;
  std::string extra;
  for (int i = 1; i < *argc; ++i) {
    std::string arg = argv[i];
    int s = kStatusInvalid;
#define ParseArgumentWithType(type)           \
  s = ParseArgument<type>(arg, &extra);       \
  if (s == kStatusOK) {                       \
    continue;                                 \
  } else if (s == kStatusInvalid) {           \
    PrintParseError(extra, argv[i], argv[0]); \
  }

205
    ParseArgumentWithType(bool);  // NOLINT
Z
zhangjinchao01 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
    ParseArgumentWithType(int32_t);
    ParseArgumentWithType(double);  // NOLINT
    ParseArgumentWithType(int64_t);
    ParseArgumentWithType(uint64_t);
    ParseArgumentWithType(std::string);

#undef ParseArgumentWithType
    s = ParseBoolArgumentExtra(arg, &extra);
    if (s == kStatusOK) {
      continue;
    }

    if (withHelp && (arg == "--help" || arg == "-h")) {
      PrintUsageAndExit(argv[0]);
    }

    // NOT Found for all flags.
    std::swap(argv[unused_argc++], argv[i]);
  }
  *argc = unused_argc;
}

}  // namespace paddle
#else
namespace paddle {
#ifndef GFLAGS_NS
#define GFLAGS_NS google
#endif

namespace gflags_ns = GFLAGS_NS;

void ParseCommandLineFlags(int* argc, char** argv, bool withHelp) {
  if (withHelp) {
    gflags_ns::ParseCommandLineFlags(argc, &argv, true);
  } else {
    gflags_ns::ParseCommandLineNonHelpFlags(argc, &argv, true);
  }
}

}  // namespace paddle
#endif