ArgsParser.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /*
  2. * Copyright (c) 2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Format.h>
  7. #include <AK/StringBuilder.h>
  8. #include <LibCore/ArgsParser.h>
  9. #include <getopt.h>
  10. #include <limits.h>
  11. #include <stdio.h>
  12. #include <string.h>
  13. static constexpr bool isnan(double __x) { return __builtin_isnan(__x); }
  14. static Optional<double> convert_to_double(const char* s)
  15. {
  16. char* p;
  17. double v = strtod(s, &p);
  18. if (isnan(v) || p == s)
  19. return {};
  20. return v;
  21. }
  22. namespace Core {
  23. ArgsParser::ArgsParser()
  24. {
  25. add_option(m_show_help, "Display this message", "help", 0);
  26. }
  27. bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_behavior)
  28. {
  29. auto fail = [this, argv, failure_behavior] {
  30. if (failure_behavior == FailureBehavior::PrintUsage || failure_behavior == FailureBehavior::PrintUsageAndExit)
  31. print_usage(stderr, argv[0]);
  32. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  33. exit(1);
  34. };
  35. Vector<option> long_options;
  36. StringBuilder short_options_builder;
  37. if (m_stop_on_first_non_option)
  38. short_options_builder.append('+');
  39. int index_of_found_long_option = -1;
  40. // Tell getopt() to reset its internal state, and start scanning from optind = 1.
  41. // We could also set optreset = 1, but the host platform may not support that.
  42. optind = 0;
  43. for (size_t i = 0; i < m_options.size(); i++) {
  44. auto& opt = m_options[i];
  45. if (opt.long_name) {
  46. option long_opt {
  47. opt.long_name,
  48. opt.requires_argument ? required_argument : no_argument,
  49. &index_of_found_long_option,
  50. static_cast<int>(i)
  51. };
  52. long_options.append(long_opt);
  53. }
  54. if (opt.short_name) {
  55. short_options_builder.append(opt.short_name);
  56. if (opt.requires_argument)
  57. short_options_builder.append(':');
  58. }
  59. }
  60. long_options.append({ 0, 0, 0, 0 });
  61. String short_options = short_options_builder.build();
  62. while (true) {
  63. int c = getopt_long(argc, argv, short_options.characters(), long_options.data(), nullptr);
  64. if (c == -1) {
  65. // We have reached the end.
  66. break;
  67. } else if (c == '?') {
  68. // There was an error, and getopt() has already
  69. // printed its error message.
  70. fail();
  71. return false;
  72. }
  73. // Let's see what option we just found.
  74. Option* found_option = nullptr;
  75. if (c == 0) {
  76. // It was a long option.
  77. VERIFY(index_of_found_long_option >= 0);
  78. found_option = &m_options[index_of_found_long_option];
  79. index_of_found_long_option = -1;
  80. } else {
  81. // It was a short option, look it up.
  82. auto it = m_options.find_if([c](auto& opt) { return c == opt.short_name; });
  83. VERIFY(!it.is_end());
  84. found_option = &*it;
  85. }
  86. VERIFY(found_option);
  87. const char* arg = found_option->requires_argument ? optarg : nullptr;
  88. if (!found_option->accept_value(arg)) {
  89. warnln("\033[31mInvalid value for option \033[1m{}\033[22m\033[0m", found_option->name_for_display());
  90. fail();
  91. return false;
  92. }
  93. }
  94. // We're done processing options, now let's parse positional arguments.
  95. int values_left = argc - optind;
  96. Vector<int, 16> num_values_for_arg;
  97. num_values_for_arg.resize(m_positional_args.size(), true);
  98. int total_values_required = 0;
  99. for (size_t i = 0; i < m_positional_args.size(); i++) {
  100. auto& arg = m_positional_args[i];
  101. num_values_for_arg[i] = arg.min_values;
  102. total_values_required += arg.min_values;
  103. }
  104. if (total_values_required > values_left) {
  105. fail();
  106. return false;
  107. }
  108. int extra_values_to_distribute = values_left - total_values_required;
  109. for (size_t i = 0; i < m_positional_args.size(); i++) {
  110. auto& arg = m_positional_args[i];
  111. int extra_values_to_this_arg = min(arg.max_values - arg.min_values, extra_values_to_distribute);
  112. num_values_for_arg[i] += extra_values_to_this_arg;
  113. extra_values_to_distribute -= extra_values_to_this_arg;
  114. if (extra_values_to_distribute == 0)
  115. break;
  116. }
  117. if (extra_values_to_distribute > 0) {
  118. // We still have too many values :(
  119. fail();
  120. return false;
  121. }
  122. for (size_t i = 0; i < m_positional_args.size(); i++) {
  123. auto& arg = m_positional_args[i];
  124. for (int j = 0; j < num_values_for_arg[i]; j++) {
  125. const char* value = argv[optind++];
  126. if (!arg.accept_value(value)) {
  127. warnln("Invalid value for argument {}", arg.name);
  128. fail();
  129. return false;
  130. }
  131. }
  132. }
  133. // We're done parsing! :)
  134. // Now let's show help if requested.
  135. if (m_show_help) {
  136. print_usage(stdout, argv[0]);
  137. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  138. exit(0);
  139. return false;
  140. }
  141. return true;
  142. }
  143. void ArgsParser::print_usage(FILE* file, const char* argv0)
  144. {
  145. out(file, "Usage:\n\t\033[1m{}\033[0m", argv0);
  146. for (auto& opt : m_options) {
  147. if (opt.long_name && !strcmp(opt.long_name, "help"))
  148. continue;
  149. if (opt.requires_argument)
  150. out(file, " [{} {}]", opt.name_for_display(), opt.value_name);
  151. else
  152. out(file, " [{}]", opt.name_for_display());
  153. }
  154. for (auto& arg : m_positional_args) {
  155. bool required = arg.min_values > 0;
  156. bool repeated = arg.max_values > 1;
  157. if (required && repeated)
  158. out(file, " <{}...>", arg.name);
  159. else if (required && !repeated)
  160. out(file, " <{}>", arg.name);
  161. else if (!required && repeated)
  162. out(file, " [{}...]", arg.name);
  163. else if (!required && !repeated)
  164. out(file, " [{}]", arg.name);
  165. }
  166. outln(file);
  167. if (m_general_help != nullptr && m_general_help[0] != '\0') {
  168. outln(file, "\nDescription:");
  169. outln(file, m_general_help);
  170. }
  171. if (!m_options.is_empty())
  172. outln(file, "\nOptions:");
  173. for (auto& opt : m_options) {
  174. auto print_argument = [&]() {
  175. if (opt.value_name) {
  176. if (opt.requires_argument)
  177. out(file, " {}", opt.value_name);
  178. else
  179. out(file, " [{}]", opt.value_name);
  180. }
  181. };
  182. out(file, "\t");
  183. if (opt.short_name) {
  184. out(file, "\033[1m-{}\033[0m", opt.short_name);
  185. print_argument();
  186. }
  187. if (opt.short_name && opt.long_name)
  188. out(file, ", ");
  189. if (opt.long_name) {
  190. out(file, "\033[1m--{}\033[0m", opt.long_name);
  191. print_argument();
  192. }
  193. if (opt.help_string)
  194. out(file, "\t{}", opt.help_string);
  195. outln(file);
  196. }
  197. if (!m_positional_args.is_empty())
  198. outln(file, "\nArguments:");
  199. for (auto& arg : m_positional_args) {
  200. out(file, "\t\033[1m{}\033[0m", arg.name);
  201. if (arg.help_string)
  202. out(file, "\t{}", arg.help_string);
  203. outln(file);
  204. }
  205. }
  206. void ArgsParser::add_option(Option&& option)
  207. {
  208. m_options.append(move(option));
  209. }
  210. void ArgsParser::add_option(bool& value, const char* help_string, const char* long_name, char short_name)
  211. {
  212. Option option {
  213. false,
  214. help_string,
  215. long_name,
  216. short_name,
  217. nullptr,
  218. [&value](const char* s) {
  219. VERIFY(s == nullptr);
  220. value = true;
  221. return true;
  222. }
  223. };
  224. add_option(move(option));
  225. }
  226. void ArgsParser::add_option(const char*& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  227. {
  228. Option option {
  229. true,
  230. help_string,
  231. long_name,
  232. short_name,
  233. value_name,
  234. [&value](const char* s) {
  235. value = s;
  236. return true;
  237. }
  238. };
  239. add_option(move(option));
  240. }
  241. void ArgsParser::add_option(String& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  242. {
  243. Option option {
  244. true,
  245. help_string,
  246. long_name,
  247. short_name,
  248. value_name,
  249. [&value](const char* s) {
  250. value = s;
  251. return true;
  252. }
  253. };
  254. add_option(move(option));
  255. }
  256. void ArgsParser::add_option(StringView& value, char const* help_string, char const* long_name, char short_name, char const* value_name)
  257. {
  258. Option option {
  259. true,
  260. help_string,
  261. long_name,
  262. short_name,
  263. value_name,
  264. [&value](const char* s) {
  265. value = s;
  266. return true;
  267. }
  268. };
  269. add_option(move(option));
  270. }
  271. void ArgsParser::add_option(int& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  272. {
  273. Option option {
  274. true,
  275. help_string,
  276. long_name,
  277. short_name,
  278. value_name,
  279. [&value](const char* s) {
  280. auto opt = StringView(s).to_int();
  281. value = opt.value_or(0);
  282. return opt.has_value();
  283. }
  284. };
  285. add_option(move(option));
  286. }
  287. void ArgsParser::add_option(unsigned& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  288. {
  289. Option option {
  290. true,
  291. help_string,
  292. long_name,
  293. short_name,
  294. value_name,
  295. [&value](const char* s) {
  296. auto opt = StringView(s).to_uint();
  297. value = opt.value_or(0);
  298. return opt.has_value();
  299. }
  300. };
  301. add_option(move(option));
  302. }
  303. void ArgsParser::add_option(double& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  304. {
  305. Option option {
  306. true,
  307. help_string,
  308. long_name,
  309. short_name,
  310. value_name,
  311. [&value](const char* s) {
  312. auto opt = convert_to_double(s);
  313. value = opt.value_or(0.0);
  314. return opt.has_value();
  315. }
  316. };
  317. add_option(move(option));
  318. }
  319. void ArgsParser::add_positional_argument(Arg&& arg)
  320. {
  321. m_positional_args.append(move(arg));
  322. }
  323. void ArgsParser::add_positional_argument(const char*& value, const char* help_string, const char* name, Required required)
  324. {
  325. Arg arg {
  326. help_string,
  327. name,
  328. required == Required::Yes ? 1 : 0,
  329. 1,
  330. [&value](const char* s) {
  331. value = s;
  332. return true;
  333. }
  334. };
  335. add_positional_argument(move(arg));
  336. }
  337. void ArgsParser::add_positional_argument(String& value, const char* help_string, const char* name, Required required)
  338. {
  339. Arg arg {
  340. help_string,
  341. name,
  342. required == Required::Yes ? 1 : 0,
  343. 1,
  344. [&value](const char* s) {
  345. value = s;
  346. return true;
  347. }
  348. };
  349. add_positional_argument(move(arg));
  350. }
  351. void ArgsParser::add_positional_argument(StringView& value, char const* help_string, char const* name, Required required)
  352. {
  353. Arg arg {
  354. help_string,
  355. name,
  356. required == Required::Yes ? 1 : 0,
  357. 1,
  358. [&value](const char* s) {
  359. value = s;
  360. return true;
  361. }
  362. };
  363. add_positional_argument(move(arg));
  364. }
  365. void ArgsParser::add_positional_argument(int& value, const char* help_string, const char* name, Required required)
  366. {
  367. Arg arg {
  368. help_string,
  369. name,
  370. required == Required::Yes ? 1 : 0,
  371. 1,
  372. [&value](const char* s) {
  373. auto opt = StringView(s).to_int();
  374. value = opt.value_or(0);
  375. return opt.has_value();
  376. }
  377. };
  378. add_positional_argument(move(arg));
  379. }
  380. void ArgsParser::add_positional_argument(unsigned& value, const char* help_string, const char* name, Required required)
  381. {
  382. Arg arg {
  383. help_string,
  384. name,
  385. required == Required::Yes ? 1 : 0,
  386. 1,
  387. [&value](const char* s) {
  388. auto opt = StringView(s).to_uint();
  389. value = opt.value_or(0);
  390. return opt.has_value();
  391. }
  392. };
  393. add_positional_argument(move(arg));
  394. }
  395. void ArgsParser::add_positional_argument(double& value, const char* help_string, const char* name, Required required)
  396. {
  397. Arg arg {
  398. help_string,
  399. name,
  400. required == Required::Yes ? 1 : 0,
  401. 1,
  402. [&value](const char* s) {
  403. auto opt = convert_to_double(s);
  404. value = opt.value_or(0.0);
  405. return opt.has_value();
  406. }
  407. };
  408. add_positional_argument(move(arg));
  409. }
  410. void ArgsParser::add_positional_argument(Vector<const char*>& values, const char* help_string, const char* name, Required required)
  411. {
  412. Arg arg {
  413. help_string,
  414. name,
  415. required == Required::Yes ? 1 : 0,
  416. INT_MAX,
  417. [&values](const char* s) {
  418. values.append(s);
  419. return true;
  420. }
  421. };
  422. add_positional_argument(move(arg));
  423. }
  424. void ArgsParser::add_positional_argument(Vector<String>& values, const char* help_string, const char* name, Required required)
  425. {
  426. Arg arg {
  427. help_string,
  428. name,
  429. required == Required::Yes ? 1 : 0,
  430. INT_MAX,
  431. [&values](const char* s) {
  432. values.append(s);
  433. return true;
  434. }
  435. };
  436. add_positional_argument(move(arg));
  437. }
  438. }