ArgsParser.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. /*
  2. * Copyright (c) 2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. * Copyright (c) 2022, Matthias Zimmerman <matthias291999@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Format.h>
  8. #include <AK/JsonObject.h>
  9. #include <AK/OptionParser.h>
  10. #include <AK/String.h>
  11. #include <LibCore/ArgsParser.h>
  12. #include <LibCore/Version.h>
  13. #include <limits.h>
  14. #include <math.h>
  15. #include <stdio.h>
  16. #include <string.h>
  17. namespace Core {
  18. ArgsParser::ArgsParser()
  19. {
  20. add_option(m_show_help, "Display help message and exit", "help", 0, OptionHideMode::Markdown);
  21. add_option(m_show_version, "Print version", "version", 0, OptionHideMode::Markdown);
  22. add_option(m_perform_autocomplete, "Perform autocompletion", "complete", 0, OptionHideMode::CommandLineAndMarkdown);
  23. }
  24. bool ArgsParser::parse(Span<StringView> arguments, FailureBehavior failure_behavior)
  25. {
  26. auto fail_impl = [this, failure_behavior](StringView name) {
  27. if (failure_behavior == FailureBehavior::PrintUsage || failure_behavior == FailureBehavior::PrintUsageAndExit)
  28. print_usage(stderr, name);
  29. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  30. exit(1);
  31. };
  32. if (arguments.is_empty()) {
  33. fail_impl("<exe>"sv);
  34. return false;
  35. }
  36. auto fail = [name = arguments[0], &fail_impl] { fail_impl(name); };
  37. OptionParser parser;
  38. Vector<OptionParser::Option> long_options;
  39. StringBuilder short_options_builder;
  40. if (m_stop_on_first_non_option)
  41. short_options_builder.append('+');
  42. int index_of_found_long_option = -1;
  43. for (size_t i = 0; i < m_options.size(); i++) {
  44. auto& opt = m_options[i];
  45. if (opt.long_name) {
  46. OptionParser::Option long_opt {
  47. { opt.long_name, strlen(opt.long_name) },
  48. opt.argument_mode == OptionArgumentMode::Required
  49. ? OptionParser::ArgumentRequirement::HasRequiredArgument
  50. : opt.argument_mode == OptionArgumentMode::Optional
  51. ? OptionParser::ArgumentRequirement::HasOptionalArgument
  52. : OptionParser::ArgumentRequirement::NoArgument,
  53. &index_of_found_long_option,
  54. static_cast<int>(i)
  55. };
  56. long_options.append(long_opt);
  57. }
  58. if (opt.short_name) {
  59. short_options_builder.append(opt.short_name);
  60. if (opt.argument_mode != OptionArgumentMode::None)
  61. short_options_builder.append(':');
  62. // Note: This is a GNU extension.
  63. if (opt.argument_mode == OptionArgumentMode::Optional)
  64. short_options_builder.append(':');
  65. }
  66. }
  67. auto short_options = short_options_builder.to_deprecated_string();
  68. size_t option_index = 1;
  69. while (true) {
  70. auto result = parser.getopt(arguments.slice(1), short_options, long_options, {});
  71. option_index += result.consumed_args;
  72. auto c = result.result;
  73. if (c == -1) {
  74. // We have reached the end.
  75. break;
  76. }
  77. if (c == '?') {
  78. // There was an error, and getopt() has already
  79. // printed its error message.
  80. fail();
  81. return false;
  82. }
  83. // Let's see what option we just found.
  84. Option* found_option = nullptr;
  85. if (c == 0) {
  86. // It was a long option.
  87. VERIFY(index_of_found_long_option >= 0);
  88. found_option = &m_options[index_of_found_long_option];
  89. index_of_found_long_option = -1;
  90. } else {
  91. // It was a short option, look it up.
  92. auto it = m_options.find_if([c](auto& opt) { return c == opt.short_name; });
  93. VERIFY(!it.is_end());
  94. found_option = &*it;
  95. }
  96. VERIFY(found_option);
  97. StringView arg = found_option->argument_mode != OptionArgumentMode::None ? result.optarg_value.value_or({}) : StringView {};
  98. if (!found_option->accept_value(arg)) {
  99. warnln("\033[31mInvalid value for option \033[1m{}\033[22m\033[0m", found_option->name_for_display());
  100. fail();
  101. return false;
  102. }
  103. }
  104. // We're done processing options.
  105. // Now let's show version or help if requested, or perform autocompletion if needed.
  106. if (m_show_version) {
  107. print_version(stdout);
  108. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  109. exit(0);
  110. return false;
  111. }
  112. if (m_show_help) {
  113. print_usage(stdout, arguments[0]);
  114. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  115. exit(0);
  116. return false;
  117. }
  118. if (m_perform_autocomplete) {
  119. autocomplete(stdout, arguments[0], arguments.slice(option_index));
  120. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  121. exit(0);
  122. return false;
  123. }
  124. // Now let's parse positional arguments.
  125. int values_left = arguments.size() - option_index;
  126. Vector<int, 16> num_values_for_arg;
  127. num_values_for_arg.resize(m_positional_args.size(), true);
  128. int total_values_required = 0;
  129. for (size_t i = 0; i < m_positional_args.size(); i++) {
  130. auto& arg = m_positional_args[i];
  131. num_values_for_arg[i] = arg.min_values;
  132. total_values_required += arg.min_values;
  133. }
  134. if (total_values_required > values_left) {
  135. fail();
  136. return false;
  137. }
  138. int extra_values_to_distribute = values_left - total_values_required;
  139. for (size_t i = 0; i < m_positional_args.size(); i++) {
  140. auto& arg = m_positional_args[i];
  141. int extra_values_to_this_arg = min(arg.max_values - arg.min_values, extra_values_to_distribute);
  142. num_values_for_arg[i] += extra_values_to_this_arg;
  143. extra_values_to_distribute -= extra_values_to_this_arg;
  144. if (extra_values_to_distribute == 0)
  145. break;
  146. }
  147. if (extra_values_to_distribute > 0) {
  148. // We still have too many values :(
  149. fail();
  150. return false;
  151. }
  152. for (size_t i = 0; i < m_positional_args.size(); i++) {
  153. auto& arg = m_positional_args[i];
  154. for (int j = 0; j < num_values_for_arg[i]; j++) {
  155. StringView value = arguments[option_index++];
  156. if (!arg.accept_value(value)) {
  157. warnln("Invalid value for argument {}", arg.name);
  158. fail();
  159. return false;
  160. }
  161. }
  162. }
  163. return true;
  164. }
  165. void ArgsParser::print_usage(FILE* file, StringView argv0)
  166. {
  167. char const* env_preference = getenv("ARGSPARSER_EMIT_MARKDOWN");
  168. if (env_preference != nullptr && env_preference[0] == '1' && env_preference[1] == 0) {
  169. print_usage_markdown(file, argv0);
  170. } else {
  171. print_usage_terminal(file, argv0);
  172. }
  173. }
  174. void ArgsParser::print_usage_terminal(FILE* file, StringView argv0)
  175. {
  176. out(file, "Usage:\n\t\033[1m{}\033[0m", argv0);
  177. for (auto& opt : m_options) {
  178. if (opt.hide_mode != OptionHideMode::None)
  179. continue;
  180. if (opt.argument_mode == OptionArgumentMode::Required)
  181. out(file, " [{} {}]", opt.name_for_display(), opt.value_name);
  182. else if (opt.argument_mode == OptionArgumentMode::Optional)
  183. out(file, " [{}[{}{}]]", opt.name_for_display(), opt.long_name ? "="sv : ""sv, opt.value_name);
  184. else
  185. out(file, " [{}]", opt.name_for_display());
  186. }
  187. for (auto& arg : m_positional_args) {
  188. bool required = arg.min_values > 0;
  189. bool repeated = arg.max_values > 1;
  190. if (required && repeated)
  191. out(file, " <{}...>", arg.name);
  192. else if (required && !repeated)
  193. out(file, " <{}>", arg.name);
  194. else if (!required && repeated)
  195. out(file, " [{}...]", arg.name);
  196. else if (!required && !repeated)
  197. out(file, " [{}]", arg.name);
  198. }
  199. outln(file);
  200. if (m_general_help != nullptr && m_general_help[0] != '\0') {
  201. outln(file, "\nDescription:");
  202. outln(file, "{}", m_general_help);
  203. }
  204. if (!m_options.is_empty())
  205. outln(file, "\nOptions:");
  206. for (auto& opt : m_options) {
  207. if (opt.hide_mode == OptionHideMode::CommandLineAndMarkdown)
  208. continue;
  209. auto print_argument = [&](StringView value_delimiter) {
  210. if (opt.value_name) {
  211. if (opt.argument_mode == OptionArgumentMode::Required)
  212. out(file, " {}", opt.value_name);
  213. if (opt.argument_mode == OptionArgumentMode::Optional)
  214. out(file, "[{}{}]", value_delimiter, opt.value_name);
  215. }
  216. };
  217. out(file, "\t");
  218. if (opt.short_name) {
  219. out(file, "\033[1m-{}\033[0m", opt.short_name);
  220. print_argument(""sv);
  221. }
  222. if (opt.short_name && opt.long_name)
  223. out(file, ", ");
  224. if (opt.long_name) {
  225. out(file, "\033[1m--{}\033[0m", opt.long_name);
  226. print_argument("="sv);
  227. }
  228. if (opt.help_string)
  229. out(file, "\t{}", opt.help_string);
  230. outln(file);
  231. }
  232. if (!m_positional_args.is_empty())
  233. outln(file, "\nArguments:");
  234. for (auto& arg : m_positional_args) {
  235. out(file, "\t\033[1m{}\033[0m", arg.name);
  236. if (arg.help_string)
  237. out(file, "\t{}", arg.help_string);
  238. outln(file);
  239. }
  240. }
  241. void ArgsParser::print_usage_markdown(FILE* file, StringView argv0)
  242. {
  243. outln(file, "## Name\n\n{}", argv0);
  244. out(file, "\n## Synopsis\n\n```sh\n$ {}", argv0);
  245. for (auto& opt : m_options) {
  246. if (opt.hide_mode != OptionHideMode::None)
  247. continue;
  248. // FIXME: We allow opt.value_name to be empty even if the option
  249. // requires an argument. This should be disallowed as it will
  250. // currently display a blank name after the option.
  251. if (opt.argument_mode == OptionArgumentMode::Required)
  252. out(file, " [{} {}]", opt.name_for_display(), opt.value_name ?: "");
  253. else if (opt.argument_mode == OptionArgumentMode::Optional)
  254. out(file, " [{}[{}{}]]", opt.name_for_display(), opt.long_name ? "="sv : ""sv, opt.value_name);
  255. else
  256. out(file, " [{}]", opt.name_for_display());
  257. }
  258. for (auto& arg : m_positional_args) {
  259. bool required = arg.min_values > 0;
  260. bool repeated = arg.max_values > 1;
  261. if (required && repeated)
  262. out(file, " <{}...>", arg.name);
  263. else if (required && !repeated)
  264. out(file, " <{}>", arg.name);
  265. else if (!required && repeated)
  266. out(file, " [{}...]", arg.name);
  267. else if (!required && !repeated)
  268. out(file, " [{}]", arg.name);
  269. }
  270. outln(file, "\n```");
  271. if (m_general_help != nullptr && m_general_help[0] != '\0') {
  272. outln(file, "\n## Description\n\n{}", m_general_help);
  273. }
  274. auto should_display_option = [](Option& opt) {
  275. return !(opt.hide_mode == OptionHideMode::Markdown || opt.hide_mode == OptionHideMode::CommandLineAndMarkdown);
  276. };
  277. size_t options_to_display = 0;
  278. for (auto& opt : m_options) {
  279. if (!should_display_option(opt))
  280. continue;
  281. options_to_display++;
  282. }
  283. if (options_to_display > 0)
  284. outln(file, "\n## Options\n");
  285. for (auto& opt : m_options) {
  286. if (!should_display_option(opt))
  287. continue;
  288. auto print_argument = [&](StringView value_delimiter) {
  289. if (opt.value_name != nullptr) {
  290. if (opt.argument_mode == OptionArgumentMode::Required)
  291. out(file, " {}", opt.value_name);
  292. if (opt.argument_mode == OptionArgumentMode::Optional)
  293. out(file, "[{}{}]", value_delimiter, opt.value_name);
  294. }
  295. };
  296. out(file, "* ");
  297. if (opt.short_name != '\0') {
  298. out(file, "`-{}", opt.short_name);
  299. print_argument(""sv);
  300. out(file, "`");
  301. }
  302. if (opt.short_name != '\0' && opt.long_name != nullptr)
  303. out(file, ", ");
  304. if (opt.long_name != nullptr) {
  305. out(file, "`--{}", opt.long_name);
  306. print_argument("="sv);
  307. out(file, "`");
  308. }
  309. if (opt.help_string != nullptr)
  310. out(file, ": {}", opt.help_string);
  311. outln(file);
  312. }
  313. if (!m_positional_args.is_empty())
  314. outln(file, "\n## Arguments\n");
  315. for (auto& arg : m_positional_args) {
  316. out(file, "* `{}`", arg.name);
  317. if (arg.help_string != nullptr)
  318. out(file, ": {}", arg.help_string);
  319. outln(file);
  320. }
  321. }
  322. void ArgsParser::print_version(FILE* file)
  323. {
  324. outln(file, Core::Version::read_long_version_string().release_value_but_fixme_should_propagate_errors());
  325. }
  326. void ArgsParser::add_option(Option&& option)
  327. {
  328. m_options.append(move(option));
  329. }
  330. void ArgsParser::add_ignored(char const* long_name, char short_name, OptionHideMode hide_mode)
  331. {
  332. Option option {
  333. OptionArgumentMode::None,
  334. "Ignored",
  335. long_name,
  336. short_name,
  337. nullptr,
  338. [](StringView) {
  339. return true;
  340. },
  341. hide_mode,
  342. };
  343. add_option(move(option));
  344. }
  345. void ArgsParser::add_option(bool& value, char const* help_string, char const* long_name, char short_name, OptionHideMode hide_mode)
  346. {
  347. Option option {
  348. OptionArgumentMode::None,
  349. help_string,
  350. long_name,
  351. short_name,
  352. nullptr,
  353. [&value](StringView s) {
  354. VERIFY(s.is_empty());
  355. value = true;
  356. return true;
  357. },
  358. hide_mode,
  359. };
  360. add_option(move(option));
  361. }
  362. void ArgsParser::add_option(DeprecatedString& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  363. {
  364. Option option {
  365. OptionArgumentMode::Required,
  366. help_string,
  367. long_name,
  368. short_name,
  369. value_name,
  370. [&value](StringView s) {
  371. value = s;
  372. return true;
  373. },
  374. hide_mode,
  375. };
  376. add_option(move(option));
  377. }
  378. void ArgsParser::add_option(StringView& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  379. {
  380. Option option {
  381. OptionArgumentMode::Required,
  382. help_string,
  383. long_name,
  384. short_name,
  385. value_name,
  386. [&value](StringView s) {
  387. value = s;
  388. return true;
  389. },
  390. hide_mode,
  391. };
  392. add_option(move(option));
  393. }
  394. template<Integral I>
  395. void ArgsParser::add_option(I& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  396. {
  397. Option option {
  398. OptionArgumentMode::Required,
  399. help_string,
  400. long_name,
  401. short_name,
  402. value_name,
  403. [&value](StringView view) {
  404. Optional<I> opt;
  405. if constexpr (IsSigned<I>)
  406. opt = view.to_int<I>();
  407. else
  408. opt = view.to_uint<I>();
  409. value = opt.value_or(0);
  410. return opt.has_value();
  411. },
  412. hide_mode,
  413. };
  414. add_option(move(option));
  415. }
  416. template void ArgsParser::add_option(int&, char const*, char const*, char, char const*, OptionHideMode);
  417. template void ArgsParser::add_option(long&, char const*, char const*, char, char const*, OptionHideMode);
  418. template void ArgsParser::add_option(long long&, char const*, char const*, char, char const*, OptionHideMode);
  419. template void ArgsParser::add_option(unsigned&, char const*, char const*, char, char const*, OptionHideMode);
  420. template void ArgsParser::add_option(unsigned long&, char const*, char const*, char, char const*, OptionHideMode);
  421. template void ArgsParser::add_option(unsigned long long&, char const*, char const*, char, char const*, OptionHideMode);
  422. void ArgsParser::add_option(double& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  423. {
  424. Option option {
  425. OptionArgumentMode::Required,
  426. help_string,
  427. long_name,
  428. short_name,
  429. value_name,
  430. [&value](StringView s) {
  431. auto opt = s.to_double();
  432. value = opt.value_or(0.0);
  433. return opt.has_value();
  434. },
  435. hide_mode,
  436. };
  437. add_option(move(option));
  438. }
  439. 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)
  440. {
  441. Option option {
  442. OptionArgumentMode::Required,
  443. help_string,
  444. long_name,
  445. short_name,
  446. value_name,
  447. [&value](StringView s) {
  448. value = s.to_double();
  449. return value.has_value();
  450. },
  451. hide_mode,
  452. };
  453. add_option(move(option));
  454. }
  455. 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)
  456. {
  457. Option option {
  458. OptionArgumentMode::Required,
  459. help_string,
  460. long_name,
  461. short_name,
  462. value_name,
  463. [&value](StringView s) {
  464. value = AK::StringUtils::convert_to_uint<size_t>(s);
  465. return value.has_value();
  466. },
  467. hide_mode,
  468. };
  469. add_option(move(option));
  470. }
  471. 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)
  472. {
  473. Option option {
  474. OptionArgumentMode::Required,
  475. help_string,
  476. long_name,
  477. short_name,
  478. value_name,
  479. [&values, separator](StringView s) {
  480. bool parsed_all_values = true;
  481. s.for_each_split_view(separator, SplitBehavior::Nothing, [&](auto value) {
  482. if (auto maybe_value = AK::StringUtils::convert_to_uint<size_t>(value); maybe_value.has_value())
  483. values.append(*maybe_value);
  484. else
  485. parsed_all_values = false;
  486. });
  487. return parsed_all_values;
  488. },
  489. hide_mode
  490. };
  491. add_option(move(option));
  492. }
  493. void ArgsParser::add_option(Vector<DeprecatedString>& values, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode)
  494. {
  495. Option option {
  496. OptionArgumentMode::Optional,
  497. help_string,
  498. long_name,
  499. short_name,
  500. value_name,
  501. [&values](StringView s) {
  502. values.append(s);
  503. return true;
  504. },
  505. hide_mode
  506. };
  507. add_option(move(option));
  508. }
  509. void ArgsParser::add_positional_argument(Arg&& arg)
  510. {
  511. m_positional_args.append(move(arg));
  512. }
  513. void ArgsParser::add_positional_argument(DeprecatedString& value, char const* help_string, char const* name, Required required)
  514. {
  515. Arg arg {
  516. help_string,
  517. name,
  518. required == Required::Yes ? 1 : 0,
  519. 1,
  520. [&value](StringView s) {
  521. value = s;
  522. return true;
  523. }
  524. };
  525. add_positional_argument(move(arg));
  526. }
  527. void ArgsParser::add_positional_argument(StringView& value, char const* help_string, char const* name, Required required)
  528. {
  529. Arg arg {
  530. help_string,
  531. name,
  532. required == Required::Yes ? 1 : 0,
  533. 1,
  534. [&value](StringView s) {
  535. value = s;
  536. return true;
  537. }
  538. };
  539. add_positional_argument(move(arg));
  540. }
  541. void ArgsParser::add_positional_argument(int& value, char const* help_string, char const* name, Required required)
  542. {
  543. Arg arg {
  544. help_string,
  545. name,
  546. required == Required::Yes ? 1 : 0,
  547. 1,
  548. [&value](StringView s) {
  549. auto opt = s.to_int();
  550. value = opt.value_or(0);
  551. return opt.has_value();
  552. }
  553. };
  554. add_positional_argument(move(arg));
  555. }
  556. void ArgsParser::add_positional_argument(unsigned& value, char const* help_string, char const* name, Required required)
  557. {
  558. Arg arg {
  559. help_string,
  560. name,
  561. required == Required::Yes ? 1 : 0,
  562. 1,
  563. [&value](StringView s) {
  564. auto opt = s.to_uint();
  565. value = opt.value_or(0);
  566. return opt.has_value();
  567. }
  568. };
  569. add_positional_argument(move(arg));
  570. }
  571. void ArgsParser::add_positional_argument(double& value, char const* help_string, char const* name, Required required)
  572. {
  573. Arg arg {
  574. help_string,
  575. name,
  576. required == Required::Yes ? 1 : 0,
  577. 1,
  578. [&value](StringView s) {
  579. auto opt = s.to_double();
  580. value = opt.value_or(0.0);
  581. return opt.has_value();
  582. }
  583. };
  584. add_positional_argument(move(arg));
  585. }
  586. void ArgsParser::add_positional_argument(Vector<DeprecatedString>& values, char const* help_string, char const* name, Required required)
  587. {
  588. Arg arg {
  589. help_string,
  590. name,
  591. required == Required::Yes ? 1 : 0,
  592. INT_MAX,
  593. [&values](StringView s) {
  594. values.append(s);
  595. return true;
  596. }
  597. };
  598. add_positional_argument(move(arg));
  599. }
  600. void ArgsParser::add_positional_argument(Vector<StringView>& values, char const* help_string, char const* name, Required required)
  601. {
  602. Arg arg {
  603. help_string,
  604. name,
  605. required == Required::Yes ? 1 : 0,
  606. INT_MAX,
  607. [&values](StringView s) {
  608. values.append(s);
  609. return true;
  610. }
  611. };
  612. add_positional_argument(move(arg));
  613. }
  614. void ArgsParser::autocomplete(FILE* file, StringView program_name, ReadonlySpan<StringView> remaining_arguments)
  615. {
  616. // We expect the full invocation of the program to be available as positional args,
  617. // e.g. `foo --bar arg -b` (program invoked as `foo --complete -- foo --bar arg -b`)
  618. auto first = true;
  619. auto seen_all_options = false;
  620. auto skip_next = false;
  621. StringView argument_to_complete;
  622. StringView option_to_complete;
  623. auto completing_option = false;
  624. for (auto& argument : remaining_arguments) {
  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("--"sv)) {
  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, strlen(option.long_name) } == option_pattern; });
  650. if (it.is_end())
  651. continue;
  652. if (it->argument_mode == OptionArgumentMode::Required)
  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->argument_mode == OptionArgumentMode::Required)
  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", DeprecatedString::formatted(StringView { format, strlen(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.argument_mode == OptionArgumentMode::Required ? " " : "");
  683. outln(file, "{}", object.to_deprecated_string());
  684. };
  685. if (option_to_complete.starts_with("--"sv)) {
  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, strlen(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. }