ArgsParser.cpp 14 KB

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