ArgsParser.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. namespace Core {
  32. ArgsParser::ArgsParser()
  33. {
  34. add_option(m_show_help, "Display this message", "help", 0);
  35. }
  36. void ArgsParser::parse(int argc, char** argv)
  37. {
  38. auto print_usage_and_exit = [this, argv] {
  39. print_usage(stderr, argv[0]);
  40. exit(1);
  41. };
  42. Vector<option> long_options;
  43. StringBuilder short_options_builder;
  44. int index_of_found_long_option = -1;
  45. for (int 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. 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. print_usage_and_exit();
  73. }
  74. // Let's see what option we just found.
  75. Option* found_option = nullptr;
  76. if (c == 0) {
  77. // It was a long option.
  78. ASSERT(index_of_found_long_option >= 0);
  79. found_option = &m_options[index_of_found_long_option];
  80. index_of_found_long_option = -1;
  81. } else {
  82. // It was a short option, look it up.
  83. auto it = m_options.find([c](auto& opt) { return c == opt.short_name; });
  84. ASSERT(!it.is_end());
  85. found_option = &*it;
  86. }
  87. ASSERT(found_option);
  88. const char* arg = found_option->requires_argument ? optarg : nullptr;
  89. if (!found_option->accept_value(arg)) {
  90. fprintf(stderr, "Invalid value for option %s\n", found_option->name_for_display().characters());
  91. print_usage_and_exit();
  92. }
  93. }
  94. // We're done processing options, now let's parse positional arguments.
  95. int values_left = argc - optind;
  96. int num_values_for_arg[m_positional_args.size()];
  97. int total_values_required = 0;
  98. for (int i = 0; i < m_positional_args.size(); i++) {
  99. auto& arg = m_positional_args[i];
  100. num_values_for_arg[i] = arg.min_values;
  101. total_values_required += arg.min_values;
  102. }
  103. if (total_values_required > values_left)
  104. print_usage_and_exit();
  105. int extra_values_to_distribute = values_left - total_values_required;
  106. for (int i = 0; i < m_positional_args.size(); i++) {
  107. auto& arg = m_positional_args[i];
  108. int extra_values_to_this_arg = min(arg.max_values - arg.min_values, extra_values_to_distribute);
  109. num_values_for_arg[i] += extra_values_to_this_arg;
  110. extra_values_to_distribute -= extra_values_to_this_arg;
  111. if (extra_values_to_distribute == 0)
  112. break;
  113. }
  114. if (extra_values_to_distribute > 0) {
  115. // We still have too many values :(
  116. print_usage_and_exit();
  117. }
  118. for (int 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. fprintf(stderr, "Invalid value for argument %s\n", arg.name);
  124. print_usage_and_exit();
  125. }
  126. }
  127. }
  128. // We're done parsing! :)
  129. // Now let's show help if requested.
  130. if (m_show_help) {
  131. print_usage(stdout, argv[0]);
  132. exit(0);
  133. }
  134. }
  135. void ArgsParser::print_usage(FILE* file, const char* argv0)
  136. {
  137. fprintf(file, "Usage:\n\t%s", argv0);
  138. for (auto& opt : m_options) {
  139. if (opt.long_name && !strcmp(opt.long_name, "help"))
  140. continue;
  141. if (opt.requires_argument)
  142. fprintf(file, " [%s %s]", opt.name_for_display().characters(), opt.value_name);
  143. else
  144. fprintf(file, " [%s]", opt.name_for_display().characters());
  145. }
  146. for (auto& arg : m_positional_args) {
  147. bool required = arg.min_values > 0;
  148. bool repeated = arg.max_values > 1;
  149. if (required && repeated)
  150. fprintf(file, " <%s...>", arg.name);
  151. else if (required && !repeated)
  152. fprintf(file, " <%s>", arg.name);
  153. else if (!required && repeated)
  154. fprintf(file, " [%s...]", arg.name);
  155. else if (!required && !repeated)
  156. fprintf(file, " [%s]", arg.name);
  157. }
  158. if (!m_options.is_empty())
  159. fprintf(file, "\nOptions:\n");
  160. for (auto& opt : m_options) {
  161. auto print_argument = [&]() {
  162. if (opt.value_name) {
  163. if (opt.requires_argument)
  164. fprintf(file, " %s", opt.value_name);
  165. else
  166. fprintf(file, " [%s]", opt.value_name);
  167. }
  168. };
  169. fprintf(file, "\t");
  170. if (opt.short_name) {
  171. fprintf(file, "-%c", opt.short_name);
  172. print_argument();
  173. }
  174. if (opt.short_name && opt.long_name)
  175. fprintf(file, ", ");
  176. if (opt.long_name) {
  177. fprintf(file, "--%s", opt.long_name);
  178. print_argument();
  179. }
  180. if (opt.help_string)
  181. fprintf(file, "\t%s", opt.help_string);
  182. fprintf(file, "\n");
  183. }
  184. if (!m_positional_args.is_empty())
  185. fprintf(file, "\nArguments:\n");
  186. for (auto& arg : m_positional_args) {
  187. fprintf(file, "\t%s", arg.name);
  188. if (arg.help_string)
  189. fprintf(file, "\t%s", arg.help_string);
  190. fprintf(file, "\n");
  191. }
  192. }
  193. void ArgsParser::add_option(Option&& option)
  194. {
  195. m_options.append(move(option));
  196. }
  197. void ArgsParser::add_option(bool& value, const char* help_string, const char* long_name, char short_name)
  198. {
  199. Option option {
  200. false,
  201. help_string,
  202. long_name,
  203. short_name,
  204. nullptr,
  205. [&value](const char* s) {
  206. ASSERT(s == nullptr);
  207. value = true;
  208. return true;
  209. }
  210. };
  211. add_option(move(option));
  212. }
  213. void ArgsParser::add_option(const char*& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  214. {
  215. Option option {
  216. true,
  217. help_string,
  218. long_name,
  219. short_name,
  220. value_name,
  221. [&value](const char* s) {
  222. value = s;
  223. return true;
  224. }
  225. };
  226. add_option(move(option));
  227. }
  228. void ArgsParser::add_option(int& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  229. {
  230. Option option {
  231. true,
  232. help_string,
  233. long_name,
  234. short_name,
  235. value_name,
  236. [&value](const char* s) {
  237. bool ok;
  238. value = StringView(s).to_int(ok);
  239. return ok;
  240. }
  241. };
  242. add_option(move(option));
  243. }
  244. void ArgsParser::add_positional_argument(Arg&& arg)
  245. {
  246. m_positional_args.append(move(arg));
  247. }
  248. void ArgsParser::add_positional_argument(const char*& value, const char* help_string, const char* name, Required required)
  249. {
  250. Arg arg {
  251. help_string,
  252. name,
  253. required == Required::Yes ? 1 : 0,
  254. 1,
  255. [&value](const char* s) {
  256. value = s;
  257. return true;
  258. }
  259. };
  260. add_positional_argument(move(arg));
  261. }
  262. void ArgsParser::add_positional_argument(int& 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. bool ok;
  271. value = StringView(s).to_int(ok);
  272. return ok;
  273. }
  274. };
  275. add_positional_argument(move(arg));
  276. }
  277. void ArgsParser::add_positional_argument(Vector<const char*>& values, const char* help_string, const char* name, Required required)
  278. {
  279. Arg arg {
  280. help_string,
  281. name,
  282. required == Required::Yes ? 1 : 0,
  283. INT_MAX,
  284. [&values](const char* s) {
  285. values.append(s);
  286. return true;
  287. }
  288. };
  289. add_positional_argument(move(arg));
  290. }
  291. }