ArgsParser.cpp 10 KB

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