usage.cc 16 KB

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