ArgsParser.cpp 9.9 KB

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