usage.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. //
  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. #include "absl/flags/internal/usage.h"
  16. #include <stdint.h>
  17. #include <algorithm>
  18. #include <cstdlib>
  19. #include <functional>
  20. #include <iterator>
  21. #include <map>
  22. #include <ostream>
  23. #include <string>
  24. #include <utility>
  25. #include <vector>
  26. #include "absl/base/attributes.h"
  27. #include "absl/base/config.h"
  28. #include "absl/base/const_init.h"
  29. #include "absl/base/thread_annotations.h"
  30. #include "absl/flags/commandlineflag.h"
  31. #include "absl/flags/flag.h"
  32. #include "absl/flags/internal/flag.h"
  33. #include "absl/flags/internal/path_util.h"
  34. #include "absl/flags/internal/private_handle_accessor.h"
  35. #include "absl/flags/internal/program_name.h"
  36. #include "absl/flags/internal/registry.h"
  37. #include "absl/flags/usage_config.h"
  38. #include "absl/strings/match.h"
  39. #include "absl/strings/str_cat.h"
  40. #include "absl/strings/str_split.h"
  41. #include "absl/strings/string_view.h"
  42. #include "absl/strings/strip.h"
  43. #include "absl/synchronization/mutex.h"
  44. // Dummy global variables to prevent anyone else defining these.
  45. bool FLAGS_help = false;
  46. bool FLAGS_helpfull = false;
  47. bool FLAGS_helpshort = false;
  48. bool FLAGS_helppackage = false;
  49. bool FLAGS_version = false;
  50. bool FLAGS_only_check_args = false;
  51. bool FLAGS_helpon = false;
  52. bool FLAGS_helpmatch = false;
  53. namespace absl {
  54. ABSL_NAMESPACE_BEGIN
  55. namespace flags_internal {
  56. namespace {
  57. using PerFlagFilter = std::function<bool(const absl::CommandLineFlag&)>;
  58. // Maximum length size in a human readable format.
  59. constexpr size_t kHrfMaxLineLength = 80;
  60. // This class is used to emit an XML element with `tag` and `text`.
  61. // It adds opening and closing tags and escapes special characters in the text.
  62. // For example:
  63. // std::cout << XMLElement("title", "Milk & Cookies");
  64. // prints "<title>Milk &amp; Cookies</title>"
  65. class XMLElement {
  66. public:
  67. XMLElement(absl::string_view tag, absl::string_view txt)
  68. : tag_(tag), txt_(txt) {}
  69. friend std::ostream& operator<<(std::ostream& out,
  70. const XMLElement& xml_elem) {
  71. out << "<" << xml_elem.tag_ << ">";
  72. for (auto c : xml_elem.txt_) {
  73. switch (c) {
  74. case '"':
  75. out << "&quot;";
  76. break;
  77. case '\'':
  78. out << "&apos;";
  79. break;
  80. case '&':
  81. out << "&amp;";
  82. break;
  83. case '<':
  84. out << "&lt;";
  85. break;
  86. case '>':
  87. out << "&gt;";
  88. break;
  89. case '\n':
  90. case '\v':
  91. case '\f':
  92. case '\t':
  93. out << " ";
  94. break;
  95. default:
  96. if (IsValidXmlCharacter(static_cast<unsigned char>(c))) {
  97. out << c;
  98. }
  99. break;
  100. }
  101. }
  102. return out << "</" << xml_elem.tag_ << ">";
  103. }
  104. private:
  105. static bool IsValidXmlCharacter(unsigned char c) { return c >= 0x20; }
  106. absl::string_view tag_;
  107. absl::string_view txt_;
  108. };
  109. // --------------------------------------------------------------------
  110. // Helper class to pretty-print info about a flag.
  111. class FlagHelpPrettyPrinter {
  112. public:
  113. // Pretty printer holds on to the std::ostream& reference to direct an output
  114. // to that stream.
  115. FlagHelpPrettyPrinter(size_t max_line_len, size_t min_line_len,
  116. size_t wrapped_line_indent, std::ostream& out)
  117. : out_(out),
  118. max_line_len_(max_line_len),
  119. min_line_len_(min_line_len),
  120. wrapped_line_indent_(wrapped_line_indent),
  121. line_len_(0),
  122. first_line_(true) {}
  123. void Write(absl::string_view str, bool wrap_line = false) {
  124. // Empty string - do nothing.
  125. if (str.empty()) return;
  126. std::vector<absl::string_view> tokens;
  127. if (wrap_line) {
  128. for (auto line : absl::StrSplit(str, absl::ByAnyChar("\n\r"))) {
  129. if (!tokens.empty()) {
  130. // Keep line separators in the input string.
  131. tokens.emplace_back("\n");
  132. }
  133. for (auto token :
  134. absl::StrSplit(line, absl::ByAnyChar(" \t"), absl::SkipEmpty())) {
  135. tokens.push_back(token);
  136. }
  137. }
  138. } else {
  139. tokens.push_back(str);
  140. }
  141. for (auto token : tokens) {
  142. bool new_line = (line_len_ == 0);
  143. // Respect line separators in the input string.
  144. if (token == "\n") {
  145. EndLine();
  146. continue;
  147. }
  148. // Write the token, ending the string first if necessary/possible.
  149. if (!new_line && (line_len_ + token.size() >= max_line_len_)) {
  150. EndLine();
  151. new_line = true;
  152. }
  153. if (new_line) {
  154. StartLine();
  155. } else {
  156. out_ << ' ';
  157. ++line_len_;
  158. }
  159. out_ << token;
  160. line_len_ += token.size();
  161. }
  162. }
  163. void StartLine() {
  164. if (first_line_) {
  165. line_len_ = min_line_len_;
  166. first_line_ = false;
  167. } else {
  168. line_len_ = min_line_len_ + wrapped_line_indent_;
  169. }
  170. out_ << std::string(line_len_, ' ');
  171. }
  172. void EndLine() {
  173. out_ << '\n';
  174. line_len_ = 0;
  175. }
  176. private:
  177. std::ostream& out_;
  178. const size_t max_line_len_;
  179. const size_t min_line_len_;
  180. const size_t wrapped_line_indent_;
  181. size_t line_len_;
  182. bool first_line_;
  183. };
  184. void FlagHelpHumanReadable(const CommandLineFlag& flag, std::ostream& out) {
  185. FlagHelpPrettyPrinter printer(kHrfMaxLineLength, 4, 2, out);
  186. // Flag name.
  187. printer.Write(absl::StrCat("--", flag.Name()));
  188. // Flag help.
  189. printer.Write(absl::StrCat("(", flag.Help(), ");"), /*wrap_line=*/true);
  190. // The listed default value will be the actual default from the flag
  191. // definition in the originating source file, unless the value has
  192. // subsequently been modified using SetCommandLineOption() with mode
  193. // SET_FLAGS_DEFAULT.
  194. std::string dflt_val = flag.DefaultValue();
  195. std::string curr_val = flag.CurrentValue();
  196. bool is_modified = curr_val != dflt_val;
  197. if (flag.IsOfType<std::string>()) {
  198. dflt_val = absl::StrCat("\"", dflt_val, "\"");
  199. }
  200. printer.Write(absl::StrCat("default: ", dflt_val, ";"));
  201. if (is_modified) {
  202. if (flag.IsOfType<std::string>()) {
  203. curr_val = absl::StrCat("\"", curr_val, "\"");
  204. }
  205. printer.Write(absl::StrCat("currently: ", curr_val, ";"));
  206. }
  207. printer.EndLine();
  208. }
  209. // Shows help for every filename which matches any of the filters
  210. // If filters are empty, shows help for every file.
  211. // If a flag's help message has been stripped (e.g. by adding '#define
  212. // STRIP_FLAG_HELP 1' then this flag will not be displayed by '--help'
  213. // and its variants.
  214. void FlagsHelpImpl(std::ostream& out, PerFlagFilter filter_cb,
  215. HelpFormat format, absl::string_view program_usage_message) {
  216. if (format == HelpFormat::kHumanReadable) {
  217. out << flags_internal::ShortProgramInvocationName() << ": "
  218. << program_usage_message << "\n\n";
  219. } else {
  220. // XML schema is not a part of our public API for now.
  221. out << "<?xml version=\"1.0\"?>\n"
  222. << "<!-- This output should be used with care. We do not report type "
  223. "names for flags with user defined types -->\n"
  224. << "<!-- Prefer flag only_check_args for validating flag inputs -->\n"
  225. // The document.
  226. << "<AllFlags>\n"
  227. // The program name and usage.
  228. << XMLElement("program", flags_internal::ShortProgramInvocationName())
  229. << '\n'
  230. << XMLElement("usage", program_usage_message) << '\n';
  231. }
  232. // Ordered map of package name to
  233. // map of file name to
  234. // vector of flags in the file.
  235. // This map is used to output matching flags grouped by package and file
  236. // name.
  237. std::map<std::string,
  238. std::map<std::string, std::vector<const absl::CommandLineFlag*>>>
  239. matching_flags;
  240. flags_internal::ForEachFlag([&](absl::CommandLineFlag& flag) {
  241. // Ignore retired flags.
  242. if (flag.IsRetired()) return;
  243. // If the flag has been stripped, pretend that it doesn't exist.
  244. if (flag.Help() == flags_internal::kStrippedFlagHelp) return;
  245. // Make sure flag satisfies the filter
  246. if (!filter_cb(flag)) return;
  247. std::string flag_filename = flag.Filename();
  248. matching_flags[std::string(flags_internal::Package(flag_filename))]
  249. [flag_filename]
  250. .push_back(&flag);
  251. });
  252. absl::string_view package_separator; // controls blank lines between packages
  253. absl::string_view file_separator; // controls blank lines between files
  254. for (auto& package : matching_flags) {
  255. if (format == HelpFormat::kHumanReadable) {
  256. out << package_separator;
  257. package_separator = "\n\n";
  258. }
  259. file_separator = "";
  260. for (auto& flags_in_file : package.second) {
  261. if (format == HelpFormat::kHumanReadable) {
  262. out << file_separator << " Flags from " << flags_in_file.first
  263. << ":\n";
  264. file_separator = "\n";
  265. }
  266. std::sort(std::begin(flags_in_file.second),
  267. std::end(flags_in_file.second),
  268. [](const CommandLineFlag* lhs, const CommandLineFlag* rhs) {
  269. return lhs->Name() < rhs->Name();
  270. });
  271. for (const auto* flag : flags_in_file.second) {
  272. flags_internal::FlagHelp(out, *flag, format);
  273. }
  274. }
  275. }
  276. if (format == HelpFormat::kHumanReadable) {
  277. FlagHelpPrettyPrinter printer(kHrfMaxLineLength, 0, 0, out);
  278. if (filter_cb && matching_flags.empty()) {
  279. printer.Write("No flags matched.\n", true);
  280. }
  281. printer.EndLine();
  282. printer.Write(
  283. "Try --helpfull to get a list of all flags or --help=substring "
  284. "shows help for flags which include specified substring in either "
  285. "in the name, or description or path.\n",
  286. true);
  287. } else {
  288. // The end of the document.
  289. out << "</AllFlags>\n";
  290. }
  291. }
  292. void FlagsHelpImpl(std::ostream& out,
  293. flags_internal::FlagKindFilter filename_filter_cb,
  294. HelpFormat format, absl::string_view program_usage_message) {
  295. FlagsHelpImpl(
  296. out,
  297. [&](const absl::CommandLineFlag& flag) {
  298. return filename_filter_cb && filename_filter_cb(flag.Filename());
  299. },
  300. format, program_usage_message);
  301. }
  302. } // namespace
  303. // --------------------------------------------------------------------
  304. // Produces the help message describing specific flag.
  305. void FlagHelp(std::ostream& out, const CommandLineFlag& flag,
  306. HelpFormat format) {
  307. if (format == HelpFormat::kHumanReadable)
  308. flags_internal::FlagHelpHumanReadable(flag, out);
  309. }
  310. // --------------------------------------------------------------------
  311. // Produces the help messages for all flags matching the filename filter.
  312. // If filter is empty produces help messages for all flags.
  313. void FlagsHelp(std::ostream& out, absl::string_view filter, HelpFormat format,
  314. absl::string_view program_usage_message) {
  315. flags_internal::FlagKindFilter filter_cb = [&](absl::string_view filename) {
  316. return filter.empty() || absl::StrContains(filename, filter);
  317. };
  318. flags_internal::FlagsHelpImpl(out, filter_cb, format, program_usage_message);
  319. }
  320. // --------------------------------------------------------------------
  321. // Checks all the 'usage' command line flags to see if any have been set.
  322. // If so, handles them appropriately.
  323. HelpMode HandleUsageFlags(std::ostream& out,
  324. absl::string_view program_usage_message) {
  325. switch (GetFlagsHelpMode()) {
  326. case HelpMode::kNone:
  327. break;
  328. case HelpMode::kImportant:
  329. flags_internal::FlagsHelpImpl(
  330. out, flags_internal::GetUsageConfig().contains_help_flags,
  331. GetFlagsHelpFormat(), program_usage_message);
  332. break;
  333. case HelpMode::kShort:
  334. flags_internal::FlagsHelpImpl(
  335. out, flags_internal::GetUsageConfig().contains_helpshort_flags,
  336. GetFlagsHelpFormat(), program_usage_message);
  337. break;
  338. case HelpMode::kFull:
  339. flags_internal::FlagsHelp(out, "", GetFlagsHelpFormat(),
  340. program_usage_message);
  341. break;
  342. case HelpMode::kPackage:
  343. flags_internal::FlagsHelpImpl(
  344. out, flags_internal::GetUsageConfig().contains_helppackage_flags,
  345. GetFlagsHelpFormat(), program_usage_message);
  346. break;
  347. case HelpMode::kMatch: {
  348. std::string substr = GetFlagsHelpMatchSubstr();
  349. if (substr.empty()) {
  350. // show all options
  351. flags_internal::FlagsHelp(out, substr, GetFlagsHelpFormat(),
  352. program_usage_message);
  353. } else {
  354. auto filter_cb = [&substr](const absl::CommandLineFlag& flag) {
  355. if (absl::StrContains(flag.Name(), substr)) return true;
  356. if (absl::StrContains(flag.Filename(), substr)) return true;
  357. if (absl::StrContains(flag.Help(), substr)) return true;
  358. return false;
  359. };
  360. flags_internal::FlagsHelpImpl(
  361. out, filter_cb, HelpFormat::kHumanReadable, program_usage_message);
  362. }
  363. break;
  364. }
  365. case HelpMode::kVersion:
  366. if (flags_internal::GetUsageConfig().version_string)
  367. out << flags_internal::GetUsageConfig().version_string();
  368. // Unlike help, we may be asking for version in a script, so return 0
  369. break;
  370. case HelpMode::kOnlyCheckArgs:
  371. break;
  372. }
  373. return GetFlagsHelpMode();
  374. }
  375. // --------------------------------------------------------------------
  376. // Globals representing usage reporting flags
  377. namespace {
  378. ABSL_CONST_INIT absl::Mutex help_attributes_guard(absl::kConstInit);
  379. ABSL_CONST_INIT std::string* match_substr
  380. ABSL_GUARDED_BY(help_attributes_guard) = nullptr;
  381. ABSL_CONST_INIT HelpMode help_mode ABSL_GUARDED_BY(help_attributes_guard) =
  382. HelpMode::kNone;
  383. ABSL_CONST_INIT HelpFormat help_format ABSL_GUARDED_BY(help_attributes_guard) =
  384. HelpFormat::kHumanReadable;
  385. } // namespace
  386. std::string GetFlagsHelpMatchSubstr() {
  387. absl::MutexLock l(&help_attributes_guard);
  388. if (match_substr == nullptr) return "";
  389. return *match_substr;
  390. }
  391. void SetFlagsHelpMatchSubstr(absl::string_view substr) {
  392. absl::MutexLock l(&help_attributes_guard);
  393. if (match_substr == nullptr) match_substr = new std::string;
  394. match_substr->assign(substr.data(), substr.size());
  395. }
  396. HelpMode GetFlagsHelpMode() {
  397. absl::MutexLock l(&help_attributes_guard);
  398. return help_mode;
  399. }
  400. void SetFlagsHelpMode(HelpMode mode) {
  401. absl::MutexLock l(&help_attributes_guard);
  402. help_mode = mode;
  403. }
  404. HelpFormat GetFlagsHelpFormat() {
  405. absl::MutexLock l(&help_attributes_guard);
  406. return help_format;
  407. }
  408. void SetFlagsHelpFormat(HelpFormat format) {
  409. absl::MutexLock l(&help_attributes_guard);
  410. help_format = format;
  411. }
  412. // Deduces usage flags from the input argument in a form --name=value or
  413. // --name. argument is already split into name and value before we call this
  414. // function.
  415. bool DeduceUsageFlags(absl::string_view name, absl::string_view value) {
  416. if (absl::ConsumePrefix(&name, "help")) {
  417. if (name.empty()) {
  418. if (value.empty()) {
  419. SetFlagsHelpMode(HelpMode::kImportant);
  420. } else {
  421. SetFlagsHelpMode(HelpMode::kMatch);
  422. SetFlagsHelpMatchSubstr(value);
  423. }
  424. return true;
  425. }
  426. if (name == "match") {
  427. SetFlagsHelpMode(HelpMode::kMatch);
  428. SetFlagsHelpMatchSubstr(value);
  429. return true;
  430. }
  431. if (name == "on") {
  432. SetFlagsHelpMode(HelpMode::kMatch);
  433. SetFlagsHelpMatchSubstr(absl::StrCat("/", value, "."));
  434. return true;
  435. }
  436. if (name == "full") {
  437. SetFlagsHelpMode(HelpMode::kFull);
  438. return true;
  439. }
  440. if (name == "short") {
  441. SetFlagsHelpMode(HelpMode::kShort);
  442. return true;
  443. }
  444. if (name == "package") {
  445. SetFlagsHelpMode(HelpMode::kPackage);
  446. return true;
  447. }
  448. return false;
  449. }
  450. if (name == "version") {
  451. SetFlagsHelpMode(HelpMode::kVersion);
  452. return true;
  453. }
  454. if (name == "only_check_args") {
  455. SetFlagsHelpMode(HelpMode::kOnlyCheckArgs);
  456. return true;
  457. }
  458. return false;
  459. }
  460. // --------------------------------------------------------------------
  461. void MaybeExit(HelpMode mode) {
  462. switch (mode) {
  463. case flags_internal::HelpMode::kNone:
  464. return;
  465. case flags_internal::HelpMode::kOnlyCheckArgs:
  466. case flags_internal::HelpMode::kVersion:
  467. std::exit(0);
  468. default: // For all the other modes we exit with 1
  469. std::exit(1);
  470. }
  471. }
  472. // --------------------------------------------------------------------
  473. } // namespace flags_internal
  474. ABSL_NAMESPACE_END
  475. } // namespace absl