blob: 16c4d68fc270e0c09b682424ea0cc4df689b723f [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001//
2// Copyright 2019 The Abseil Authors.
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// 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 <fstream>
21#include <iostream>
22#include <tuple>
23
24#ifdef _WIN32
25#include <windows.h>
26#endif
27
28#include "absl/flags/flag.h"
29#include "absl/flags/internal/program_name.h"
30#include "absl/flags/internal/registry.h"
31#include "absl/flags/internal/usage.h"
32#include "absl/flags/usage.h"
33#include "absl/flags/usage_config.h"
34#include "absl/strings/str_cat.h"
35#include "absl/strings/strip.h"
36#include "absl/synchronization/mutex.h"
37
38// --------------------------------------------------------------------
39
40namespace absl {
41namespace flags_internal {
42namespace {
43
44ABSL_CONST_INIT absl::Mutex processing_checks_guard(absl::kConstInit);
45
46ABSL_CONST_INIT bool flagfile_needs_processing
47 ABSL_GUARDED_BY(processing_checks_guard) = false;
48ABSL_CONST_INIT bool fromenv_needs_processing
49 ABSL_GUARDED_BY(processing_checks_guard) = false;
50ABSL_CONST_INIT bool tryfromenv_needs_processing
51 ABSL_GUARDED_BY(processing_checks_guard) = false;
52
53} // namespace
54} // namespace flags_internal
55} // namespace absl
56
57ABSL_FLAG(std::vector<std::string>, flagfile, {},
58 "comma-separated list of files to load flags from")
59 .OnUpdate([]() {
60 if (absl::GetFlag(FLAGS_flagfile).empty()) return;
61
62 absl::MutexLock l(&absl::flags_internal::processing_checks_guard);
63
64 // Setting this flag twice before it is handled most likely an internal
65 // error and should be reviewed by developers.
66 if (absl::flags_internal::flagfile_needs_processing) {
67 ABSL_INTERNAL_LOG(WARNING, "flagfile set twice before it is handled");
68 }
69
70 absl::flags_internal::flagfile_needs_processing = true;
71 });
72ABSL_FLAG(std::vector<std::string>, fromenv, {},
73 "comma-separated list of flags to set from the environment"
74 " [use 'export FLAGS_flag1=value']")
75 .OnUpdate([]() {
76 if (absl::GetFlag(FLAGS_fromenv).empty()) return;
77
78 absl::MutexLock l(&absl::flags_internal::processing_checks_guard);
79
80 // Setting this flag twice before it is handled most likely an internal
81 // error and should be reviewed by developers.
82 if (absl::flags_internal::fromenv_needs_processing) {
83 ABSL_INTERNAL_LOG(WARNING, "fromenv set twice before it is handled.");
84 }
85
86 absl::flags_internal::fromenv_needs_processing = true;
87 });
88ABSL_FLAG(std::vector<std::string>, tryfromenv, {},
89 "comma-separated list of flags to try to set from the environment if "
90 "present")
91 .OnUpdate([]() {
92 if (absl::GetFlag(FLAGS_tryfromenv).empty()) return;
93
94 absl::MutexLock l(&absl::flags_internal::processing_checks_guard);
95
96 // Setting this flag twice before it is handled most likely an internal
97 // error and should be reviewed by developers.
98 if (absl::flags_internal::tryfromenv_needs_processing) {
99 ABSL_INTERNAL_LOG(WARNING,
100 "tryfromenv set twice before it is handled.");
101 }
102
103 absl::flags_internal::tryfromenv_needs_processing = true;
104 });
105
106ABSL_FLAG(std::vector<std::string>, undefok, {},
107 "comma-separated list of flag names that it is okay to specify "
108 "on the command line even if the program does not define a flag "
109 "with that name");
110
111namespace absl {
112namespace flags_internal {
113
114namespace {
115
116class ArgsList {
117 public:
118 ArgsList() : next_arg_(0) {}
119 ArgsList(int argc, char* argv[]) : args_(argv, argv + argc), next_arg_(0) {}
120 explicit ArgsList(const std::vector<std::string>& args)
121 : args_(args), next_arg_(0) {}
122
123 // Returns success status: true if parsing successful, false otherwise.
124 bool ReadFromFlagfile(const std::string& flag_file_name);
125
126 int Size() const { return args_.size() - next_arg_; }
127 int FrontIndex() const { return next_arg_; }
128 absl::string_view Front() const { return args_[next_arg_]; }
129 void PopFront() { next_arg_++; }
130
131 private:
132 std::vector<std::string> args_;
133 int next_arg_;
134};
135
136bool ArgsList::ReadFromFlagfile(const std::string& flag_file_name) {
137 std::ifstream flag_file(flag_file_name);
138
139 if (!flag_file) {
140 flags_internal::ReportUsageError(
141 absl::StrCat("Can't open flagfile ", flag_file_name), true);
142
143 return false;
144 }
145
146 // This argument represents fake argv[0], which should be present in all arg
147 // lists.
148 args_.push_back("");
149
150 std::string line;
151 bool success = true;
152
153 while (std::getline(flag_file, line)) {
154 absl::string_view stripped = absl::StripLeadingAsciiWhitespace(line);
155
156 if (stripped.empty() || stripped[0] == '#') {
157 // Comment or empty line; just ignore.
158 continue;
159 }
160
161 if (stripped[0] == '-') {
162 if (stripped == "--") {
163 flags_internal::ReportUsageError(
164 "Flagfile can't contain position arguments or --", true);
165
166 success = false;
167 break;
168 }
169
170 args_.push_back(std::string(stripped));
171 continue;
172 }
173
174 flags_internal::ReportUsageError(
175 absl::StrCat("Unexpected line in the flagfile ", flag_file_name, ": ",
176 line),
177 true);
178
179 success = false;
180 }
181
182 return success;
183}
184
185// --------------------------------------------------------------------
186
187// Reads the environment variable with name `name` and stores results in
188// `value`. If variable is not present in environment returns false, otherwise
189// returns true.
190bool GetEnvVar(const char* var_name, std::string* var_value) {
191#ifdef _WIN32
192 char buf[1024];
193 auto get_res = GetEnvironmentVariableA(var_name, buf, sizeof(buf));
194 if (get_res >= sizeof(buf)) {
195 return false;
196 }
197
198 if (get_res == 0) {
199 return false;
200 }
201
202 *var_value = std::string(buf, get_res);
203#else
204 const char* val = ::getenv(var_name);
205 if (val == nullptr) {
206 return false;
207 }
208
209 *var_value = val;
210#endif
211
212 return true;
213}
214
215// --------------------------------------------------------------------
216
217// Returns:
218// Flag name or empty if arg= --
219// Flag value after = in --flag=value (empty if --foo)
220// "Is empty value" status. True if arg= --foo=, false otherwise. This is
221// required to separate --foo from --foo=.
222// For example:
223// arg return values
224// "--foo=bar" -> {"foo", "bar", false}.
225// "--foo" -> {"foo", "", false}.
226// "--foo=" -> {"foo", "", true}.
227std::tuple<absl::string_view, absl::string_view, bool> SplitNameAndValue(
228 absl::string_view arg) {
229 // Allow -foo and --foo
230 absl::ConsumePrefix(&arg, "-");
231
232 if (arg.empty()) {
233 return std::make_tuple("", "", false);
234 }
235
236 auto equal_sign_pos = arg.find("=");
237
238 absl::string_view flag_name = arg.substr(0, equal_sign_pos);
239
240 absl::string_view value;
241 bool is_empty_value = false;
242
243 if (equal_sign_pos != absl::string_view::npos) {
244 value = arg.substr(equal_sign_pos + 1);
245 is_empty_value = value.empty();
246 }
247
248 return std::make_tuple(flag_name, value, is_empty_value);
249}
250
251// --------------------------------------------------------------------
252
253// Returns:
254// found flag or nullptr
255// is negative in case of --nofoo
256std::tuple<CommandLineFlag*, bool> LocateFlag(absl::string_view flag_name) {
257 CommandLineFlag* flag = flags_internal::FindCommandLineFlag(flag_name);
258 bool is_negative = false;
259
260 if (!flag && absl::ConsumePrefix(&flag_name, "no")) {
261 flag = flags_internal::FindCommandLineFlag(flag_name);
262 is_negative = true;
263 }
264
265 return std::make_tuple(flag, is_negative);
266}
267
268// --------------------------------------------------------------------
269
270// Verify that default values of typed flags must be convertible to string and
271// back.
272void CheckDefaultValuesParsingRoundtrip() {
273#ifndef NDEBUG
274 flags_internal::ForEachFlag([&](CommandLineFlag* flag) {
275 if (flag->IsRetired()) return;
276
277#define IGNORE_TYPE(T) \
278 if (flag->IsOfType<T>()) return;
279
280 ABSL_FLAGS_INTERNAL_FOR_EACH_LOCK_FREE(IGNORE_TYPE)
281 IGNORE_TYPE(std::string)
282 IGNORE_TYPE(std::vector<std::string>)
283#undef IGNORE_TYPE
284
285 flag->CheckDefaultValueParsingRoundtrip();
286 });
287#endif
288}
289
290// --------------------------------------------------------------------
291
292// Returns success status, which is true if we successfully read all flag files,
293// in which case new ArgLists are appended to the input_args in a reverse order
294// of file names in the input flagfiles list. This order ensures that flags from
295// the first flagfile in the input list are processed before the second flagfile
296// etc.
297bool ReadFlagfiles(const std::vector<std::string>& flagfiles,
298 std::vector<ArgsList>* input_args) {
299 bool success = true;
300 for (auto it = flagfiles.rbegin(); it != flagfiles.rend(); ++it) {
301 ArgsList al;
302
303 if (al.ReadFromFlagfile(*it)) {
304 input_args->push_back(al);
305 } else {
306 success = false;
307 }
308 }
309
310 return success;
311}
312
313// Returns success status, which is true if were able to locate all environment
314// variables correctly or if fail_on_absent_in_env is false. The environment
315// variable names are expected to be of the form `FLAGS_<flag_name>`, where
316// `flag_name` is a string from the input flag_names list. If successful we
317// append a single ArgList at the end of the input_args.
318bool ReadFlagsFromEnv(const std::vector<std::string>& flag_names,
319 std::vector<ArgsList>* input_args,
320 bool fail_on_absent_in_env) {
321 bool success = true;
322 std::vector<std::string> args;
323
324 // This argument represents fake argv[0], which should be present in all arg
325 // lists.
326 args.push_back("");
327
328 for (const auto& flag_name : flag_names) {
329 // Avoid infinite recursion.
330 if (flag_name == "fromenv" || flag_name == "tryfromenv") {
331 flags_internal::ReportUsageError(
332 absl::StrCat("Infinite recursion on flag ", flag_name), true);
333
334 success = false;
335 continue;
336 }
337
338 const std::string envname = absl::StrCat("FLAGS_", flag_name);
339 std::string envval;
340 if (!GetEnvVar(envname.c_str(), &envval)) {
341 if (fail_on_absent_in_env) {
342 flags_internal::ReportUsageError(
343 absl::StrCat(envname, " not found in environment"), true);
344
345 success = false;
346 }
347
348 continue;
349 }
350
351 args.push_back(absl::StrCat("--", flag_name, "=", envval));
352 }
353
354 if (success) {
355 input_args->emplace_back(args);
356 }
357
358 return success;
359}
360
361// --------------------------------------------------------------------
362
363// Returns success status, which is true if were able to handle all generator
364// flags (flagfile, fromenv, tryfromemv) successfully.
365bool HandleGeneratorFlags(std::vector<ArgsList>* input_args,
366 std::vector<std::string>* flagfile_value) {
367 bool success = true;
368
369 absl::MutexLock l(&flags_internal::processing_checks_guard);
370
371 // flagfile could have been set either on a command line or
372 // programmatically before invoking ParseCommandLine. Note that we do not
373 // actually process arguments specified in the flagfile, but instead
374 // create a secondary arguments list to be processed along with the rest
375 // of the comamnd line arguments. Since we always the process most recently
376 // created list of arguments first, this will result in flagfile argument
377 // being processed before any other argument in the command line. If
378 // FLAGS_flagfile contains more than one file name we create multiple new
379 // levels of arguments in a reverse order of file names. Thus we always
380 // process arguments from first file before arguments containing in a
381 // second file, etc. If flagfile contains another
382 // --flagfile inside of it, it will produce new level of arguments and
383 // processed before the rest of the flagfile. We are also collecting all
384 // flagfiles set on original command line. Unlike the rest of the flags,
385 // this flag can be set multiple times and is expected to be handled
386 // multiple times. We are collecting them all into a single list and set
387 // the value of FLAGS_flagfile to that value at the end of the parsing.
388 if (flags_internal::flagfile_needs_processing) {
389 auto flagfiles = absl::GetFlag(FLAGS_flagfile);
390
391 if (input_args->size() == 1) {
392 flagfile_value->insert(flagfile_value->end(), flagfiles.begin(),
393 flagfiles.end());
394 }
395
396 success &= ReadFlagfiles(flagfiles, input_args);
397
398 flags_internal::flagfile_needs_processing = false;
399 }
400
401 // Similar to flagfile fromenv/tryfromemv can be set both
402 // programmatically and at runtime on a command line. Unlike flagfile these
403 // can't be recursive.
404 if (flags_internal::fromenv_needs_processing) {
405 auto flags_list = absl::GetFlag(FLAGS_fromenv);
406
407 success &= ReadFlagsFromEnv(flags_list, input_args, true);
408
409 flags_internal::fromenv_needs_processing = false;
410 }
411
412 if (flags_internal::tryfromenv_needs_processing) {
413 auto flags_list = absl::GetFlag(FLAGS_tryfromenv);
414
415 success &= ReadFlagsFromEnv(flags_list, input_args, false);
416
417 flags_internal::tryfromenv_needs_processing = false;
418 }
419
420 return success;
421}
422
423// --------------------------------------------------------------------
424
425void ResetGeneratorFlags(const std::vector<std::string>& flagfile_value) {
426 // Setting flagfile to the value which collates all the values set on a
427 // command line and programmatically. So if command line looked like
428 // --flagfile=f1 --flagfile=f2 the final value of the FLAGS_flagfile flag is
429 // going to be {"f1", "f2"}
430 if (!flagfile_value.empty()) {
431 absl::SetFlag(&FLAGS_flagfile, flagfile_value);
432 absl::MutexLock l(&flags_internal::processing_checks_guard);
433 flags_internal::flagfile_needs_processing = false;
434 }
435
436 // fromenv/tryfromenv are set to <undefined> value.
437 if (!absl::GetFlag(FLAGS_fromenv).empty()) {
438 absl::SetFlag(&FLAGS_fromenv, {});
439 }
440 if (!absl::GetFlag(FLAGS_tryfromenv).empty()) {
441 absl::SetFlag(&FLAGS_tryfromenv, {});
442 }
443
444 absl::MutexLock l(&flags_internal::processing_checks_guard);
445 flags_internal::fromenv_needs_processing = false;
446 flags_internal::tryfromenv_needs_processing = false;
447}
448
449// --------------------------------------------------------------------
450
451// Returns:
452// success status
453// deduced value
454// We are also mutating curr_list in case if we need to get a hold of next
455// argument in the input.
456std::tuple<bool, absl::string_view> DeduceFlagValue(const CommandLineFlag& flag,
457 absl::string_view value,
458 bool is_negative,
459 bool is_empty_value,
460 ArgsList* curr_list) {
461 // Value is either an argument suffix after `=` in "--foo=<value>"
462 // or separate argument in case of "--foo" "<value>".
463
464 // boolean flags have these forms:
465 // --foo
466 // --nofoo
467 // --foo=true
468 // --foo=false
469 // --nofoo=<value> is not supported
470 // --foo <value> is not supported
471
472 // non boolean flags have these forms:
473 // --foo=<value>
474 // --foo <value>
475 // --nofoo is not supported
476
477 if (flag.IsOfType<bool>()) {
478 if (value.empty()) {
479 if (is_empty_value) {
480 // "--bool_flag=" case
481 flags_internal::ReportUsageError(
482 absl::StrCat(
483 "Missing the value after assignment for the boolean flag '",
484 flag.Name(), "'"),
485 true);
486 return std::make_tuple(false, "");
487 }
488
489 // "--bool_flag" case
490 value = is_negative ? "0" : "1";
491 } else if (is_negative) {
492 // "--nobool_flag=Y" case
493 flags_internal::ReportUsageError(
494 absl::StrCat("Negative form with assignment is not valid for the "
495 "boolean flag '",
496 flag.Name(), "'"),
497 true);
498 return std::make_tuple(false, "");
499 }
500 } else if (is_negative) {
501 // "--noint_flag=1" case
502 flags_internal::ReportUsageError(
503 absl::StrCat("Negative form is not valid for the flag '", flag.Name(),
504 "'"),
505 true);
506 return std::make_tuple(false, "");
507 } else if (value.empty() && (!is_empty_value)) {
508 if (curr_list->Size() == 1) {
509 // "--int_flag" case
510 flags_internal::ReportUsageError(
511 absl::StrCat("Missing the value for the flag '", flag.Name(), "'"),
512 true);
513 return std::make_tuple(false, "");
514 }
515
516 // "--int_flag" "10" case
517 curr_list->PopFront();
518 value = curr_list->Front();
519
520 // Heuristic to detect the case where someone treats a std::string arg
521 // like a bool or just forgets to pass a value:
522 // --my_string_var --foo=bar
523 // We look for a flag of std::string type, whose value begins with a
524 // dash and corresponds to known flag or standalone --.
525 if (value[0] == '-' && flag.IsOfType<std::string>()) {
526 auto maybe_flag_name = std::get<0>(SplitNameAndValue(value.substr(1)));
527
528 if (maybe_flag_name.empty() ||
529 std::get<0>(LocateFlag(maybe_flag_name)) != nullptr) {
530 // "--string_flag" "--known_flag" case
531 ABSL_INTERNAL_LOG(
532 WARNING,
533 absl::StrCat("Did you really mean to set flag '", flag.Name(),
534 "' to the value '", value, "'?"));
535 }
536 }
537 }
538
539 return std::make_tuple(true, value);
540}
541
542// --------------------------------------------------------------------
543
544bool CanIgnoreUndefinedFlag(absl::string_view flag_name) {
545 auto undefok = absl::GetFlag(FLAGS_undefok);
546 if (std::find(undefok.begin(), undefok.end(), flag_name) != undefok.end()) {
547 return true;
548 }
549
550 if (absl::ConsumePrefix(&flag_name, "no") &&
551 std::find(undefok.begin(), undefok.end(), flag_name) != undefok.end()) {
552 return true;
553 }
554
555 return false;
556}
557
558} // namespace
559
560// --------------------------------------------------------------------
561
562std::vector<char*> ParseCommandLineImpl(int argc, char* argv[],
563 ArgvListAction arg_list_act,
564 UsageFlagsAction usage_flag_act,
565 OnUndefinedFlag on_undef_flag) {
566 ABSL_INTERNAL_CHECK(argc > 0, "Missing argv[0]");
567
568 // This routine does not return anything since we abort on failure.
569 CheckDefaultValuesParsingRoundtrip();
570
571 std::vector<std::string> flagfile_value;
572
573 std::vector<ArgsList> input_args;
574 input_args.push_back(ArgsList(argc, argv));
575
576 std::vector<char*> output_args;
577 std::vector<char*> positional_args;
578 output_args.reserve(argc);
579
580 // This is the list of undefined flags. The element of the list is the pair
581 // consisting of boolean indicating if flag came from command line (vs from
582 // some flag file we've read) and flag name.
583 // TODO(rogeeff): Eliminate the first element in the pair after cleanup.
584 std::vector<std::pair<bool, std::string>> undefined_flag_names;
585
586 // Set program invocation name if it is not set before.
587 if (ProgramInvocationName() == "UNKNOWN") {
588 flags_internal::SetProgramInvocationName(argv[0]);
589 }
590 output_args.push_back(argv[0]);
591
592 // Iterate through the list of the input arguments. First level are arguments
593 // originated from argc/argv. Following levels are arguments originated from
594 // recursive parsing of flagfile(s).
595 bool success = true;
596 while (!input_args.empty()) {
597 // 10. First we process the built-in generator flags.
598 success &= HandleGeneratorFlags(&input_args, &flagfile_value);
599
600 // 30. Select top-most (most recent) arguments list. If it is empty drop it
601 // and re-try.
602 ArgsList& curr_list = input_args.back();
603
604 curr_list.PopFront();
605
606 if (curr_list.Size() == 0) {
607 input_args.pop_back();
608 continue;
609 }
610
611 // 40. Pick up the front remaining argument in the current list. If current
612 // stack of argument lists contains only one element - we are processing an
613 // argument from the original argv.
614 absl::string_view arg(curr_list.Front());
615 bool arg_from_argv = input_args.size() == 1;
616
617 // 50. If argument does not start with - or is just "-" - this is
618 // positional argument.
619 if (!absl::ConsumePrefix(&arg, "-") || arg.empty()) {
620 ABSL_INTERNAL_CHECK(arg_from_argv,
621 "Flagfile cannot contain positional argument");
622
623 positional_args.push_back(argv[curr_list.FrontIndex()]);
624 continue;
625 }
626
627 if (arg_from_argv && (arg_list_act == ArgvListAction::kKeepParsedArgs)) {
628 output_args.push_back(argv[curr_list.FrontIndex()]);
629 }
630
631 // 60. Split the current argument on '=' to figure out the argument
632 // name and value. If flag name is empty it means we've got "--". value
633 // can be empty either if there were no '=' in argument std::string at all or
634 // an argument looked like "--foo=". In a latter case is_empty_value is
635 // true.
636 absl::string_view flag_name;
637 absl::string_view value;
638 bool is_empty_value = false;
639
640 std::tie(flag_name, value, is_empty_value) = SplitNameAndValue(arg);
641
642 // 70. "--" alone means what it does for GNU: stop flags parsing. We do
643 // not support positional arguments in flagfiles, so we just drop them.
644 if (flag_name.empty()) {
645 ABSL_INTERNAL_CHECK(arg_from_argv,
646 "Flagfile cannot contain positional argument");
647
648 curr_list.PopFront();
649 break;
650 }
651
652 // 80. Locate the flag based on flag name. Handle both --foo and --nofoo
653 CommandLineFlag* flag = nullptr;
654 bool is_negative = false;
655 std::tie(flag, is_negative) = LocateFlag(flag_name);
656
657 if (flag == nullptr) {
658 if (on_undef_flag != OnUndefinedFlag::kIgnoreUndefined) {
659 undefined_flag_names.emplace_back(arg_from_argv,
660 std::string(flag_name));
661 }
662 continue;
663 }
664
665 // 90. Deduce flag's value (from this or next argument)
666 auto curr_index = curr_list.FrontIndex();
667 bool value_success = true;
668 std::tie(value_success, value) =
669 DeduceFlagValue(*flag, value, is_negative, is_empty_value, &curr_list);
670 success &= value_success;
671
672 // If above call consumed an argument, it was a standalone value
673 if (arg_from_argv && (arg_list_act == ArgvListAction::kKeepParsedArgs) &&
674 (curr_index != curr_list.FrontIndex())) {
675 output_args.push_back(argv[curr_list.FrontIndex()]);
676 }
677
678 // 100. Set the located flag to a new new value, unless it is retired.
679 // Setting retired flag fails, but we ignoring it here.
680 if (flag->IsRetired()) continue;
681
682 std::string error;
683 if (!flag->SetFromString(value, SET_FLAGS_VALUE, kCommandLine, &error)) {
684 flags_internal::ReportUsageError(error, true);
685 success = false;
686 }
687 }
688
689 for (const auto& flag_name : undefined_flag_names) {
690 if (CanIgnoreUndefinedFlag(flag_name.second)) continue;
691
692 flags_internal::ReportUsageError(
693 absl::StrCat("Unknown command line flag '", flag_name.second, "'"),
694 true);
695
696 success = false;
697 }
698
699#if ABSL_FLAGS_STRIP_NAMES
700 if (!success) {
701 flags_internal::ReportUsageError(
702 "NOTE: command line flags are disabled in this build", true);
703 }
704#endif
705
706 if (!success) {
707 flags_internal::HandleUsageFlags(std::cout,
708 ProgramUsageMessage());
709 std::exit(1);
710 }
711
712 if (usage_flag_act == UsageFlagsAction::kHandleUsage) {
713 int exit_code = flags_internal::HandleUsageFlags(
714 std::cout, ProgramUsageMessage());
715
716 if (exit_code != -1) {
717 std::exit(exit_code);
718 }
719 }
720
721 ResetGeneratorFlags(flagfile_value);
722
723 // Reinstate positional args which were intermixed with flags in the arguments
724 // list.
725 for (auto arg : positional_args) {
726 output_args.push_back(arg);
727 }
728
729 // All the remaining arguments are positional.
730 if (!input_args.empty()) {
731 for (int arg_index = input_args.back().FrontIndex(); arg_index < argc;
732 ++arg_index) {
733 output_args.push_back(argv[arg_index]);
734 }
735 }
736
737 return output_args;
738}
739
740} // namespace flags_internal
741
742// --------------------------------------------------------------------
743
744std::vector<char*> ParseCommandLine(int argc, char* argv[]) {
745 return flags_internal::ParseCommandLineImpl(
746 argc, argv, flags_internal::ArgvListAction::kRemoveParsedArgs,
747 flags_internal::UsageFlagsAction::kHandleUsage,
748 flags_internal::OnUndefinedFlag::kAbortIfUndefined);
749}
750
751} // namespace absl