usage.cc 16 KB

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