| 6 |
| // You may obtain a copy of the License at |
| 7 | // |
| 8 | // https://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 | #include "absl/flags/parse.h" |
| 17 |
| 18 | #include <stdlib.h> |
| 19 |
| 20 | #include <algorithm> |
| 21 | #include <cstdint> |
| 22 | #include <cstdlib> |
| 23 | #include <fstream> |
| 24 | #include <iostream> |
| 25 | #include <ostream> |
| 26 | #include <string> |
| 27 | #include <tuple> |
| 28 | #include <utility> |
| 29 | #include <vector> |
| 30 |
| 31 | #ifdef _WIN32 |
| 32 | #include <windows.h> |
| 33 | #endif |
| 34 |
| 35 | #include "absl/algorithm/container.h" |
| 36 | #include "absl/base/attributes.h" |
| 37 | #include "absl/base/config.h" |
| 38 | #include "absl/base/no_destructor.h" |
| 39 | #include "absl/base/thread_annotations.h" |
| 40 | #include "absl/flags/commandlineflag.h" |
| 41 | #include "absl/flags/config.h" |
| 42 | #include "absl/flags/flag.h" |
| 43 | #include "absl/flags/internal/commandlineflag.h" |
| 44 | #include "absl/flags/internal/flag.h" |
| 45 | #include "absl/flags/internal/parse.h" |
| 46 | #include "absl/flags/internal/private_handle_accessor.h" |
| 47 | #include "absl/flags/internal/program_name.h" |
| 48 | #include "absl/flags/internal/usage.h" |
| 49 | #include "absl/flags/reflection.h" |
| 50 | #include "absl/flags/usage.h" |
| 51 | #include "absl/flags/usage_config.h" |
| 52 | #include "absl/strings/ascii.h" |
| 53 | #include "absl/strings/internal/damerau_levenshtein_distance.h" |
| 54 | #include "absl/strings/str_cat.h" |
| 55 | #include "absl/strings/str_join.h" |
| 56 | #include "absl/strings/string_view.h" |
| 57 | #include "absl/strings/strip.h" |
| 58 | #include "absl/synchronization/mutex.h" |
| 59 |
| 60 | // -------------------------------------------------------------------- |
| 61 |
| 62 | namespace absl { |
| 63 | ABSL_NAMESPACE_BEGIN |
| 64 | namespace flags_internal { |
| 65 | namespace { |
| 66 |
| 67 | absl::Mutex* ProcessingChecksMutex() { |
| 68 | static absl::NoDestructor<absl::Mutex> mutex; |
| 69 | return mutex.get(); |
| 70 | } |
| 71 |
| 72 | ABSL_CONST_INIT bool flagfile_needs_processing |
| 73 | ABSL_GUARDED_BY(ProcessingChecksMutex()) = false; |
| 74 | ABSL_CONST_INIT bool fromenv_needs_processing |
| 75 | ABSL_GUARDED_BY(ProcessingChecksMutex()) = false; |
| 76 | ABSL_CONST_INIT bool tryfromenv_needs_processing |
| 77 | ABSL_GUARDED_BY(ProcessingChecksMutex()) = false; |
| 78 |
| 79 | ABSL_CONST_INIT absl::Mutex specified_flags_guard(absl::kConstInit); |
| 80 | ABSL_CONST_INIT std::vector<const CommandLineFlag*>* specified_flags |
| 81 | ABSL_GUARDED_BY(specified_flags_guard) = nullptr; |
| 82 |
| 83 | // Suggesting at most kMaxHints flags in case of misspellings. |
| 84 | ABSL_CONST_INIT const size_t kMaxHints = 100; |
| 85 | // Suggesting only flags which have a smaller distance than kMaxDistance. |
| 86 | ABSL_CONST_INIT const size_t kMaxDistance = 3; |
| 87 |
| 88 | struct SpecifiedFlagsCompare { |
| 89 | bool operator()(const CommandLineFlag* a, const CommandLineFlag* b) const { |
| 90 | return a->Name() < b->Name(); |
| 91 | } |
| 92 | bool operator()(const CommandLineFlag* a, absl::string_view b) const { |
| 93 | return a->Name() < b; |
| 94 | } |
| 95 | bool operator()(absl::string_view a, const CommandLineFlag* b) const { |
| 96 | return a < b->Name(); |
| 97 | } |
| 98 | }; |
| 99 |
| 100 | } // namespace |
| 101 | } // namespace flags_internal |
| 102 | ABSL_NAMESPACE_END |
| 103 | } // namespace absl |
| 104 |
| 105 | // These flags influence how command line flags are parsed and are only intended |
| 106 | // to be set on the command line. Avoid reading or setting them from C++ code. |
| 107 | ABSL_FLAG(std::vector<std::string>, flagfile, {}, |
| 108 | "comma-separated list of files to load flags from") |
| 109 | .OnUpdate([]() { |
| 110 | if (absl::GetFlag(FLAGS_flagfile).empty()) return; |
| 111 |
| 112 | absl::MutexLock l(absl::flags_internal::ProcessingChecksMutex()); |
| 113 |
| 114 | // Setting this flag twice before it is handled most likely an internal |
| 115 | // error and should be reviewed by developers. |
| 116 | if (absl::flags_internal::flagfile_needs_processing) { |
| 117 | ABSL_INTERNAL_LOG(WARNING, "flagfile set twice before it is handled"); |
| 118 | } |
| 119 |
| 120 | absl::flags_internal::flagfile_needs_processing = true; |
| 121 | }); |
| 122 | ABSL_FLAG(std::vector<std::string>, fromenv, {}, |
| 123 | "comma-separated list of flags to set from the environment" |
| 124 | " [use 'export FLAGS_flag1=value']") |
| 125 | .OnUpdate([]() { |
| 126 | if (absl::GetFlag(FLAGS_fromenv).empty()) return; |
| 127 |
| 128 | absl::MutexLock l(absl::flags_internal::ProcessingChecksMutex()); |
| 129 |
| 130 | // Setting this flag twice before it is handled most likely an internal |
| 131 | // error and should be reviewed by developers. |
| 132 | if (absl::flags_internal::fromenv_needs_processing) { |
| 133 | ABSL_INTERNAL_LOG(WARNING, "fromenv set twice before it is handled."); |
| 134 | } |
| 135 |
| 136 | absl::flags_internal::fromenv_needs_processing = true; |
| 137 | }); |
| 138 | ABSL_FLAG(std::vector<std::string>, tryfromenv, {}, |
| 139 | "comma-separated list of flags to try to set from the environment if " |
| 140 | "present") |
| 141 | .OnUpdate([]() { |
| 142 | if (absl::GetFlag(FLAGS_tryfromenv).empty()) return; |
| 143 |
| 144 | absl::MutexLock l(absl::flags_internal::ProcessingChecksMutex()); |
| 145 |
| 146 | // Setting this flag twice before it is handled most likely an internal |
| 147 | // error and should be reviewed by developers. |
| 148 | if (absl::flags_internal::tryfromenv_needs_processing) { |
| 149 | ABSL_INTERNAL_LOG(WARNING, |
| 150 | "tryfromenv set twice before it is handled."); |
| 151 | } |
| 152 |
| 153 | absl::flags_internal::tryfromenv_needs_processing = true; |
| 154 | }); |
| 155 |
| 156 | // Rather than reading or setting --undefok from C++ code, please consider using |
| 157 | // ABSL_RETIRED_FLAG instead. |
| 158 | ABSL_FLAG(std::vector<std::string>, undefok, {}, |
| 159 | "comma-separated list of flag names that it is okay to specify " |
| 160 | "on the command line even if the program does not define a flag " |
| 161 | "with that name"); |
| 162 |
| 163 | namespace absl { |
| 164 | ABSL_NAMESPACE_BEGIN |
| 165 | namespace flags_internal { |
| 166 |
| 167 | namespace { |
| 168 |
| 169 | class ArgsList { |
| 170 | public: |
| 171 | ArgsList() : next_arg_(0) {} |
| 172 | ArgsList(int argc, char* argv[]) : args_(argv, argv + argc), next_arg_(0) {} |
| 173 | explicit ArgsList(const std::vector<std::string>& args) |
| 174 | : args_(args), next_arg_(0) {} |
| 175 |
| 176 | // Returns success status: true if parsing successful, false otherwise. |
| 177 | bool ReadFromFlagfile(const std::string& flag_file_name); |
| 178 |
| 179 | size_t Size() const { return args_.size() - next_arg_; } |
| 180 | size_t FrontIndex() const { return next_arg_; } |
| 181 | absl::string_view Front() const { return args_[next_arg_]; } |
| 182 | void PopFront() { next_arg_++; } |
| 183 |
| 184 | private: |
| 185 | std::vector<std::string> args_; |
| 186 | size_t next_arg_; |
| 187 | }; |
| 188 |
| 189 | bool ArgsList::ReadFromFlagfile(const std::string& flag_file_name) { |
| 190 | std::ifstream flag_file(flag_file_name); |
| 191 |
| 192 | if (!flag_file) { |
| 193 | flags_internal::ReportUsageError( |
| 194 | absl::StrCat("Can't open flagfile ", flag_file_name), true); |
| 195 |
| 196 | return false; |
| 197 | } |
| 198 |
| 199 | // This argument represents fake argv[0], which should be present in all arg |
| 200 | // lists. |
| 201 | args_.emplace_back(""); |
| 202 |
| 203 | std::string line; |
| 204 | bool success = true; |
| 205 |
| 206 | while (std::getline(flag_file, line)) { |
| 207 | absl::string_view stripped = absl::StripLeadingAsciiWhitespace(line); |
| 208 |
| 209 | if (stripped.empty() || stripped[0] == '#') { |
| 210 | // Comment or empty line; just ignore. |
| 211 | continue; |
| 212 | } |
| 213 |
| 214 | if (stripped[0] == '-') { |
| 215 | if (stripped == "--") { |
| 216 | flags_internal::ReportUsageError( |
| 217 | "Flagfile can't contain position arguments or --", true); |
| 218 |
| 219 | success = false; |
| 220 | break; |
| 221 | } |
| 222 |
| 223 | args_.emplace_back(stripped); |
| 224 | continue; |
| 225 | } |
| 226 |
| 227 | flags_internal::ReportUsageError( |
| 228 | absl::StrCat("Unexpected line in the flagfile ", flag_file_name, ": ", |
| 229 | line), |
| 230 | true); |
| 231 |
| 232 | success = false; |
| 233 | } |
| 234 |
| 235 | return success; |
| 236 | } |
| 237 |
| 238 | // -------------------------------------------------------------------- |
| 239 |
| 240 | // Reads the environment variable with name `name` and stores results in |
| 241 | // `value`. If variable is not present in environment returns false, otherwise |
| 242 | // returns true. |
| 243 | bool GetEnvVar(const char* var_name, std::string& var_value) { |
| 244 | #ifdef _WIN32 |
| 245 | char buf[1024]; |
| 246 | auto get_res = GetEnvironmentVariableA(var_name, buf, sizeof(buf)); |
| 247 | if (get_res >= sizeof(buf)) { |
| 248 | return false; |
| 249 | } |
| 250 |
| 251 | if (get_res == 0) { |
| 252 | return false; |
| 253 | } |
| 254 |
| 255 | var_value = std::string(buf, get_res); |
| 256 | #else |
| 257 | const char* val = ::getenv(var_name); |
| 258 | if (val == nullptr) { |
| 259 | return false; |
| 260 | } |
| 261 |
| 262 | var_value = val; |
| 263 | #endif |
| 264 |
| 265 | return true; |
| 266 | } |
| 267 |
| 268 | // -------------------------------------------------------------------- |
| 269 |
| 270 | // Returns: |
| 271 | // Flag name or empty if arg= -- |
| 272 | // Flag value after = in --flag=value (empty if --foo) |
| 273 | // "Is empty value" status. True if arg= --foo=, false otherwise. This is |
| 274 | // required to separate --foo from --foo=. |
| 275 | // For example: |
| 276 | // arg return values |
| 277 | // "--foo=bar" -> {"foo", "bar", false}. |
| 278 | // "--foo" -> {"foo", "", false}. |
| 279 | // "--foo=" -> {"foo", "", true}. |
| 280 | std::tuple<absl::string_view, absl::string_view, bool> SplitNameAndValue( |
| 281 | absl::string_view arg) { |
| 282 | // Allow -foo and --foo |
| 283 | absl::ConsumePrefix(&arg, "-"); |
| 284 |
| 285 | if (arg.empty()) { |
| 286 | return std::make_tuple("", "", false); |
| 287 | } |
| 288 |
| 289 | auto equal_sign_pos = arg.find('='); |
| 290 |
| 291 | absl::string_view flag_name = arg.substr(0, equal_sign_pos); |
| 292 |
| 293 | absl::string_view value; |
| 294 | bool is_empty_value = false; |
| 295 |
| 296 | if (equal_sign_pos != absl::string_view::npos) { |
| 297 | value = arg.substr(equal_sign_pos + 1); |
| 298 | is_empty_value = value.empty(); |
| 299 | } |
| 300 |
| 301 | return std::make_tuple(flag_name, value, is_empty_value); |
| 302 | } |
| 303 |
| 304 | // -------------------------------------------------------------------- |
| 305 |
| 306 | // Returns: |
| 307 | // found flag or nullptr |
| 308 | // is negative in case of --nofoo |
| 309 | std::tuple<CommandLineFlag*, bool> LocateFlag(absl::string_view flag_name) { |
| 310 | CommandLineFlag* flag = absl::FindCommandLineFlag(flag_name); |
| 311 | bool is_negative = false; |
| 312 |
| 313 | if (!flag && absl::ConsumePrefix(&flag_name, "no")) { |
| 314 | flag = absl::FindCommandLineFlag(flag_name); |
| 315 | is_negative = true; |
| 316 | } |
| 317 |
| 318 | return std::make_tuple(flag, is_negative); |
| 319 | } |
| 320 |
| 321 | // -------------------------------------------------------------------- |
| 322 |
| 323 | // Verify that default values of typed flags must be convertible to string and |
| 324 | // back. |
| 325 | void CheckDefaultValuesParsingRoundtrip() { |
| 326 | #ifndef NDEBUG |
| 327 | flags_internal::ForEachFlag([&](CommandLineFlag& flag) { |
| 328 | if (flag.IsRetired()) return; |
| 329 |
| 330 | #define ABSL_FLAGS_INTERNAL_IGNORE_TYPE(T, _) \ |
| 331 | if (flag.IsOfType<T>()) return; |
| 332 |
| 333 | ABSL_FLAGS_INTERNAL_SUPPORTED_TYPES(ABSL_FLAGS_INTERNAL_IGNORE_TYPE) |
| 334 | #undef ABSL_FLAGS_INTERNAL_IGNORE_TYPE |
| 335 |
| 336 | flags_internal::PrivateHandleAccessor::CheckDefaultValueParsingRoundtrip( |
| 337 | flag); |
| 338 | }); |
| 339 | #endif |
| 340 | } |
| 341 |
| 342 | // -------------------------------------------------------------------- |
| 343 |
| 344 | // Returns success status, which is true if we successfully read all flag files, |
| 345 | // in which case new ArgLists are appended to the input_args in a reverse order |
| 346 | // of file names in the input flagfiles list. This order ensures that flags from |
| 347 | // the first flagfile in the input list are processed before the second flagfile |
| 348 | // etc. |
| 349 | bool ReadFlagfiles(const std::vector<std::string>& flagfiles, |
| 350 | std::vector<ArgsList>& input_args) { |
| 351 | bool success = true; |
| 352 | for (auto it = flagfiles.rbegin(); it != flagfiles.rend(); ++it) { |
| 353 | ArgsList al; |
| 354 |
| 355 | if (al.ReadFromFlagfile(*it)) { |
| 356 | input_args.push_back(al); |
| 357 | } else { |
| 358 | success = false; |
| 359 | } |
| 360 | } |
| 361 |
| 362 | return success; |
| 363 | } |
| 364 |
| 365 | // Returns success status, which is true if were able to locate all environment |
| 366 | // variables correctly or if fail_on_absent_in_env is false. The environment |
| 367 | // variable names are expected to be of the form `FLAGS_<flag_name>`, where |
| 368 | // `flag_name` is a string from the input flag_names list. If successful we |
| 369 | // append a single ArgList at the end of the input_args. |
| 370 | bool ReadFlagsFromEnv(const std::vector<std::string>& flag_names, |
| 371 | std::vector<ArgsList>& input_args, |
| 372 | bool fail_on_absent_in_env) { |
| 373 | bool success = true; |
| 374 | std::vector<std::string> args; |
| 375 |
| 376 | // This argument represents fake argv[0], which should be present in all arg |
| 377 | // lists. |
| 378 | args.emplace_back(""); |
| 379 |
| 380 | for (const auto& flag_name : flag_names) { |
| 381 | // Avoid infinite recursion. |
| 382 | if (flag_name == "fromenv" || flag_name == "tryfromenv") { |
| 383 | flags_internal::ReportUsageError( |
| 384 | absl::StrCat("Infinite recursion on flag ", flag_name), true); |
| 385 |
| 386 | success = false; |
| 387 | continue; |
| 388 | } |
| 389 |
| 390 | const std::string envname = absl::StrCat("FLAGS_", flag_name); |
| 391 | std::string envval; |
| 392 | if (!GetEnvVar(envname.c_str(), envval)) { |
| 393 | if (fail_on_absent_in_env) { |
| 394 | flags_internal::ReportUsageError( |
| 395 | absl::StrCat(envname, " not found in environment"), true); |
| 396 |
| 397 | success = false; |
| 398 | } |
| 399 |
| 400 | continue; |
| 401 | } |
| 402 |
| 403 | args.push_back(absl::StrCat("--", flag_name, "=", envval)); |
| 404 | } |
| 405 |
| 406 | if (success) { |
| 407 | input_args.emplace_back(args); |
| 408 | } |
| 409 |
| 410 | return success; |
| 411 | } |
| 412 |
| 413 | // -------------------------------------------------------------------- |
| 414 |
| 415 | // Returns success status, which is true if were able to handle all generator |
| 416 | // flags (flagfile, fromenv, tryfromemv) successfully. |
| 417 | bool HandleGeneratorFlags(std::vector<ArgsList>& input_args, |
| 418 | std::vector<std::string>& flagfile_value) { |
| 419 | bool success = true; |
| 420 |
| 421 | absl::MutexLock l(flags_internal::ProcessingChecksMutex()); |
| 422 |
| 423 | // flagfile could have been set either on a command line or |
| 424 | // programmatically before invoking ParseCommandLine. Note that we do not |
| 425 | // actually process arguments specified in the flagfile, but instead |
| 426 | // create a secondary arguments list to be processed along with the rest |
| 427 | // of the command line arguments. Since we always the process most recently |
| 428 | // created list of arguments first, this will result in flagfile argument |
| 429 | // being processed before any other argument in the command line. If |
| 430 | // FLAGS_flagfile contains more than one file name we create multiple new |
| 431 | // levels of arguments in a reverse order of file names. Thus we always |
| 432 | // process arguments from first file before arguments containing in a |
| 433 | // second file, etc. If flagfile contains another |
| 434 | // --flagfile inside of it, it will produce new level of arguments and |
| 435 | // processed before the rest of the flagfile. We are also collecting all |
| 436 | // flagfiles set on original command line. Unlike the rest of the flags, |
| 437 | // this flag can be set multiple times and is expected to be handled |
| 438 | // multiple times. We are collecting them all into a single list and set |
| 439 | // the value of FLAGS_flagfile to that value at the end of the parsing. |
| 440 | if (flags_internal::flagfile_needs_processing) { |
| 441 | auto flagfiles = absl::GetFlag(FLAGS_flagfile); |
| 442 |
| 443 | if (input_args.size() == 1) { |
| 444 | flagfile_value.insert(flagfile_value.end(), flagfiles.begin(), |
| 445 | flagfiles.end()); |
| 446 | } |
| 447 |
| 448 | success &= ReadFlagfiles(flagfiles, input_args); |
| 449 |
| 450 | flags_internal::flagfile_needs_processing = false; |
| 451 | } |
| 452 |
| 453 | // Similar to flagfile fromenv/tryfromemv can be set both |
| 454 | // programmatically and at runtime on a command line. Unlike flagfile these |
| 455 | // can't be recursive. |
| 456 | if (flags_internal::fromenv_needs_processing) { |
| 457 | auto flags_list = absl::GetFlag(FLAGS_fromenv); |
| 458 |
| 459 | success &= ReadFlagsFromEnv(flags_list, input_args, true); |
| 460 |
| 461 | flags_internal::fromenv_needs_processing = false; |
| 462 | } |
| 463 |
| 464 | if (flags_internal::tryfromenv_needs_processing) { |
| 465 | auto flags_list = absl::GetFlag(FLAGS_tryfromenv); |
| 466 |
| 467 | success &= ReadFlagsFromEnv(flags_list, input_args, false); |
| 468 |
| 469 | flags_internal::tryfromenv_needs_processing = false; |
| 470 | } |
| 471 |
| 472 | return success; |
| 473 | } |
| 474 |
| 475 | // -------------------------------------------------------------------- |
| 476 |
| 477 | void ResetGeneratorFlags(const std::vector<std::string>& flagfile_value) { |
| 478 | // Setting flagfile to the value which collates all the values set on a |
| 479 | // command line and programmatically. So if command line looked like |
| 480 | // --flagfile=f1 --flagfile=f2 the final value of the FLAGS_flagfile flag is |
| 481 | // going to be {"f1", "f2"} |
| 482 | if (!flagfile_value.empty()) { |
| 483 | absl::SetFlag(&FLAGS_flagfile, flagfile_value); |
| 484 | absl::MutexLock l(flags_internal::ProcessingChecksMutex()); |
| 485 | flags_internal::flagfile_needs_processing = false; |
| 486 | } |
| 487 |
| 488 | // fromenv/tryfromenv are set to <undefined> value. |
| 489 | if (!absl::GetFlag(FLAGS_fromenv).empty()) { |
| 490 | absl::SetFlag(&FLAGS_fromenv, {}); |
| 491 | } |
| 492 | if (!absl::GetFlag(FLAGS_tryfromenv).empty()) { |
| 493 | absl::SetFlag(&FLAGS_tryfromenv, {}); |
| 494 | } |
| 495 |
| 496 | absl::MutexLock l(flags_internal::ProcessingChecksMutex()); |
| 497 | flags_internal::fromenv_needs_processing = false; |
| 498 | flags_internal::tryfromenv_needs_processing = false; |
| 499 | } |
| 500 |
| 501 | // -------------------------------------------------------------------- |
| 502 |
| 503 | // Returns: |
| 504 | // success status |
| 505 | // deduced value |
| 506 | // We are also mutating curr_list in case if we need to get a hold of next |
| 507 | // argument in the input. |
| 508 | std::tuple<bool, absl::string_view> DeduceFlagValue(const CommandLineFlag& flag, |
| 509 | absl::string_view value, |
| 510 | bool is_negative, |
| 511 | bool is_empty_value, |
| 512 | ArgsList* curr_list) { |
| 513 | // Value is either an argument suffix after `=` in "--foo=<value>" |
| 514 | // or separate argument in case of "--foo" "<value>". |
| 515 |
| 516 | // boolean flags have these forms: |
| 517 | // --foo |
| 518 | // --nofoo |
| 519 | // --foo=true |
| 520 | // --foo=false |
| 521 | // --nofoo=<value> is not supported |
| 522 | // --foo <value> is not supported |
| 523 |
| 524 | // non boolean flags have these forms: |
| 525 | // --foo=<value> |
| 526 | // --foo <value> |
| 527 | // --nofoo is not supported |
| 528 |
| 529 | if (flag.IsOfType<bool>()) { |
| 530 | if (value.empty()) { |
| 531 | if (is_empty_value) { |
| 532 | // "--bool_flag=" case |
| 533 | flags_internal::ReportUsageError( |
| 534 | absl::StrCat( |
| 535 | "Missing the value after assignment for the boolean flag '", |
| 536 | flag.Name(), "'"), |
| 537 | true); |
| 538 | return std::make_tuple(false, ""); |
| 539 | } |
| 540 |
| 541 | // "--bool_flag" case |
| 542 | value = is_negative ? "0" : "1"; |
| 543 | } else if (is_negative) { |
| 544 | // "--nobool_flag=Y" case |
| 545 | flags_internal::ReportUsageError( |
| 546 | absl::StrCat("Negative form with assignment is not valid for the " |
| 547 | "boolean flag '", |
| 548 | flag.Name(), "'"), |
| 549 | true); |
| 550 | return std::make_tuple(false, ""); |
| 551 | } |
| 552 | } else if (is_negative) { |
| 553 | // "--noint_flag=1" case |
| 554 | flags_internal::ReportUsageError( |
| 555 | absl::StrCat("Negative form is not valid for the flag '", flag.Name(), |
| 556 | "'"), |
| 557 | true); |
| 558 | return std::make_tuple(false, ""); |
| 559 | } else if (value.empty() && (!is_empty_value)) { |
| 560 | if (curr_list->Size() == 1) { |
| 561 | // "--int_flag" case |
| 562 | flags_internal::ReportUsageError( |
| 563 | absl::StrCat("Missing the value for the flag '", flag.Name(), "'"), |
| 564 | true); |
| 565 | return std::make_tuple(false, ""); |
| 566 | } |
| 567 |
| 568 | // "--int_flag" "10" case |
| 569 | curr_list->PopFront(); |
| 570 | value = curr_list->Front(); |
| 571 |
| 572 | // Heuristic to detect the case where someone treats a string arg |
| 573 | // like a bool or just forgets to pass a value: |
| 574 | // --my_string_var --foo=bar |
| 575 | // We look for a flag of string type, whose value begins with a |
| 576 | // dash and corresponds to known flag or standalone --. |
| 577 | if (!value.empty() && value[0] == '-' && flag.IsOfType<std::string>()) { |
| 578 | auto maybe_flag_name = std::get<0>(SplitNameAndValue(value.substr(1))); |
| 579 |
| 580 | if (maybe_flag_name.empty() || |
| 581 | std::get<0>(LocateFlag(maybe_flag_name)) != nullptr) { |
| 582 | // "--string_flag" "--known_flag" case |
| 583 | ABSL_INTERNAL_LOG( |
| 584 | WARNING, |
| 585 | absl::StrCat("Did you really mean to set flag '", flag.Name(), |
| 586 | "' to the value '", value, "'?")); |
| 587 | } |
| 588 | } |
| 589 | } |
| 590 |
| 591 | return std::make_tuple(true, value); |
| 592 | } |
| 593 |
| 594 | // -------------------------------------------------------------------- |
| 595 |
| 596 | bool CanIgnoreUndefinedFlag(absl::string_view flag_name) { |
| 597 | auto undefok = absl::GetFlag(FLAGS_undefok); |
| 598 | if (std::find(undefok.begin(), undefok.end(), flag_name) != undefok.end()) { |
| 599 | return true; |
| 600 | } |
| 601 |
| 602 | if (absl::ConsumePrefix(&flag_name, "no") && |
| 603 | std::find(undefok.begin(), undefok.end(), flag_name) != undefok.end()) { |
| 604 | return true; |
| 605 | } |
| 606 |
| 607 | return false; |
| 608 | } |
| 609 |
| 610 | // -------------------------------------------------------------------- |
| 611 |
| 612 | void ReportUnrecognizedFlags( |
| 613 | const std::vector<UnrecognizedFlag>& unrecognized_flags, |
| 614 | bool report_as_fatal_error) { |
| 615 | for (const auto& unrecognized : unrecognized_flags) { |
| 616 | // Verify if flag_name has the "no" already removed |
| 617 | std::vector<std::string> misspelling_hints; |
| 618 | if (unrecognized.source == UnrecognizedFlag::kFromArgv) { |
| 619 | misspelling_hints = |
| 620 | flags_internal::GetMisspellingHints(unrecognized.flag_name); |
| 621 | } |
| 622 |
| 623 | if (misspelling_hints.empty()) { |
| 624 | flags_internal::ReportUsageError( |
| 625 | absl::StrCat("Unknown command line flag '", unrecognized.flag_name, |
| 626 | "'"), |
| 627 | report_as_fatal_error); |
| 628 | } else { |
| 629 | flags_internal::ReportUsageError( |
| 630 | absl::StrCat("Unknown command line flag '", unrecognized.flag_name, |
| 631 | "'. Did you mean: ", |
| 632 | absl::StrJoin(misspelling_hints, ", "), " ?"), |
| 633 | report_as_fatal_error); |
| 634 | } |
| 635 | } |
| 636 | } |
| 637 |
| 638 | } // namespace |
| 639 |
| 640 | // -------------------------------------------------------------------- |
| 641 |
| 642 | bool WasPresentOnCommandLine(absl::string_view flag_name) { |
| 643 | absl::ReaderMutexLock l(&specified_flags_guard); |
| 644 | ABSL_INTERNAL_CHECK(specified_flags != nullptr, |
| 645 | "ParseCommandLine is not invoked yet"); |
| 646 |
| 647 | return std::binary_search(specified_flags->begin(), specified_flags->end(), |
| 648 | flag_name, SpecifiedFlagsCompare{}); |
| 649 | } |
| 650 |
| 651 | // -------------------------------------------------------------------- |
| 652 |
| 653 | struct BestHints { |
| 654 | explicit BestHints(uint8_t _max) : best_distance(_max + 1) {} |
| 655 | bool AddHint(absl::string_view hint, uint8_t distance) { |
| 656 | if (hints.size() >= kMaxHints) return false; |
| 657 | if (distance == best_distance) { |
| 658 | hints.emplace_back(hint); |
| 659 | } |
| 660 | if (distance < best_distance) { |
| 661 | best_distance = distance; |
| 662 | hints = std::vector<std::string>{std::string(hint)}; |
| 663 | } |
| 664 | return true; |
| 665 | } |
| 666 |
| 667 | uint8_t best_distance; |
| 668 | std::vector<std::string> hints; |
| 669 | }; |
| 670 |
| 671 | // Return the list of flags with the smallest Damerau-Levenshtein distance to |
| 672 | // the given flag. |
| 673 | std::vector<std::string> GetMisspellingHints(const absl::string_view flag) { |
| 674 | const size_t maxCutoff = std::min(flag.size() / 2 + 1, kMaxDistance); |
| 675 | auto undefok = absl::GetFlag(FLAGS_undefok); |
| 676 | BestHints best_hints(static_cast<uint8_t>(maxCutoff)); |
| 677 | flags_internal::ForEachFlag([&](const CommandLineFlag& f) { |
| 678 | if (best_hints.hints.size() >= kMaxHints) return; |
| 679 | uint8_t distance = strings_internal::CappedDamerauLevenshteinDistance( |
| 680 | flag, f.Name(), best_hints.best_distance); |
| 681 | best_hints.AddHint(f.Name(), distance); |
| 682 | // For boolean flags, also calculate distance to the negated form. |
| 683 | if (f.IsOfType<bool>()) { |
| 684 | const std::string negated_flag = absl::StrCat("no", f.Name()); |
| 685 | distance = strings_internal::CappedDamerauLevenshteinDistance( |
| 686 | flag, negated_flag, best_hints.best_distance); |
| 687 | best_hints.AddHint(negated_flag, distance); |
| 688 | } |
| 689 | }); |
| 690 | // Finally calculate distance to flags in "undefok". |
| 691 | absl::c_for_each(undefok, [&](const absl::string_view f) { |
| 692 | if (best_hints.hints.size() >= kMaxHints) return; |
| 693 | uint8_t distance = strings_internal::CappedDamerauLevenshteinDistance( |
| 694 | flag, f, best_hints.best_distance); |
| 695 | best_hints.AddHint(absl::StrCat(f, " (undefok)"), distance); |
| 696 | }); |
| 697 | return best_hints.hints; |
| 698 | } |
| 699 |
| 700 | // -------------------------------------------------------------------- |
| 701 |
| 702 | std::vector<char*> ParseCommandLineImpl(int argc, char* argv[], |
| 703 | UsageFlagsAction usage_flag_action, |
| 704 | OnUndefinedFlag undef_flag_action, |
| 705 | std::ostream& error_help_output) { |
| 706 | std::vector<char*> positional_args; |
| 707 | std::vector<UnrecognizedFlag> unrecognized_flags; |
| 708 |
| 709 | auto help_mode = flags_internal::ParseAbseilFlagsOnlyImpl( |
| 710 | argc, argv, positional_args, unrecognized_flags, usage_flag_action); |
| 711 |
| 712 | if (undef_flag_action != OnUndefinedFlag::kIgnoreUndefined) { |
| 713 | flags_internal::ReportUnrecognizedFlags( |
| 714 | unrecognized_flags, |
| 715 | (undef_flag_action == OnUndefinedFlag::kAbortIfUndefined)); |
| 716 |
| 717 | if (undef_flag_action == OnUndefinedFlag::kAbortIfUndefined) { |
| 718 | if (!unrecognized_flags.empty()) { |
| 719 | flags_internal::HandleUsageFlags(error_help_output, |
| 720 | ProgramUsageMessage()); std::exit(1); |
| 721 | } |
| 722 | } |
| 723 | } |
| 724 |
| 725 | flags_internal::MaybeExit(help_mode); |
| 726 |
| 727 | return positional_args; |
| 728 | } |
| 729 |
| 730 | // -------------------------------------------------------------------- |
| 731 |
| 732 | // This function handles all Abseil Flags and built-in usage flags and, if any |
| 733 | // help mode was handled, it returns that help mode. The caller of this function |
| 734 | // can decide to exit based on the returned help mode. |
| 735 | // The caller may decide to handle unrecognized positional arguments and |
| 736 | // unrecognized flags first before exiting. |
| 737 | // |
| 738 | // Returns: |
| 739 | // * HelpMode::kFull if parsing errors were detected in recognized arguments |
| 740 | // * The HelpMode that was handled in case when `usage_flag_action` is |
| 741 | // UsageFlagsAction::kHandleUsage and a usage flag was specified on the |
| 742 | // commandline |
| 743 | // * Otherwise it returns HelpMode::kNone |
| 744 | HelpMode ParseAbseilFlagsOnlyImpl( |
| 745 | int argc, char* argv[], std::vector<char*>& positional_args, |
| 746 | std::vector<UnrecognizedFlag>& unrecognized_flags, |
| 747 | UsageFlagsAction usage_flag_action) { |
| 748 | ABSL_INTERNAL_CHECK(argc > 0, "Missing argv[0]"); |
| 749 |
| 750 | using flags_internal::ArgsList; |
| 751 | using flags_internal::specified_flags; |
| 752 |
| 753 | std::vector<std::string> flagfile_value; |
| 754 | std::vector<ArgsList> input_args; |
| 755 |
| 756 | // Once parsing has started we will not allow more flag registrations. |
| 757 | flags_internal::FinalizeRegistry(); |
| 758 |
| 759 | // This routine does not return anything since we abort on failure. |
| 760 | flags_internal::CheckDefaultValuesParsingRoundtrip(); |
| 761 |
| 762 | input_args.push_back(ArgsList(argc, argv)); |
| 763 |
| 764 | // Set program invocation name if it is not set before. |
| 765 | if (flags_internal::ProgramInvocationName() == "UNKNOWN") { |
| 766 | flags_internal::SetProgramInvocationName(argv[0]); |
| 767 | } |
| 768 | positional_args.push_back(argv[0]); |
| 769 |
| 770 | absl::MutexLock l(&flags_internal::specified_flags_guard); |
| 771 | if (specified_flags == nullptr) { |
| 772 | specified_flags = new std::vector<const CommandLineFlag*>; |
| 773 | } else { |
| 774 | specified_flags->clear(); |
| 775 | } |
| 776 |
| 777 | // Iterate through the list of the input arguments. First level are |
| 778 | // arguments originated from argc/argv. Following levels are arguments |
| 779 | // originated from recursive parsing of flagfile(s). |
| 780 | bool success = true; |
| 781 | while (!input_args.empty()) { |
| 782 | // First we process the built-in generator flags. |
| 783 | success &= flags_internal::HandleGeneratorFlags(input_args, flagfile_value); |
| 784 |
| 785 | // Select top-most (most recent) arguments list. If it is empty drop it |
| 786 | // and re-try. |
| 787 | ArgsList& curr_list = input_args.back(); |
| 788 |
| 789 | // Every ArgsList starts with real or fake program name, so we can always |
| 790 | // start by skipping it. |
| 791 | curr_list.PopFront(); |
| 792 |
| 793 | if (curr_list.Size() == 0) { |
| 794 | input_args.pop_back(); |
| 795 | continue; |
| 796 | } |
| 797 |
| 798 | // Handle the next argument in the current list. If the stack of argument |
| 799 | // lists contains only one element - we are processing an argument from |
| 800 | // the original argv. |
| 801 | absl::string_view arg(curr_list.Front()); |
| 802 | bool arg_from_argv = input_args.size() == 1; |
| 803 |
| 804 | // If argument does not start with '-' or is just "-" - this is |
| 805 | // positional argument. |
| 806 | if (!absl::ConsumePrefix(&arg, "-") || arg.empty()) { |
| 807 | ABSL_INTERNAL_CHECK(arg_from_argv, |
| 808 | "Flagfile cannot contain positional argument"); |
| 809 |
| 810 | positional_args.push_back(argv[curr_list.FrontIndex()]); |
| 811 | continue; |
| 812 | } |
| 813 |
| 814 | // Split the current argument on '=' to deduce the argument flag name and |
| 815 | // value. If flag name is empty it means we've got an "--" argument. Value |
| 816 | // can be empty either if there were no '=' in argument string at all or |
| 817 | // an argument looked like "--foo=". In a latter case is_empty_value is |
| 818 | // true. |
| 819 | absl::string_view flag_name; |
| 820 | absl::string_view value; |
| 821 | bool is_empty_value = false; |
| 822 |
| 823 | std::tie(flag_name, value, is_empty_value) = |
| 824 | flags_internal::SplitNameAndValue(arg); |
| 825 |
| 826 | // Standalone "--" argument indicates that the rest of the arguments are |
| 827 | // positional. We do not support positional arguments in flagfiles. |
| 828 | if (flag_name.empty()) { |
| 829 | ABSL_INTERNAL_CHECK(arg_from_argv, |
| 830 | "Flagfile cannot contain positional argument"); |
| 831 |
| 832 | curr_list.PopFront(); |
| 833 | break; |
| 834 | } |
| 835 |
| 836 | // Locate the flag based on flag name. Handle both --foo and --nofoo. |
| 837 | CommandLineFlag* flag = nullptr; |
| 838 | bool is_negative = false; |
| 839 | std::tie(flag, is_negative) = flags_internal::LocateFlag(flag_name); |
| 840 |
| 841 | if (flag == nullptr) { |
| 842 | // Usage flags are not modeled as Abseil flags. Locate them separately. |
| 843 | if (flags_internal::DeduceUsageFlags(flag_name, value)) { |
| 844 | continue; |
| 845 | } |
| 846 | unrecognized_flags.emplace_back(arg_from_argv |
| 847 | ? UnrecognizedFlag::kFromArgv |
| 848 | : UnrecognizedFlag::kFromFlagfile, |
| 849 | flag_name); |
| 850 | continue; |
| 851 | } |
| 852 |
| 853 | // Deduce flag's value (from this or next argument). |
| 854 | bool value_success = true; |
| 855 | std::tie(value_success, value) = flags_internal::DeduceFlagValue( |
| 856 | *flag, value, is_negative, is_empty_value, &curr_list); |
| 857 | success &= value_success; |
| 858 |
| 859 | // Set the located flag to a new value, unless it is retired. Setting |
| 860 | // retired flag fails, but we ignoring it here while also reporting access |
| 861 | // to retired flag. |
| 862 | std::string error; |
| 863 | if (!flags_internal::PrivateHandleAccessor::ParseFrom( |
| 864 | *flag, value, flags_internal::SET_FLAGS_VALUE, |
| 865 | flags_internal::kCommandLine, error)) { |
| 866 | if (flag->IsRetired()) continue; |
| 867 |
| 868 | flags_internal::ReportUsageError(error, true); |
| 869 | success = false; |
| 870 | } else { |
| 871 | specified_flags->push_back(flag); |
| 872 | } |
| 873 | } |
| 874 |
| 875 | flags_internal::ResetGeneratorFlags(flagfile_value); |
| 876 |
| 877 | // All the remaining arguments are positional. |
| 878 | if (!input_args.empty()) { |
| 879 | for (size_t arg_index = input_args.back().FrontIndex(); |
| 880 | arg_index < static_cast<size_t>(argc); ++arg_index) { |
| 881 | positional_args.push_back(argv[arg_index]); |
| 882 | } |
| 883 | } |
| 884 |
| 885 | // Trim and sort the vector. |
| 886 | specified_flags->shrink_to_fit(); |
| 887 | std::sort(specified_flags->begin(), specified_flags->end(), |
| 888 | flags_internal::SpecifiedFlagsCompare{}); |
| 889 |
| 890 | // Filter out unrecognized flags, which are ok to ignore. |
| 891 | std::vector<UnrecognizedFlag> filtered; |
| 892 | filtered.reserve(unrecognized_flags.size()); |
| 893 | for (const auto& unrecognized : unrecognized_flags) { |
| 894 | if (flags_internal::CanIgnoreUndefinedFlag(unrecognized.flag_name)) |
| 895 | continue; |
| 896 | filtered.push_back(unrecognized); |
| 897 | } |
| 898 |
| 899 | std::swap(unrecognized_flags, filtered); |
| 900 |
| 901 | if (!success) { |
| 902 | #if ABSL_FLAGS_STRIP_NAMES |
| 903 | flags_internal::ReportUsageError( |
| 904 | "NOTE: command line flags are disabled in this build", true); |
| 905 | #else |
| 906 | flags_internal::HandleUsageFlags(std::cerr, ProgramUsageMessage()); |
| 907 | #endif |
| 908 | return HelpMode::kFull; // We just need to make sure the exit with |
| 909 | // code 1. |
| 910 | } |
| 911 |
| 912 | return usage_flag_action == UsageFlagsAction::kHandleUsage |
| 913 | ? flags_internal::HandleUsageFlags(std::cout, |
| 914 | ProgramUsageMessage()) |
| 915 | : HelpMode::kNone; |
| 916 | } |
| 917 |
| 918 | } // namespace flags_internal |
| 919 |
| 920 | void ParseAbseilFlagsOnly(int argc, char* argv[], |
| 921 | std::vector<char*>& positional_args, |
| 922 | std::vector<UnrecognizedFlag>& unrecognized_flags) { |
| 923 | auto help_mode = flags_internal::ParseAbseilFlagsOnlyImpl( |
| 924 | argc, argv, positional_args, unrecognized_flags, |
| 925 | flags_internal::UsageFlagsAction::kHandleUsage); |
| 926 |
| 927 | flags_internal::MaybeExit(help_mode); |
| 928 | } |
| 929 |
| 930 | // -------------------------------------------------------------------- |
| 931 |
| 932 | void ReportUnrecognizedFlags( |
| 933 | const std::vector<UnrecognizedFlag>& unrecognized_flags) { |
| 934 | flags_internal::ReportUnrecognizedFlags(unrecognized_flags, true); |
| 935 | } |
| 936 |
| 937 | // -------------------------------------------------------------------- |
| 938 |
| 939 | std::vector<char*> ParseCommandLine(int argc, char* argv[]) { |
| 940 | return flags_internal::ParseCommandLineImpl( |
| 941 | argc, argv, flags_internal::UsageFlagsAction::kHandleUsage, |
| 942 | flags_internal::OnUndefinedFlag::kAbortIfUndefined); |
| 943 | } |
| 944 |
| 945 | ABSL_NAMESPACE_END |
| 946 | } // namespace absl |
| 947 |