ArgsParser.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*
  2. * Copyright (c) 2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Format.h>
  27. #include <AK/StringBuilder.h>
  28. #include <LibCore/ArgsParser.h>
  29. #include <getopt.h>
  30. #include <limits.h>
  31. #include <stdio.h>
  32. #include <string.h>
  33. static constexpr bool isnan(double __x) { return __builtin_isnan(__x); }
  34. static Optional<double> convert_to_double(const char* s)
  35. {
  36. char* p;
  37. double v = strtod(s, &p);
  38. if (isnan(v) || p == s)
  39. return {};
  40. return v;
  41. }
  42. namespace Core {
  43. ArgsParser::ArgsParser()
  44. {
  45. add_option(m_show_help, "Display this message", "help", 0);
  46. }
  47. bool ArgsParser::parse(int argc, char** argv, bool exit_on_failure)
  48. {
  49. auto print_usage_and_exit = [this, argv, exit_on_failure] {
  50. print_usage(stderr, argv[0]);
  51. if (exit_on_failure)
  52. exit(1);
  53. };
  54. Vector<option> long_options;
  55. StringBuilder short_options_builder;
  56. int index_of_found_long_option = -1;
  57. // Tell getopt() to reset its internal state, and start scanning from optind = 1.
  58. // We could also set optreset = 1, but the host platform may not support that.
  59. optind = 0;
  60. for (size_t i = 0; i < m_options.size(); i++) {
  61. auto& opt = m_options[i];
  62. if (opt.long_name) {
  63. option long_opt {
  64. opt.long_name,
  65. opt.requires_argument ? required_argument : no_argument,
  66. &index_of_found_long_option,
  67. static_cast<int>(i)
  68. };
  69. long_options.append(long_opt);
  70. }
  71. if (opt.short_name) {
  72. short_options_builder.append(opt.short_name);
  73. if (opt.requires_argument)
  74. short_options_builder.append(':');
  75. }
  76. }
  77. long_options.append({ 0, 0, 0, 0 });
  78. String short_options = short_options_builder.build();
  79. while (true) {
  80. int c = getopt_long(argc, argv, short_options.characters(), long_options.data(), nullptr);
  81. if (c == -1) {
  82. // We have reached the end.
  83. break;
  84. } else if (c == '?') {
  85. // There was an error, and getopt() has already
  86. // printed its error message.
  87. print_usage_and_exit();
  88. return false;
  89. }
  90. // Let's see what option we just found.
  91. Option* found_option = nullptr;
  92. if (c == 0) {
  93. // It was a long option.
  94. ASSERT(index_of_found_long_option >= 0);
  95. found_option = &m_options[index_of_found_long_option];
  96. index_of_found_long_option = -1;
  97. } else {
  98. // It was a short option, look it up.
  99. auto it = m_options.find([c](auto& opt) { return c == opt.short_name; });
  100. ASSERT(!it.is_end());
  101. found_option = &*it;
  102. }
  103. ASSERT(found_option);
  104. const char* arg = found_option->requires_argument ? optarg : nullptr;
  105. if (!found_option->accept_value(arg)) {
  106. warnln("\033[31mInvalid value for option \033[1m{}\033[22m, dude\033[0m", found_option->name_for_display());
  107. print_usage_and_exit();
  108. return false;
  109. }
  110. }
  111. // We're done processing options, now let's parse positional arguments.
  112. int values_left = argc - optind;
  113. int num_values_for_arg[m_positional_args.size()];
  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. print_usage_and_exit();
  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. print_usage_and_exit();
  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. print_usage_and_exit();
  145. return false;
  146. }
  147. }
  148. }
  149. // We're done parsing! :)
  150. // Now let's show help if requested.
  151. if (m_show_help) {
  152. print_usage(stdout, argv[0]);
  153. if (exit_on_failure)
  154. exit(0);
  155. return false;
  156. }
  157. return true;
  158. }
  159. void ArgsParser::print_usage(FILE* file, const char* argv0)
  160. {
  161. new_out(file, "Usage:\n\t\033[1m{}\033[0m", argv0);
  162. for (auto& opt : m_options) {
  163. if (opt.long_name && !strcmp(opt.long_name, "help"))
  164. continue;
  165. if (opt.requires_argument)
  166. new_out(file, " [{} {}]", opt.name_for_display(), opt.value_name);
  167. else
  168. new_out(file, " [{}]", opt.name_for_display());
  169. }
  170. for (auto& arg : m_positional_args) {
  171. bool required = arg.min_values > 0;
  172. bool repeated = arg.max_values > 1;
  173. if (required && repeated)
  174. new_out(file, " <{}...>", arg.name);
  175. else if (required && !repeated)
  176. new_out(file, " <{}>", arg.name);
  177. else if (!required && repeated)
  178. new_out(file, " [{}...]", arg.name);
  179. else if (!required && !repeated)
  180. new_out(file, " [{}]", arg.name);
  181. }
  182. outln(file);
  183. if (!m_options.is_empty())
  184. outln(file, "\nOptions:");
  185. for (auto& opt : m_options) {
  186. auto print_argument = [&]() {
  187. if (opt.value_name) {
  188. if (opt.requires_argument)
  189. new_out(file, " {}", opt.value_name);
  190. else
  191. new_out(file, " [{}]", opt.value_name);
  192. }
  193. };
  194. new_out(file, "\t");
  195. if (opt.short_name) {
  196. new_out(file, "\033[1m-{}\033[0m", opt.short_name);
  197. print_argument();
  198. }
  199. if (opt.short_name && opt.long_name)
  200. new_out(file, ", ");
  201. if (opt.long_name) {
  202. new_out(file, "\033[1m--{}\033[0m", opt.long_name);
  203. print_argument();
  204. }
  205. if (opt.help_string)
  206. new_out(file, "\t{}", opt.help_string);
  207. outln(file);
  208. }
  209. if (!m_positional_args.is_empty())
  210. outln(file, "\nArguments:");
  211. for (auto& arg : m_positional_args) {
  212. new_out(file, "\t\033[1m{}\033[0m", arg.name);
  213. if (arg.help_string)
  214. new_out(file, "\t{}", arg.help_string);
  215. outln(file);
  216. }
  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. ASSERT(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(int& 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. auto opt = StringView(s).to_int();
  263. value = opt.value_or(0);
  264. return opt.has_value();
  265. }
  266. };
  267. add_option(move(option));
  268. }
  269. void ArgsParser::add_option(double& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  270. {
  271. Option option {
  272. true,
  273. help_string,
  274. long_name,
  275. short_name,
  276. value_name,
  277. [&value](const char* s) {
  278. auto opt = convert_to_double(s);
  279. value = opt.value_or(0.0);
  280. return opt.has_value();
  281. }
  282. };
  283. add_option(move(option));
  284. }
  285. void ArgsParser::add_positional_argument(Arg&& arg)
  286. {
  287. m_positional_args.append(move(arg));
  288. }
  289. void ArgsParser::add_positional_argument(const char*& value, const char* help_string, const char* name, Required required)
  290. {
  291. Arg arg {
  292. help_string,
  293. name,
  294. required == Required::Yes ? 1 : 0,
  295. 1,
  296. [&value](const char* s) {
  297. value = s;
  298. return true;
  299. }
  300. };
  301. add_positional_argument(move(arg));
  302. }
  303. void ArgsParser::add_positional_argument(int& value, const char* help_string, const char* name, Required required)
  304. {
  305. Arg arg {
  306. help_string,
  307. name,
  308. required == Required::Yes ? 1 : 0,
  309. 1,
  310. [&value](const char* s) {
  311. auto opt = StringView(s).to_int();
  312. value = opt.value_or(0);
  313. return opt.has_value();
  314. }
  315. };
  316. add_positional_argument(move(arg));
  317. }
  318. void ArgsParser::add_positional_argument(double& value, const char* help_string, const char* name, Required required)
  319. {
  320. Arg arg {
  321. help_string,
  322. name,
  323. required == Required::Yes ? 1 : 0,
  324. 1,
  325. [&value](const char* s) {
  326. auto opt = convert_to_double(s);
  327. value = opt.value_or(0.0);
  328. return opt.has_value();
  329. }
  330. };
  331. add_positional_argument(move(arg));
  332. }
  333. void ArgsParser::add_positional_argument(Vector<const char*>& values, const char* help_string, const char* name, Required required)
  334. {
  335. Arg arg {
  336. help_string,
  337. name,
  338. required == Required::Yes ? 1 : 0,
  339. INT_MAX,
  340. [&values](const char* s) {
  341. values.append(s);
  342. return true;
  343. }
  344. };
  345. add_positional_argument(move(arg));
  346. }
  347. }