ArgsParser.cpp 17 KB

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