ArgsParser.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. /*
  2. * Copyright (c) 2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Format.h>
  7. #include <AK/StringBuilder.h>
  8. #include <LibCore/ArgsParser.h>
  9. #include <LibCore/Version.h>
  10. #include <getopt.h>
  11. #include <limits.h>
  12. #include <math.h>
  13. #include <stdio.h>
  14. #include <string.h>
  15. static Optional<double> convert_to_double(const char* s)
  16. {
  17. char* p;
  18. double v = strtod(s, &p);
  19. if (isnan(v) || p == s)
  20. return {};
  21. return v;
  22. }
  23. namespace Core {
  24. ArgsParser::ArgsParser()
  25. {
  26. add_option(m_show_help, "Display help message and exit", "help", 0);
  27. add_option(m_show_version, "Print version", "version", 0);
  28. }
  29. bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_behavior)
  30. {
  31. auto fail = [this, argv, failure_behavior] {
  32. if (failure_behavior == FailureBehavior::PrintUsage || failure_behavior == FailureBehavior::PrintUsageAndExit)
  33. print_usage(stderr, argv[0]);
  34. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  35. exit(1);
  36. };
  37. Vector<option> long_options;
  38. StringBuilder short_options_builder;
  39. if (m_stop_on_first_non_option)
  40. short_options_builder.append('+');
  41. int index_of_found_long_option = -1;
  42. // Tell getopt() to reset its internal state, and start scanning from optind = 1.
  43. // We could also set optreset = 1, but the host platform may not support that.
  44. optind = 0;
  45. for (size_t i = 0; i < m_options.size(); i++) {
  46. auto& opt = m_options[i];
  47. if (opt.long_name) {
  48. option long_opt {
  49. opt.long_name,
  50. opt.requires_argument ? required_argument : no_argument,
  51. &index_of_found_long_option,
  52. static_cast<int>(i)
  53. };
  54. long_options.append(long_opt);
  55. }
  56. if (opt.short_name) {
  57. short_options_builder.append(opt.short_name);
  58. if (opt.requires_argument)
  59. short_options_builder.append(':');
  60. }
  61. }
  62. long_options.append({ 0, 0, 0, 0 });
  63. String short_options = short_options_builder.build();
  64. while (true) {
  65. int c = getopt_long(argc, argv, short_options.characters(), long_options.data(), nullptr);
  66. if (c == -1) {
  67. // We have reached the end.
  68. break;
  69. } else if (c == '?') {
  70. // There was an error, and getopt() has already
  71. // printed its error message.
  72. fail();
  73. return false;
  74. }
  75. // Let's see what option we just found.
  76. Option* found_option = nullptr;
  77. if (c == 0) {
  78. // It was a long option.
  79. VERIFY(index_of_found_long_option >= 0);
  80. found_option = &m_options[index_of_found_long_option];
  81. index_of_found_long_option = -1;
  82. } else {
  83. // It was a short option, look it up.
  84. auto it = m_options.find_if([c](auto& opt) { return c == opt.short_name; });
  85. VERIFY(!it.is_end());
  86. found_option = &*it;
  87. }
  88. VERIFY(found_option);
  89. const char* arg = found_option->requires_argument ? optarg : nullptr;
  90. if (!found_option->accept_value(arg)) {
  91. warnln("\033[31mInvalid value for option \033[1m{}\033[22m\033[0m", found_option->name_for_display());
  92. fail();
  93. return false;
  94. }
  95. }
  96. // We're done processing options.
  97. // Now let's show version or help if requested.
  98. if (m_show_version) {
  99. print_version(stdout);
  100. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  101. exit(0);
  102. return false;
  103. }
  104. if (m_show_help) {
  105. print_usage(stdout, argv[0]);
  106. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  107. exit(0);
  108. return false;
  109. }
  110. // Now let's parse positional arguments.
  111. int values_left = argc - optind;
  112. Vector<int, 16> num_values_for_arg;
  113. num_values_for_arg.resize(m_positional_args.size(), true);
  114. int total_values_required = 0;
  115. for (size_t i = 0; i < m_positional_args.size(); i++) {
  116. auto& arg = m_positional_args[i];
  117. num_values_for_arg[i] = arg.min_values;
  118. total_values_required += arg.min_values;
  119. }
  120. if (total_values_required > values_left) {
  121. fail();
  122. return false;
  123. }
  124. int extra_values_to_distribute = values_left - total_values_required;
  125. for (size_t i = 0; i < m_positional_args.size(); i++) {
  126. auto& arg = m_positional_args[i];
  127. int extra_values_to_this_arg = min(arg.max_values - arg.min_values, extra_values_to_distribute);
  128. num_values_for_arg[i] += extra_values_to_this_arg;
  129. extra_values_to_distribute -= extra_values_to_this_arg;
  130. if (extra_values_to_distribute == 0)
  131. break;
  132. }
  133. if (extra_values_to_distribute > 0) {
  134. // We still have too many values :(
  135. fail();
  136. return false;
  137. }
  138. for (size_t i = 0; i < m_positional_args.size(); i++) {
  139. auto& arg = m_positional_args[i];
  140. for (int j = 0; j < num_values_for_arg[i]; j++) {
  141. const char* value = argv[optind++];
  142. if (!arg.accept_value(value)) {
  143. warnln("Invalid value for argument {}", arg.name);
  144. fail();
  145. return false;
  146. }
  147. }
  148. }
  149. return true;
  150. }
  151. void ArgsParser::print_usage(FILE* file, const char* argv0)
  152. {
  153. char const* env_preference = getenv("ARGSPARSER_EMIT_MARKDOWN");
  154. if (env_preference != nullptr && env_preference[0] == '1' && env_preference[1] == 0) {
  155. print_usage_markdown(file, argv0);
  156. } else {
  157. print_usage_terminal(file, argv0);
  158. }
  159. }
  160. void ArgsParser::print_usage_terminal(FILE* file, const char* argv0)
  161. {
  162. out(file, "Usage:\n\t\033[1m{}\033[0m", argv0);
  163. for (auto& opt : m_options) {
  164. if (opt.long_name && !strcmp(opt.long_name, "help"))
  165. continue;
  166. if (opt.requires_argument)
  167. out(file, " [{} {}]", opt.name_for_display(), opt.value_name);
  168. else
  169. out(file, " [{}]", opt.name_for_display());
  170. }
  171. for (auto& arg : m_positional_args) {
  172. bool required = arg.min_values > 0;
  173. bool repeated = arg.max_values > 1;
  174. if (required && repeated)
  175. out(file, " <{}...>", arg.name);
  176. else if (required && !repeated)
  177. out(file, " <{}>", arg.name);
  178. else if (!required && repeated)
  179. out(file, " [{}...]", arg.name);
  180. else if (!required && !repeated)
  181. out(file, " [{}]", arg.name);
  182. }
  183. outln(file);
  184. if (m_general_help != nullptr && m_general_help[0] != '\0') {
  185. outln(file, "\nDescription:");
  186. outln(file, "{}", m_general_help);
  187. }
  188. if (!m_options.is_empty())
  189. outln(file, "\nOptions:");
  190. for (auto& opt : m_options) {
  191. auto print_argument = [&]() {
  192. if (opt.value_name) {
  193. if (opt.requires_argument)
  194. out(file, " {}", opt.value_name);
  195. else
  196. out(file, " [{}]", opt.value_name);
  197. }
  198. };
  199. out(file, "\t");
  200. if (opt.short_name) {
  201. out(file, "\033[1m-{}\033[0m", opt.short_name);
  202. print_argument();
  203. }
  204. if (opt.short_name && opt.long_name)
  205. out(file, ", ");
  206. if (opt.long_name) {
  207. out(file, "\033[1m--{}\033[0m", opt.long_name);
  208. print_argument();
  209. }
  210. if (opt.help_string)
  211. out(file, "\t{}", opt.help_string);
  212. outln(file);
  213. }
  214. if (!m_positional_args.is_empty())
  215. outln(file, "\nArguments:");
  216. for (auto& arg : m_positional_args) {
  217. out(file, "\t\033[1m{}\033[0m", arg.name);
  218. if (arg.help_string)
  219. out(file, "\t{}", arg.help_string);
  220. outln(file);
  221. }
  222. }
  223. void ArgsParser::print_usage_markdown(FILE* file, const char* argv0)
  224. {
  225. outln(file, "## Name\n\n{}", argv0);
  226. out(file, "\n## Synopsis\n\n```sh\n$ {}", argv0);
  227. for (auto& opt : m_options) {
  228. if (opt.long_name != nullptr && (!strcmp(opt.long_name, "help") || !strcmp(opt.long_name, "version")))
  229. continue;
  230. if (opt.requires_argument)
  231. out(file, " [{} {}]", opt.name_for_display(), opt.value_name);
  232. else
  233. out(file, " [{}]", opt.name_for_display());
  234. }
  235. for (auto& arg : m_positional_args) {
  236. bool required = arg.min_values > 0;
  237. bool repeated = arg.max_values > 1;
  238. if (required && repeated)
  239. out(file, " <{}...>", arg.name);
  240. else if (required && !repeated)
  241. out(file, " <{}>", arg.name);
  242. else if (!required && repeated)
  243. out(file, " [{}...]", arg.name);
  244. else if (!required && !repeated)
  245. out(file, " [{}]", arg.name);
  246. }
  247. outln(file, "\n```");
  248. if (m_general_help != nullptr && m_general_help[0] != '\0') {
  249. outln(file, "\n## Description\n\n{}", m_general_help);
  250. }
  251. if (!m_options.is_empty())
  252. outln(file, "\n## Options:\n");
  253. for (auto& opt : m_options) {
  254. auto print_argument = [&]() {
  255. if (opt.value_name != nullptr) {
  256. if (opt.requires_argument)
  257. out(file, " {}", opt.value_name);
  258. else
  259. out(file, " [{}]", opt.value_name);
  260. }
  261. };
  262. out(file, "* ");
  263. if (opt.short_name != '\0') {
  264. out(file, "`-{}", opt.short_name);
  265. print_argument();
  266. out(file, "`");
  267. }
  268. if (opt.short_name != '\0' && opt.long_name != nullptr)
  269. out(file, ", ");
  270. if (opt.long_name != nullptr) {
  271. out(file, "`--{}", opt.long_name);
  272. print_argument();
  273. out(file, "`");
  274. }
  275. if (opt.help_string != nullptr)
  276. out(file, ": {}", opt.help_string);
  277. outln(file);
  278. }
  279. if (!m_positional_args.is_empty())
  280. outln(file, "\n## Arguments:\n");
  281. for (auto& arg : m_positional_args) {
  282. out(file, "* `{}`", arg.name);
  283. if (arg.help_string != nullptr)
  284. out(file, ": {}", arg.help_string);
  285. outln(file);
  286. }
  287. }
  288. void ArgsParser::print_version(FILE* file)
  289. {
  290. outln(file, Core::Version::SERENITY_VERSION);
  291. }
  292. void ArgsParser::add_option(Option&& option)
  293. {
  294. m_options.append(move(option));
  295. }
  296. void ArgsParser::add_ignored(const char* long_name, char short_name)
  297. {
  298. Option option {
  299. false,
  300. "Ignored",
  301. long_name,
  302. short_name,
  303. nullptr,
  304. [](const char*) {
  305. return true;
  306. }
  307. };
  308. add_option(move(option));
  309. }
  310. void ArgsParser::add_option(bool& value, const char* help_string, const char* long_name, char short_name)
  311. {
  312. Option option {
  313. false,
  314. help_string,
  315. long_name,
  316. short_name,
  317. nullptr,
  318. [&value](const char* s) {
  319. VERIFY(s == nullptr);
  320. value = true;
  321. return true;
  322. }
  323. };
  324. add_option(move(option));
  325. }
  326. void ArgsParser::add_option(const char*& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  327. {
  328. Option option {
  329. true,
  330. help_string,
  331. long_name,
  332. short_name,
  333. value_name,
  334. [&value](const char* s) {
  335. value = s;
  336. return true;
  337. }
  338. };
  339. add_option(move(option));
  340. }
  341. void ArgsParser::add_option(String& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  342. {
  343. Option option {
  344. true,
  345. help_string,
  346. long_name,
  347. short_name,
  348. value_name,
  349. [&value](const char* s) {
  350. value = s;
  351. return true;
  352. }
  353. };
  354. add_option(move(option));
  355. }
  356. void ArgsParser::add_option(StringView& value, char const* help_string, char const* long_name, char short_name, char const* value_name)
  357. {
  358. Option option {
  359. true,
  360. help_string,
  361. long_name,
  362. short_name,
  363. value_name,
  364. [&value](const char* s) {
  365. value = s;
  366. return true;
  367. }
  368. };
  369. add_option(move(option));
  370. }
  371. void ArgsParser::add_option(int& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  372. {
  373. Option option {
  374. true,
  375. help_string,
  376. long_name,
  377. short_name,
  378. value_name,
  379. [&value](const char* s) {
  380. auto opt = StringView(s).to_int();
  381. value = opt.value_or(0);
  382. return opt.has_value();
  383. }
  384. };
  385. add_option(move(option));
  386. }
  387. void ArgsParser::add_option(unsigned& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  388. {
  389. Option option {
  390. true,
  391. help_string,
  392. long_name,
  393. short_name,
  394. value_name,
  395. [&value](const char* s) {
  396. auto opt = StringView(s).to_uint();
  397. value = opt.value_or(0);
  398. return opt.has_value();
  399. }
  400. };
  401. add_option(move(option));
  402. }
  403. void ArgsParser::add_option(double& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  404. {
  405. Option option {
  406. true,
  407. help_string,
  408. long_name,
  409. short_name,
  410. value_name,
  411. [&value](const char* s) {
  412. auto opt = convert_to_double(s);
  413. value = opt.value_or(0.0);
  414. return opt.has_value();
  415. }
  416. };
  417. add_option(move(option));
  418. }
  419. void ArgsParser::add_positional_argument(Arg&& arg)
  420. {
  421. m_positional_args.append(move(arg));
  422. }
  423. void ArgsParser::add_positional_argument(const char*& value, const char* help_string, const char* name, Required required)
  424. {
  425. Arg arg {
  426. help_string,
  427. name,
  428. required == Required::Yes ? 1 : 0,
  429. 1,
  430. [&value](const char* s) {
  431. value = s;
  432. return true;
  433. }
  434. };
  435. add_positional_argument(move(arg));
  436. }
  437. void ArgsParser::add_positional_argument(String& value, const char* help_string, const char* name, Required required)
  438. {
  439. Arg arg {
  440. help_string,
  441. name,
  442. required == Required::Yes ? 1 : 0,
  443. 1,
  444. [&value](const char* s) {
  445. value = s;
  446. return true;
  447. }
  448. };
  449. add_positional_argument(move(arg));
  450. }
  451. void ArgsParser::add_positional_argument(StringView& value, char const* help_string, char const* name, Required required)
  452. {
  453. Arg arg {
  454. help_string,
  455. name,
  456. required == Required::Yes ? 1 : 0,
  457. 1,
  458. [&value](const char* s) {
  459. value = s;
  460. return true;
  461. }
  462. };
  463. add_positional_argument(move(arg));
  464. }
  465. void ArgsParser::add_positional_argument(int& value, const char* help_string, const char* name, Required required)
  466. {
  467. Arg arg {
  468. help_string,
  469. name,
  470. required == Required::Yes ? 1 : 0,
  471. 1,
  472. [&value](const char* s) {
  473. auto opt = StringView(s).to_int();
  474. value = opt.value_or(0);
  475. return opt.has_value();
  476. }
  477. };
  478. add_positional_argument(move(arg));
  479. }
  480. void ArgsParser::add_positional_argument(unsigned& value, const char* help_string, const char* name, Required required)
  481. {
  482. Arg arg {
  483. help_string,
  484. name,
  485. required == Required::Yes ? 1 : 0,
  486. 1,
  487. [&value](const char* s) {
  488. auto opt = StringView(s).to_uint();
  489. value = opt.value_or(0);
  490. return opt.has_value();
  491. }
  492. };
  493. add_positional_argument(move(arg));
  494. }
  495. void ArgsParser::add_positional_argument(double& value, const char* help_string, const char* name, Required required)
  496. {
  497. Arg arg {
  498. help_string,
  499. name,
  500. required == Required::Yes ? 1 : 0,
  501. 1,
  502. [&value](const char* s) {
  503. auto opt = convert_to_double(s);
  504. value = opt.value_or(0.0);
  505. return opt.has_value();
  506. }
  507. };
  508. add_positional_argument(move(arg));
  509. }
  510. void ArgsParser::add_positional_argument(Vector<const char*>& values, const char* help_string, const char* name, Required required)
  511. {
  512. Arg arg {
  513. help_string,
  514. name,
  515. required == Required::Yes ? 1 : 0,
  516. INT_MAX,
  517. [&values](const char* s) {
  518. values.append(s);
  519. return true;
  520. }
  521. };
  522. add_positional_argument(move(arg));
  523. }
  524. void ArgsParser::add_positional_argument(Vector<StringView>& values, char const* help_string, char const* name, Required required)
  525. {
  526. Arg arg {
  527. help_string,
  528. name,
  529. required == Required::Yes ? 1 : 0,
  530. INT_MAX,
  531. [&values](char const* s) {
  532. values.append(s);
  533. return true;
  534. }
  535. };
  536. add_positional_argument(move(arg));
  537. }
  538. }