ArgsParser.cpp 24 KB

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