ArgsParser.cpp 10 KB

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