ArgsParser.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  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/JsonObject.h"
  8. #include <AK/Format.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibCore/ArgsParser.h>
  11. #include <LibCore/Version.h>
  12. #include <getopt.h>
  13. #include <limits.h>
  14. #include <math.h>
  15. #include <stdio.h>
  16. #include <string.h>
  17. static Optional<double> convert_to_double(char const* s)
  18. {
  19. char* p;
  20. double v = strtod(s, &p);
  21. if (isnan(v) || p == s)
  22. return {};
  23. return v;
  24. }
  25. namespace Core {
  26. ArgsParser::ArgsParser()
  27. {
  28. add_option(m_show_help, "Display help message and exit", "help", 0, OptionHideMode::Markdown);
  29. add_option(m_show_version, "Print version", "version", 0, OptionHideMode::Markdown);
  30. add_option(m_perform_autocomplete, "Perform autocompletion", "complete", 0, OptionHideMode::CommandLineAndMarkdown);
  31. }
  32. bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_behavior)
  33. {
  34. auto fail = [this, argv, failure_behavior] {
  35. if (failure_behavior == FailureBehavior::PrintUsage || failure_behavior == FailureBehavior::PrintUsageAndExit)
  36. print_usage(stderr, argv[0]);
  37. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  38. exit(1);
  39. };
  40. Vector<option> long_options;
  41. StringBuilder short_options_builder;
  42. if (m_stop_on_first_non_option)
  43. short_options_builder.append('+');
  44. int index_of_found_long_option = -1;
  45. // Tell getopt() to reset its internal state, and start scanning from optind = 1.
  46. // We could also set optreset = 1, but the host platform may not support that.
  47. optind = 0;
  48. for (size_t i = 0; i < m_options.size(); i++) {
  49. auto& opt = m_options[i];
  50. if (opt.long_name) {
  51. option long_opt {
  52. opt.long_name,
  53. opt.requires_argument ? required_argument : no_argument,
  54. &index_of_found_long_option,
  55. static_cast<int>(i)
  56. };
  57. long_options.append(long_opt);
  58. }
  59. if (opt.short_name) {
  60. short_options_builder.append(opt.short_name);
  61. if (opt.requires_argument)
  62. short_options_builder.append(':');
  63. }
  64. }
  65. long_options.append({ 0, 0, 0, 0 });
  66. String short_options = short_options_builder.build();
  67. while (true) {
  68. int c = getopt_long(argc, argv, short_options.characters(), long_options.data(), nullptr);
  69. if (c == -1) {
  70. // We have reached the end.
  71. break;
  72. } else if (c == '?') {
  73. // There was an error, and getopt() has already
  74. // printed its error message.
  75. fail();
  76. return false;
  77. }
  78. // Let's see what option we just found.
  79. Option* found_option = nullptr;
  80. if (c == 0) {
  81. // It was a long option.
  82. VERIFY(index_of_found_long_option >= 0);
  83. found_option = &m_options[index_of_found_long_option];
  84. index_of_found_long_option = -1;
  85. } else {
  86. // It was a short option, look it up.
  87. auto it = m_options.find_if([c](auto& opt) { return c == opt.short_name; });
  88. VERIFY(!it.is_end());
  89. found_option = &*it;
  90. }
  91. VERIFY(found_option);
  92. char const* arg = found_option->requires_argument ? optarg : nullptr;
  93. if (!found_option->accept_value(arg)) {
  94. warnln("\033[31mInvalid value for option \033[1m{}\033[22m\033[0m", found_option->name_for_display());
  95. fail();
  96. return false;
  97. }
  98. }
  99. // We're done processing options.
  100. // Now let's show version or help if requested, or perform autocompletion if needed.
  101. if (m_show_version) {
  102. print_version(stdout);
  103. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  104. exit(0);
  105. return false;
  106. }
  107. if (m_show_help) {
  108. print_usage(stdout, argv[0]);
  109. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  110. exit(0);
  111. return false;
  112. }
  113. if (m_perform_autocomplete) {
  114. autocomplete(stdout, argv[0], Span<char const* const> { argv + optind, static_cast<size_t>(argc - optind) });
  115. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  116. exit(0);
  117. return false;
  118. }
  119. // Now let's parse positional arguments.
  120. int values_left = argc - optind;
  121. Vector<int, 16> num_values_for_arg;
  122. num_values_for_arg.resize(m_positional_args.size(), true);
  123. int total_values_required = 0;
  124. for (size_t i = 0; i < m_positional_args.size(); i++) {
  125. auto& arg = m_positional_args[i];
  126. num_values_for_arg[i] = arg.min_values;
  127. total_values_required += arg.min_values;
  128. }
  129. if (total_values_required > values_left) {
  130. fail();
  131. return false;
  132. }
  133. int extra_values_to_distribute = values_left - total_values_required;
  134. for (size_t i = 0; i < m_positional_args.size(); i++) {
  135. auto& arg = m_positional_args[i];
  136. int extra_values_to_this_arg = min(arg.max_values - arg.min_values, extra_values_to_distribute);
  137. num_values_for_arg[i] += extra_values_to_this_arg;
  138. extra_values_to_distribute -= extra_values_to_this_arg;
  139. if (extra_values_to_distribute == 0)
  140. break;
  141. }
  142. if (extra_values_to_distribute > 0) {
  143. // We still have too many values :(
  144. fail();
  145. return false;
  146. }
  147. for (size_t i = 0; i < m_positional_args.size(); i++) {
  148. auto& arg = m_positional_args[i];
  149. for (int j = 0; j < num_values_for_arg[i]; j++) {
  150. char const* value = argv[optind++];
  151. if (!arg.accept_value(value)) {
  152. warnln("Invalid value for argument {}", arg.name);
  153. fail();
  154. return false;
  155. }
  156. }
  157. }
  158. return true;
  159. }
  160. void ArgsParser::print_usage(FILE* file, char const* argv0)
  161. {
  162. char const* env_preference = getenv("ARGSPARSER_EMIT_MARKDOWN");
  163. if (env_preference != nullptr && env_preference[0] == '1' && env_preference[1] == 0) {
  164. print_usage_markdown(file, argv0);
  165. } else {
  166. print_usage_terminal(file, argv0);
  167. }
  168. }
  169. void ArgsParser::print_usage_terminal(FILE* file, char const* argv0)
  170. {
  171. out(file, "Usage:\n\t\033[1m{}\033[0m", argv0);
  172. for (auto& opt : m_options) {
  173. if (opt.hide_mode != OptionHideMode::None)
  174. continue;
  175. if (opt.requires_argument)
  176. out(file, " [{} {}]", opt.name_for_display(), opt.value_name);
  177. else
  178. out(file, " [{}]", opt.name_for_display());
  179. }
  180. for (auto& arg : m_positional_args) {
  181. bool required = arg.min_values > 0;
  182. bool repeated = arg.max_values > 1;
  183. if (required && repeated)
  184. out(file, " <{}...>", arg.name);
  185. else if (required && !repeated)
  186. out(file, " <{}>", arg.name);
  187. else if (!required && repeated)
  188. out(file, " [{}...]", arg.name);
  189. else if (!required && !repeated)
  190. out(file, " [{}]", arg.name);
  191. }
  192. outln(file);
  193. if (m_general_help != nullptr && m_general_help[0] != '\0') {
  194. outln(file, "\nDescription:");
  195. outln(file, "{}", m_general_help);
  196. }
  197. if (!m_options.is_empty())
  198. outln(file, "\nOptions:");
  199. for (auto& opt : m_options) {
  200. if (opt.hide_mode == OptionHideMode::CommandLineAndMarkdown)
  201. continue;
  202. auto print_argument = [&]() {
  203. if (opt.value_name) {
  204. if (opt.requires_argument)
  205. out(file, " {}", opt.value_name);
  206. else
  207. out(file, " [{}]", opt.value_name);
  208. }
  209. };
  210. out(file, "\t");
  211. if (opt.short_name) {
  212. out(file, "\033[1m-{}\033[0m", opt.short_name);
  213. print_argument();
  214. }
  215. if (opt.short_name && opt.long_name)
  216. out(file, ", ");
  217. if (opt.long_name) {
  218. out(file, "\033[1m--{}\033[0m", opt.long_name);
  219. print_argument();
  220. }
  221. if (opt.help_string)
  222. out(file, "\t{}", opt.help_string);
  223. outln(file);
  224. }
  225. if (!m_positional_args.is_empty())
  226. outln(file, "\nArguments:");
  227. for (auto& arg : m_positional_args) {
  228. out(file, "\t\033[1m{}\033[0m", arg.name);
  229. if (arg.help_string)
  230. out(file, "\t{}", arg.help_string);
  231. outln(file);
  232. }
  233. }
  234. void ArgsParser::print_usage_markdown(FILE* file, char const* argv0)
  235. {
  236. outln(file, "## Name\n\n{}", argv0);
  237. out(file, "\n## Synopsis\n\n```sh\n$ {}", argv0);
  238. for (auto& opt : m_options) {
  239. if (opt.hide_mode != OptionHideMode::None)
  240. continue;
  241. if (opt.requires_argument)
  242. out(file, " [{} {}]", opt.name_for_display(), opt.value_name);
  243. else
  244. out(file, " [{}]", opt.name_for_display());
  245. }
  246. for (auto& arg : m_positional_args) {
  247. bool required = arg.min_values > 0;
  248. bool repeated = arg.max_values > 1;
  249. if (required && repeated)
  250. out(file, " <{}...>", arg.name);
  251. else if (required && !repeated)
  252. out(file, " <{}>", arg.name);
  253. else if (!required && repeated)
  254. out(file, " [{}...]", arg.name);
  255. else if (!required && !repeated)
  256. out(file, " [{}]", arg.name);
  257. }
  258. outln(file, "\n```");
  259. if (m_general_help != nullptr && m_general_help[0] != '\0') {
  260. outln(file, "\n## Description\n\n{}", m_general_help);
  261. }
  262. auto should_display_option = [](Option& opt) {
  263. return !(opt.hide_mode == OptionHideMode::Markdown || opt.hide_mode == OptionHideMode::CommandLineAndMarkdown);
  264. };
  265. size_t options_to_display = 0;
  266. for (auto& opt : m_options) {
  267. if (!should_display_option(opt))
  268. continue;
  269. options_to_display++;
  270. }
  271. if (options_to_display > 0)
  272. outln(file, "\n## Options:\n");
  273. for (auto& opt : m_options) {
  274. if (!should_display_option(opt))
  275. continue;
  276. auto print_argument = [&]() {
  277. if (opt.value_name != nullptr) {
  278. if (opt.requires_argument)
  279. out(file, " {}", opt.value_name);
  280. else
  281. out(file, " [{}]", opt.value_name);
  282. }
  283. };
  284. out(file, "* ");
  285. if (opt.short_name != '\0') {
  286. out(file, "`-{}", opt.short_name);
  287. print_argument();
  288. out(file, "`");
  289. }
  290. if (opt.short_name != '\0' && opt.long_name != nullptr)
  291. out(file, ", ");
  292. if (opt.long_name != nullptr) {
  293. out(file, "`--{}", opt.long_name);
  294. print_argument();
  295. out(file, "`");
  296. }
  297. if (opt.help_string != nullptr)
  298. out(file, ": {}", opt.help_string);
  299. outln(file);
  300. }
  301. if (!m_positional_args.is_empty())
  302. outln(file, "\n## Arguments:\n");
  303. for (auto& arg : m_positional_args) {
  304. out(file, "* `{}`", arg.name);
  305. if (arg.help_string != nullptr)
  306. out(file, ": {}", arg.help_string);
  307. outln(file);
  308. }
  309. }
  310. void ArgsParser::print_version(FILE* file)
  311. {
  312. outln(file, Core::Version::SERENITY_VERSION);
  313. }
  314. void ArgsParser::add_option(Option&& option)
  315. {
  316. m_options.append(move(option));
  317. }
  318. void ArgsParser::add_ignored(char const* long_name, char short_name, OptionHideMode hide_mode)
  319. {
  320. Option option {
  321. false,
  322. "Ignored",
  323. long_name,
  324. short_name,
  325. nullptr,
  326. [](char const*) {
  327. return true;
  328. },
  329. hide_mode,
  330. };
  331. add_option(move(option));
  332. }
  333. void ArgsParser::add_option(bool& value, char const* help_string, char const* long_name, char short_name, OptionHideMode hide_mode)
  334. {
  335. Option option {
  336. false,
  337. help_string,
  338. long_name,
  339. short_name,
  340. nullptr,
  341. [&value](char const* s) {
  342. VERIFY(s == nullptr);
  343. value = true;
  344. return true;
  345. },
  346. hide_mode,
  347. };
  348. add_option(move(option));
  349. }
  350. void ArgsParser::add_option(char const*& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  351. {
  352. Option option {
  353. true,
  354. help_string,
  355. long_name,
  356. short_name,
  357. value_name,
  358. [&value](char const* s) {
  359. value = s;
  360. return true;
  361. },
  362. hide_mode,
  363. };
  364. add_option(move(option));
  365. }
  366. void ArgsParser::add_option(String& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  367. {
  368. Option option {
  369. true,
  370. help_string,
  371. long_name,
  372. short_name,
  373. value_name,
  374. [&value](char const* s) {
  375. value = s;
  376. return true;
  377. },
  378. hide_mode,
  379. };
  380. add_option(move(option));
  381. }
  382. void ArgsParser::add_option(StringView& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  383. {
  384. Option option {
  385. true,
  386. help_string,
  387. long_name,
  388. short_name,
  389. value_name,
  390. [&value](char const* s) {
  391. value = s;
  392. return true;
  393. },
  394. hide_mode,
  395. };
  396. add_option(move(option));
  397. }
  398. void ArgsParser::add_option(int& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  399. {
  400. Option option {
  401. true,
  402. help_string,
  403. long_name,
  404. short_name,
  405. value_name,
  406. [&value](char const* s) {
  407. auto opt = StringView(s).to_int();
  408. value = opt.value_or(0);
  409. return opt.has_value();
  410. },
  411. hide_mode,
  412. };
  413. add_option(move(option));
  414. }
  415. void ArgsParser::add_option(unsigned& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  416. {
  417. Option option {
  418. true,
  419. help_string,
  420. long_name,
  421. short_name,
  422. value_name,
  423. [&value](char const* s) {
  424. auto opt = StringView(s).to_uint();
  425. value = opt.value_or(0);
  426. return opt.has_value();
  427. },
  428. hide_mode,
  429. };
  430. add_option(move(option));
  431. }
  432. void ArgsParser::add_option(double& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  433. {
  434. Option option {
  435. true,
  436. help_string,
  437. long_name,
  438. short_name,
  439. value_name,
  440. [&value](char const* s) {
  441. auto opt = convert_to_double(s);
  442. value = opt.value_or(0.0);
  443. return opt.has_value();
  444. },
  445. hide_mode,
  446. };
  447. add_option(move(option));
  448. }
  449. void ArgsParser::add_option(Optional<double>& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  450. {
  451. Option option {
  452. true,
  453. help_string,
  454. long_name,
  455. short_name,
  456. value_name,
  457. [&value](char const* s) {
  458. value = convert_to_double(s);
  459. return value.has_value();
  460. },
  461. hide_mode,
  462. };
  463. add_option(move(option));
  464. }
  465. void ArgsParser::add_option(Optional<size_t>& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  466. {
  467. Option option {
  468. true,
  469. help_string,
  470. long_name,
  471. short_name,
  472. value_name,
  473. [&value](char const* s) {
  474. value = AK::StringUtils::convert_to_uint<size_t>(s);
  475. return value.has_value();
  476. },
  477. hide_mode,
  478. };
  479. add_option(move(option));
  480. }
  481. void ArgsParser::add_option(Vector<size_t>& values, char const* help_string, char const* long_name, char short_name, char const* value_name, char separator, OptionHideMode hide_mode)
  482. {
  483. Option option {
  484. true,
  485. help_string,
  486. long_name,
  487. short_name,
  488. value_name,
  489. [&values, separator](char const* s) {
  490. bool parsed_all_values = true;
  491. StringView { s }.for_each_split_view(separator, false, [&](auto value) {
  492. if (auto maybe_value = AK::StringUtils::convert_to_uint<size_t>(value); maybe_value.has_value())
  493. values.append(*maybe_value);
  494. else
  495. parsed_all_values = false;
  496. });
  497. return parsed_all_values;
  498. },
  499. hide_mode
  500. };
  501. add_option(move(option));
  502. }
  503. void ArgsParser::add_positional_argument(Arg&& arg)
  504. {
  505. m_positional_args.append(move(arg));
  506. }
  507. void ArgsParser::add_positional_argument(char const*& value, char const* help_string, char const* name, Required required)
  508. {
  509. Arg arg {
  510. help_string,
  511. name,
  512. required == Required::Yes ? 1 : 0,
  513. 1,
  514. [&value](char const* s) {
  515. value = s;
  516. return true;
  517. }
  518. };
  519. add_positional_argument(move(arg));
  520. }
  521. void ArgsParser::add_positional_argument(String& value, char const* help_string, char const* name, Required required)
  522. {
  523. Arg arg {
  524. help_string,
  525. name,
  526. required == Required::Yes ? 1 : 0,
  527. 1,
  528. [&value](char const* s) {
  529. value = s;
  530. return true;
  531. }
  532. };
  533. add_positional_argument(move(arg));
  534. }
  535. void ArgsParser::add_positional_argument(StringView& value, char const* help_string, char const* name, Required required)
  536. {
  537. Arg arg {
  538. help_string,
  539. name,
  540. required == Required::Yes ? 1 : 0,
  541. 1,
  542. [&value](char const* s) {
  543. value = s;
  544. return true;
  545. }
  546. };
  547. add_positional_argument(move(arg));
  548. }
  549. void ArgsParser::add_positional_argument(int& value, char const* help_string, char const* name, Required required)
  550. {
  551. Arg arg {
  552. help_string,
  553. name,
  554. required == Required::Yes ? 1 : 0,
  555. 1,
  556. [&value](char const* s) {
  557. auto opt = StringView(s).to_int();
  558. value = opt.value_or(0);
  559. return opt.has_value();
  560. }
  561. };
  562. add_positional_argument(move(arg));
  563. }
  564. void ArgsParser::add_positional_argument(unsigned& value, char const* help_string, char const* name, Required required)
  565. {
  566. Arg arg {
  567. help_string,
  568. name,
  569. required == Required::Yes ? 1 : 0,
  570. 1,
  571. [&value](char const* s) {
  572. auto opt = StringView(s).to_uint();
  573. value = opt.value_or(0);
  574. return opt.has_value();
  575. }
  576. };
  577. add_positional_argument(move(arg));
  578. }
  579. void ArgsParser::add_positional_argument(double& value, char const* help_string, char const* name, Required required)
  580. {
  581. Arg arg {
  582. help_string,
  583. name,
  584. required == Required::Yes ? 1 : 0,
  585. 1,
  586. [&value](char const* s) {
  587. auto opt = convert_to_double(s);
  588. value = opt.value_or(0.0);
  589. return opt.has_value();
  590. }
  591. };
  592. add_positional_argument(move(arg));
  593. }
  594. void ArgsParser::add_positional_argument(Vector<char const*>& values, char const* help_string, char const* name, Required required)
  595. {
  596. Arg arg {
  597. help_string,
  598. name,
  599. required == Required::Yes ? 1 : 0,
  600. INT_MAX,
  601. [&values](char const* s) {
  602. values.append(s);
  603. return true;
  604. }
  605. };
  606. add_positional_argument(move(arg));
  607. }
  608. void ArgsParser::add_positional_argument(Vector<StringView>& values, char const* help_string, char const* name, Required required)
  609. {
  610. Arg arg {
  611. help_string,
  612. name,
  613. required == Required::Yes ? 1 : 0,
  614. INT_MAX,
  615. [&values](char const* s) {
  616. values.append(s);
  617. return true;
  618. }
  619. };
  620. add_positional_argument(move(arg));
  621. }
  622. void ArgsParser::autocomplete(FILE* file, StringView program_name, Span<char const* const> remaining_arguments)
  623. {
  624. // We expect the full invocation of the program to be available as positional args,
  625. // e.g. `foo --bar arg -b` (program invoked as `foo --complete -- foo --bar arg -b`)
  626. auto first = true;
  627. auto seen_all_options = false;
  628. auto skip_next = false;
  629. StringView argument_to_complete;
  630. StringView option_to_complete;
  631. auto completing_option = false;
  632. for (auto& arg : remaining_arguments) {
  633. StringView argument { arg };
  634. completing_option = false;
  635. if (skip_next) {
  636. argument_to_complete = argument;
  637. skip_next = false;
  638. continue;
  639. }
  640. // Skip over the program name.
  641. if (first && program_name == argument) {
  642. first = false;
  643. continue;
  644. }
  645. if (seen_all_options) {
  646. argument_to_complete = argument;
  647. continue;
  648. }
  649. if (argument.starts_with("--")) {
  650. option_to_complete = argument;
  651. completing_option = true;
  652. if (argument == "--") {
  653. seen_all_options = true;
  654. continue;
  655. }
  656. // Look for a long option
  657. auto option_pattern = argument.substring_view(2);
  658. auto it = m_options.find_if([&](auto& option) { return option.hide_mode != OptionHideMode::None && StringView(option.long_name) == option_pattern; });
  659. if (it.is_end())
  660. continue;
  661. if (it->requires_argument)
  662. skip_next = true;
  663. continue;
  664. }
  665. if (argument.starts_with("-")) {
  666. option_to_complete = argument;
  667. completing_option = true;
  668. if (argument == "-") {
  669. option_to_complete = argument;
  670. continue;
  671. }
  672. // Look for a short option
  673. auto option_pattern = argument[argument.length() - 1];
  674. auto it = m_options.find_if([&](auto& option) { return option.hide_mode != OptionHideMode::None && option.short_name == option_pattern; });
  675. if (it.is_end())
  676. continue;
  677. if (it->requires_argument)
  678. skip_next = true;
  679. continue;
  680. }
  681. }
  682. // We don't know how to complete arguments quite yet.
  683. if (!completing_option)
  684. return;
  685. auto write_completion = [&](auto format, auto& option, auto has_invariant, auto... args) {
  686. JsonObject object;
  687. object.set("completion", String::formatted(format, args...));
  688. object.set("static_offset", 0);
  689. object.set("invariant_offset", has_invariant ? option_to_complete.length() : 0u);
  690. object.set("display_trivia", option.help_string);
  691. object.set("trailing_trivia", option.requires_argument ? " " : "");
  692. outln(file, "{}", object.to_string());
  693. };
  694. if (option_to_complete.starts_with("--")) {
  695. // Complete a long option.
  696. auto option_pattern = option_to_complete.substring_view(2);
  697. for (auto& option : m_options) {
  698. if (option.hide_mode != OptionHideMode::None)
  699. continue;
  700. StringView option_string = option.long_name;
  701. if (option_string.starts_with(option_pattern)) {
  702. write_completion("--{}", option, true, option_string);
  703. }
  704. }
  705. } else {
  706. // Complete a short option, note that we're not going to attempt to 'match' anything here.
  707. for (auto& option : m_options) {
  708. if (option.hide_mode != OptionHideMode::None)
  709. continue;
  710. if (option.short_name == 0)
  711. continue;
  712. auto has_invariant = option_to_complete == "-";
  713. write_completion("{}{}", option, has_invariant, has_invariant ? "-" : "", option.short_name);
  714. }
  715. }
  716. }
  717. }