ArgsParser.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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. if (!m_options.is_empty())
  263. outln(file, "\n## Options:\n");
  264. for (auto& opt : m_options) {
  265. if (opt.hide_mode == OptionHideMode::Markdown || opt.hide_mode == OptionHideMode::CommandLineAndMarkdown)
  266. continue;
  267. auto print_argument = [&]() {
  268. if (opt.value_name != nullptr) {
  269. if (opt.requires_argument)
  270. out(file, " {}", opt.value_name);
  271. else
  272. out(file, " [{}]", opt.value_name);
  273. }
  274. };
  275. out(file, "* ");
  276. if (opt.short_name != '\0') {
  277. out(file, "`-{}", opt.short_name);
  278. print_argument();
  279. out(file, "`");
  280. }
  281. if (opt.short_name != '\0' && opt.long_name != nullptr)
  282. out(file, ", ");
  283. if (opt.long_name != nullptr) {
  284. out(file, "`--{}", opt.long_name);
  285. print_argument();
  286. out(file, "`");
  287. }
  288. if (opt.help_string != nullptr)
  289. out(file, ": {}", opt.help_string);
  290. outln(file);
  291. }
  292. if (!m_positional_args.is_empty())
  293. outln(file, "\n## Arguments:\n");
  294. for (auto& arg : m_positional_args) {
  295. out(file, "* `{}`", arg.name);
  296. if (arg.help_string != nullptr)
  297. out(file, ": {}", arg.help_string);
  298. outln(file);
  299. }
  300. }
  301. void ArgsParser::print_version(FILE* file)
  302. {
  303. outln(file, Core::Version::SERENITY_VERSION);
  304. }
  305. void ArgsParser::add_option(Option&& option)
  306. {
  307. m_options.append(move(option));
  308. }
  309. void ArgsParser::add_ignored(char const* long_name, char short_name, OptionHideMode hide_mode)
  310. {
  311. Option option {
  312. false,
  313. "Ignored",
  314. long_name,
  315. short_name,
  316. nullptr,
  317. [](char const*) {
  318. return true;
  319. },
  320. hide_mode,
  321. };
  322. add_option(move(option));
  323. }
  324. void ArgsParser::add_option(bool& value, char const* help_string, char const* long_name, char short_name, OptionHideMode hide_mode)
  325. {
  326. Option option {
  327. false,
  328. help_string,
  329. long_name,
  330. short_name,
  331. nullptr,
  332. [&value](char const* s) {
  333. VERIFY(s == nullptr);
  334. value = true;
  335. return true;
  336. },
  337. hide_mode,
  338. };
  339. add_option(move(option));
  340. }
  341. 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)
  342. {
  343. Option option {
  344. true,
  345. help_string,
  346. long_name,
  347. short_name,
  348. value_name,
  349. [&value](char const* s) {
  350. value = s;
  351. return true;
  352. },
  353. hide_mode,
  354. };
  355. add_option(move(option));
  356. }
  357. void ArgsParser::add_option(String& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  358. {
  359. Option option {
  360. true,
  361. help_string,
  362. long_name,
  363. short_name,
  364. value_name,
  365. [&value](char const* s) {
  366. value = s;
  367. return true;
  368. },
  369. hide_mode,
  370. };
  371. add_option(move(option));
  372. }
  373. void ArgsParser::add_option(StringView& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  374. {
  375. Option option {
  376. true,
  377. help_string,
  378. long_name,
  379. short_name,
  380. value_name,
  381. [&value](char const* s) {
  382. value = s;
  383. return true;
  384. },
  385. hide_mode,
  386. };
  387. add_option(move(option));
  388. }
  389. void ArgsParser::add_option(int& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  390. {
  391. Option option {
  392. true,
  393. help_string,
  394. long_name,
  395. short_name,
  396. value_name,
  397. [&value](char const* s) {
  398. auto opt = StringView(s).to_int();
  399. value = opt.value_or(0);
  400. return opt.has_value();
  401. },
  402. hide_mode,
  403. };
  404. add_option(move(option));
  405. }
  406. void ArgsParser::add_option(unsigned& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  407. {
  408. Option option {
  409. true,
  410. help_string,
  411. long_name,
  412. short_name,
  413. value_name,
  414. [&value](char const* s) {
  415. auto opt = StringView(s).to_uint();
  416. value = opt.value_or(0);
  417. return opt.has_value();
  418. },
  419. hide_mode,
  420. };
  421. add_option(move(option));
  422. }
  423. void ArgsParser::add_option(double& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  424. {
  425. Option option {
  426. true,
  427. help_string,
  428. long_name,
  429. short_name,
  430. value_name,
  431. [&value](char const* s) {
  432. auto opt = convert_to_double(s);
  433. value = opt.value_or(0.0);
  434. return opt.has_value();
  435. },
  436. hide_mode,
  437. };
  438. add_option(move(option));
  439. }
  440. 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)
  441. {
  442. Option option {
  443. true,
  444. help_string,
  445. long_name,
  446. short_name,
  447. value_name,
  448. [&value](char const* s) {
  449. value = convert_to_double(s);
  450. return value.has_value();
  451. },
  452. hide_mode,
  453. };
  454. add_option(move(option));
  455. }
  456. 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)
  457. {
  458. Option option {
  459. true,
  460. help_string,
  461. long_name,
  462. short_name,
  463. value_name,
  464. [&value](char const* s) {
  465. value = AK::StringUtils::convert_to_uint<size_t>(s);
  466. return value.has_value();
  467. },
  468. hide_mode,
  469. };
  470. add_option(move(option));
  471. }
  472. 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)
  473. {
  474. Option option {
  475. true,
  476. help_string,
  477. long_name,
  478. short_name,
  479. value_name,
  480. [&values, separator](char const* s) {
  481. bool parsed_all_values = true;
  482. StringView { s }.for_each_split_view(separator, false, [&](auto value) {
  483. if (auto maybe_value = AK::StringUtils::convert_to_uint<size_t>(value); maybe_value.has_value())
  484. values.append(*maybe_value);
  485. else
  486. parsed_all_values = false;
  487. });
  488. return parsed_all_values;
  489. },
  490. hide_mode
  491. };
  492. add_option(move(option));
  493. }
  494. void ArgsParser::add_positional_argument(Arg&& arg)
  495. {
  496. m_positional_args.append(move(arg));
  497. }
  498. void ArgsParser::add_positional_argument(char const*& value, char const* help_string, char const* name, Required required)
  499. {
  500. Arg arg {
  501. help_string,
  502. name,
  503. required == Required::Yes ? 1 : 0,
  504. 1,
  505. [&value](char const* s) {
  506. value = s;
  507. return true;
  508. }
  509. };
  510. add_positional_argument(move(arg));
  511. }
  512. void ArgsParser::add_positional_argument(String& value, char const* help_string, char const* name, Required required)
  513. {
  514. Arg arg {
  515. help_string,
  516. name,
  517. required == Required::Yes ? 1 : 0,
  518. 1,
  519. [&value](char const* s) {
  520. value = s;
  521. return true;
  522. }
  523. };
  524. add_positional_argument(move(arg));
  525. }
  526. void ArgsParser::add_positional_argument(StringView& value, char const* help_string, char const* name, Required required)
  527. {
  528. Arg arg {
  529. help_string,
  530. name,
  531. required == Required::Yes ? 1 : 0,
  532. 1,
  533. [&value](char const* s) {
  534. value = s;
  535. return true;
  536. }
  537. };
  538. add_positional_argument(move(arg));
  539. }
  540. void ArgsParser::add_positional_argument(int& value, 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. 1,
  547. [&value](char const* s) {
  548. auto opt = StringView(s).to_int();
  549. value = opt.value_or(0);
  550. return opt.has_value();
  551. }
  552. };
  553. add_positional_argument(move(arg));
  554. }
  555. void ArgsParser::add_positional_argument(unsigned& value, char const* help_string, char const* name, Required required)
  556. {
  557. Arg arg {
  558. help_string,
  559. name,
  560. required == Required::Yes ? 1 : 0,
  561. 1,
  562. [&value](char const* s) {
  563. auto opt = StringView(s).to_uint();
  564. value = opt.value_or(0);
  565. return opt.has_value();
  566. }
  567. };
  568. add_positional_argument(move(arg));
  569. }
  570. void ArgsParser::add_positional_argument(double& value, char const* help_string, char const* name, Required required)
  571. {
  572. Arg arg {
  573. help_string,
  574. name,
  575. required == Required::Yes ? 1 : 0,
  576. 1,
  577. [&value](char const* s) {
  578. auto opt = convert_to_double(s);
  579. value = opt.value_or(0.0);
  580. return opt.has_value();
  581. }
  582. };
  583. add_positional_argument(move(arg));
  584. }
  585. void ArgsParser::add_positional_argument(Vector<char const*>& values, char const* help_string, char const* name, Required required)
  586. {
  587. Arg arg {
  588. help_string,
  589. name,
  590. required == Required::Yes ? 1 : 0,
  591. INT_MAX,
  592. [&values](char const* s) {
  593. values.append(s);
  594. return true;
  595. }
  596. };
  597. add_positional_argument(move(arg));
  598. }
  599. void ArgsParser::add_positional_argument(Vector<StringView>& values, char const* help_string, char const* name, Required required)
  600. {
  601. Arg arg {
  602. help_string,
  603. name,
  604. required == Required::Yes ? 1 : 0,
  605. INT_MAX,
  606. [&values](char const* s) {
  607. values.append(s);
  608. return true;
  609. }
  610. };
  611. add_positional_argument(move(arg));
  612. }
  613. void ArgsParser::autocomplete(FILE* file, StringView program_name, Span<char const* const> remaining_arguments)
  614. {
  615. // We expect the full invocation of the program to be available as positional args,
  616. // e.g. `foo --bar arg -b` (program invoked as `foo --complete -- foo --bar arg -b`)
  617. auto first = true;
  618. auto seen_all_options = false;
  619. auto skip_next = false;
  620. StringView argument_to_complete;
  621. StringView option_to_complete;
  622. auto completing_option = false;
  623. for (auto& arg : remaining_arguments) {
  624. StringView argument { arg };
  625. completing_option = false;
  626. if (skip_next) {
  627. argument_to_complete = argument;
  628. skip_next = false;
  629. continue;
  630. }
  631. // Skip over the program name.
  632. if (first && program_name == argument) {
  633. first = false;
  634. continue;
  635. }
  636. if (seen_all_options) {
  637. argument_to_complete = argument;
  638. continue;
  639. }
  640. if (argument.starts_with("--")) {
  641. option_to_complete = argument;
  642. completing_option = true;
  643. if (argument == "--") {
  644. seen_all_options = true;
  645. continue;
  646. }
  647. // Look for a long option
  648. auto option_pattern = argument.substring_view(2);
  649. auto it = m_options.find_if([&](auto& option) { return option.hide_mode != OptionHideMode::None && StringView(option.long_name) == option_pattern; });
  650. if (it.is_end())
  651. continue;
  652. if (it->requires_argument)
  653. skip_next = true;
  654. continue;
  655. }
  656. if (argument.starts_with("-")) {
  657. option_to_complete = argument;
  658. completing_option = true;
  659. if (argument == "-") {
  660. option_to_complete = argument;
  661. continue;
  662. }
  663. // Look for a short option
  664. auto option_pattern = argument[argument.length() - 1];
  665. auto it = m_options.find_if([&](auto& option) { return option.hide_mode != OptionHideMode::None && option.short_name == option_pattern; });
  666. if (it.is_end())
  667. continue;
  668. if (it->requires_argument)
  669. skip_next = true;
  670. continue;
  671. }
  672. }
  673. // We don't know how to complete arguments quite yet.
  674. if (!completing_option)
  675. return;
  676. auto write_completion = [&](auto format, auto& option, auto has_invariant, auto... args) {
  677. JsonObject object;
  678. object.set("completion", String::formatted(format, args...));
  679. object.set("static_offset", 0);
  680. object.set("invariant_offset", has_invariant ? option_to_complete.length() : 0u);
  681. object.set("display_trivia", option.help_string);
  682. object.set("trailing_trivia", option.requires_argument ? " " : "");
  683. outln(file, "{}", object.to_string());
  684. };
  685. if (option_to_complete.starts_with("--")) {
  686. // Complete a long option.
  687. auto option_pattern = option_to_complete.substring_view(2);
  688. for (auto& option : m_options) {
  689. if (option.hide_mode != OptionHideMode::None)
  690. continue;
  691. StringView option_string = option.long_name;
  692. if (option_string.starts_with(option_pattern)) {
  693. write_completion("--{}", option, true, option_string);
  694. }
  695. }
  696. } else {
  697. // Complete a short option, note that we're not going to attempt to 'match' anything here.
  698. for (auto& option : m_options) {
  699. if (option.hide_mode != OptionHideMode::None)
  700. continue;
  701. if (option.short_name == 0)
  702. continue;
  703. auto has_invariant = option_to_complete == "-";
  704. write_completion("{}{}", option, has_invariant, has_invariant ? "-" : "", option.short_name);
  705. }
  706. }
  707. }
  708. }