ArgsParser.cpp 24 KB

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