ArgsParser.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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** argv, bool exit_on_failure)
  28. {
  29. auto print_usage_and_exit = [this, argv, exit_on_failure] {
  30. print_usage(stderr, argv[0]);
  31. if (exit_on_failure)
  32. exit(1);
  33. };
  34. Vector<option> long_options;
  35. StringBuilder short_options_builder;
  36. int index_of_found_long_option = -1;
  37. // Tell getopt() to reset its internal state, and start scanning from optind = 1.
  38. // We could also set optreset = 1, but the host platform may not support that.
  39. optind = 0;
  40. for (size_t i = 0; i < m_options.size(); i++) {
  41. auto& opt = m_options[i];
  42. if (opt.long_name) {
  43. option long_opt {
  44. opt.long_name,
  45. opt.requires_argument ? required_argument : no_argument,
  46. &index_of_found_long_option,
  47. static_cast<int>(i)
  48. };
  49. long_options.append(long_opt);
  50. }
  51. if (opt.short_name) {
  52. short_options_builder.append(opt.short_name);
  53. if (opt.requires_argument)
  54. short_options_builder.append(':');
  55. }
  56. }
  57. long_options.append({ 0, 0, 0, 0 });
  58. String short_options = short_options_builder.build();
  59. while (true) {
  60. int c = getopt_long(argc, argv, short_options.characters(), long_options.data(), nullptr);
  61. if (c == -1) {
  62. // We have reached the end.
  63. break;
  64. } else if (c == '?') {
  65. // There was an error, and getopt() has already
  66. // printed its error message.
  67. print_usage_and_exit();
  68. return false;
  69. }
  70. // Let's see what option we just found.
  71. Option* found_option = nullptr;
  72. if (c == 0) {
  73. // It was a long option.
  74. VERIFY(index_of_found_long_option >= 0);
  75. found_option = &m_options[index_of_found_long_option];
  76. index_of_found_long_option = -1;
  77. } else {
  78. // It was a short option, look it up.
  79. auto it = m_options.find_if([c](auto& opt) { return c == opt.short_name; });
  80. VERIFY(!it.is_end());
  81. found_option = &*it;
  82. }
  83. VERIFY(found_option);
  84. const char* arg = found_option->requires_argument ? optarg : nullptr;
  85. if (!found_option->accept_value(arg)) {
  86. warnln("\033[31mInvalid value for option \033[1m{}\033[22m, dude\033[0m", found_option->name_for_display());
  87. print_usage_and_exit();
  88. return false;
  89. }
  90. }
  91. // We're done processing options, now let's parse positional arguments.
  92. int values_left = argc - optind;
  93. int num_values_for_arg[m_positional_args.size()];
  94. int total_values_required = 0;
  95. for (size_t i = 0; i < m_positional_args.size(); i++) {
  96. auto& arg = m_positional_args[i];
  97. num_values_for_arg[i] = arg.min_values;
  98. total_values_required += arg.min_values;
  99. }
  100. if (total_values_required > values_left) {
  101. print_usage_and_exit();
  102. return false;
  103. }
  104. int extra_values_to_distribute = values_left - total_values_required;
  105. for (size_t i = 0; i < m_positional_args.size(); i++) {
  106. auto& arg = m_positional_args[i];
  107. int extra_values_to_this_arg = min(arg.max_values - arg.min_values, extra_values_to_distribute);
  108. num_values_for_arg[i] += extra_values_to_this_arg;
  109. extra_values_to_distribute -= extra_values_to_this_arg;
  110. if (extra_values_to_distribute == 0)
  111. break;
  112. }
  113. if (extra_values_to_distribute > 0) {
  114. // We still have too many values :(
  115. print_usage_and_exit();
  116. return false;
  117. }
  118. for (size_t i = 0; i < m_positional_args.size(); i++) {
  119. auto& arg = m_positional_args[i];
  120. for (int j = 0; j < num_values_for_arg[i]; j++) {
  121. const char* value = argv[optind++];
  122. if (!arg.accept_value(value)) {
  123. warnln("Invalid value for argument {}", arg.name);
  124. print_usage_and_exit();
  125. return false;
  126. }
  127. }
  128. }
  129. // We're done parsing! :)
  130. // Now let's show help if requested.
  131. if (m_show_help) {
  132. print_usage(stdout, argv[0]);
  133. if (exit_on_failure)
  134. exit(0);
  135. return false;
  136. }
  137. return true;
  138. }
  139. void ArgsParser::print_usage(FILE* file, const char* argv0)
  140. {
  141. out(file, "Usage:\n\t\033[1m{}\033[0m", argv0);
  142. for (auto& opt : m_options) {
  143. if (opt.long_name && !strcmp(opt.long_name, "help"))
  144. continue;
  145. if (opt.requires_argument)
  146. out(file, " [{} {}]", opt.name_for_display(), opt.value_name);
  147. else
  148. out(file, " [{}]", opt.name_for_display());
  149. }
  150. for (auto& arg : m_positional_args) {
  151. bool required = arg.min_values > 0;
  152. bool repeated = arg.max_values > 1;
  153. if (required && repeated)
  154. out(file, " <{}...>", arg.name);
  155. else if (required && !repeated)
  156. out(file, " <{}>", arg.name);
  157. else if (!required && repeated)
  158. out(file, " [{}...]", arg.name);
  159. else if (!required && !repeated)
  160. out(file, " [{}]", arg.name);
  161. }
  162. outln(file);
  163. if (m_general_help != nullptr && m_general_help[0] != '\0') {
  164. outln(file, "\nDescription:");
  165. outln(file, m_general_help);
  166. }
  167. if (!m_options.is_empty())
  168. outln(file, "\nOptions:");
  169. for (auto& opt : m_options) {
  170. auto print_argument = [&]() {
  171. if (opt.value_name) {
  172. if (opt.requires_argument)
  173. out(file, " {}", opt.value_name);
  174. else
  175. out(file, " [{}]", opt.value_name);
  176. }
  177. };
  178. out(file, "\t");
  179. if (opt.short_name) {
  180. out(file, "\033[1m-{}\033[0m", opt.short_name);
  181. print_argument();
  182. }
  183. if (opt.short_name && opt.long_name)
  184. out(file, ", ");
  185. if (opt.long_name) {
  186. out(file, "\033[1m--{}\033[0m", opt.long_name);
  187. print_argument();
  188. }
  189. if (opt.help_string)
  190. out(file, "\t{}", opt.help_string);
  191. outln(file);
  192. }
  193. if (!m_positional_args.is_empty())
  194. outln(file, "\nArguments:");
  195. for (auto& arg : m_positional_args) {
  196. out(file, "\t\033[1m{}\033[0m", arg.name);
  197. if (arg.help_string)
  198. out(file, "\t{}", arg.help_string);
  199. outln(file);
  200. }
  201. }
  202. void ArgsParser::add_option(Option&& option)
  203. {
  204. m_options.append(move(option));
  205. }
  206. void ArgsParser::add_option(bool& value, const char* help_string, const char* long_name, char short_name)
  207. {
  208. Option option {
  209. false,
  210. help_string,
  211. long_name,
  212. short_name,
  213. nullptr,
  214. [&value](const char* s) {
  215. VERIFY(s == nullptr);
  216. value = true;
  217. return true;
  218. }
  219. };
  220. add_option(move(option));
  221. }
  222. void ArgsParser::add_option(const char*& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  223. {
  224. Option option {
  225. true,
  226. help_string,
  227. long_name,
  228. short_name,
  229. value_name,
  230. [&value](const char* s) {
  231. value = s;
  232. return true;
  233. }
  234. };
  235. add_option(move(option));
  236. }
  237. void ArgsParser::add_option(String& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  238. {
  239. Option option {
  240. true,
  241. help_string,
  242. long_name,
  243. short_name,
  244. value_name,
  245. [&value](const char* s) {
  246. value = s;
  247. return true;
  248. }
  249. };
  250. add_option(move(option));
  251. }
  252. void ArgsParser::add_option(int& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  253. {
  254. Option option {
  255. true,
  256. help_string,
  257. long_name,
  258. short_name,
  259. value_name,
  260. [&value](const char* s) {
  261. auto opt = StringView(s).to_int();
  262. value = opt.value_or(0);
  263. return opt.has_value();
  264. }
  265. };
  266. add_option(move(option));
  267. }
  268. void ArgsParser::add_option(double& value, const char* help_string, const char* long_name, char short_name, const char* 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. auto opt = convert_to_double(s);
  278. value = opt.value_or(0.0);
  279. return opt.has_value();
  280. }
  281. };
  282. add_option(move(option));
  283. }
  284. void ArgsParser::add_positional_argument(Arg&& arg)
  285. {
  286. m_positional_args.append(move(arg));
  287. }
  288. void ArgsParser::add_positional_argument(const char*& value, const char* help_string, const char* name, Required required)
  289. {
  290. Arg arg {
  291. help_string,
  292. name,
  293. required == Required::Yes ? 1 : 0,
  294. 1,
  295. [&value](const char* s) {
  296. value = s;
  297. return true;
  298. }
  299. };
  300. add_positional_argument(move(arg));
  301. }
  302. void ArgsParser::add_positional_argument(String& value, const char* help_string, const char* name, Required required)
  303. {
  304. Arg arg {
  305. help_string,
  306. name,
  307. required == Required::Yes ? 1 : 0,
  308. 1,
  309. [&value](const char* s) {
  310. value = s;
  311. return true;
  312. }
  313. };
  314. add_positional_argument(move(arg));
  315. }
  316. void ArgsParser::add_positional_argument(int& value, const char* help_string, const char* name, Required required)
  317. {
  318. Arg arg {
  319. help_string,
  320. name,
  321. required == Required::Yes ? 1 : 0,
  322. 1,
  323. [&value](const char* s) {
  324. auto opt = StringView(s).to_int();
  325. value = opt.value_or(0);
  326. return opt.has_value();
  327. }
  328. };
  329. add_positional_argument(move(arg));
  330. }
  331. void ArgsParser::add_positional_argument(double& value, const char* help_string, const char* name, Required required)
  332. {
  333. Arg arg {
  334. help_string,
  335. name,
  336. required == Required::Yes ? 1 : 0,
  337. 1,
  338. [&value](const char* s) {
  339. auto opt = convert_to_double(s);
  340. value = opt.value_or(0.0);
  341. return opt.has_value();
  342. }
  343. };
  344. add_positional_argument(move(arg));
  345. }
  346. void ArgsParser::add_positional_argument(Vector<const char*>& values, const char* help_string, const char* name, Required required)
  347. {
  348. Arg arg {
  349. help_string,
  350. name,
  351. required == Required::Yes ? 1 : 0,
  352. INT_MAX,
  353. [&values](const char* s) {
  354. values.append(s);
  355. return true;
  356. }
  357. };
  358. add_positional_argument(move(arg));
  359. }
  360. void ArgsParser::add_positional_argument(Vector<String>& values, const char* help_string, const char* name, Required required)
  361. {
  362. Arg arg {
  363. help_string,
  364. name,
  365. required == Required::Yes ? 1 : 0,
  366. INT_MAX,
  367. [&values](const char* s) {
  368. values.append(s);
  369. return true;
  370. }
  371. };
  372. add_positional_argument(move(arg));
  373. }
  374. }