getopt.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. /*
  2. * Copyright (c) 2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/StringView.h>
  7. #include <AK/Vector.h>
  8. #include <getopt.h>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <unistd.h>
  12. int opterr = 1;
  13. int optopt = 0;
  14. int optind = 1;
  15. int optreset = 0;
  16. char* optarg = nullptr;
  17. // POSIX says, "When an element of argv[] contains multiple option characters,
  18. // it is unspecified how getopt() determines which options have already been
  19. // processed". Well, this is how we do it.
  20. static size_t s_index_into_multioption_argument = 0;
  21. [[gnu::format(printf, 1, 2)]] static inline void report_error(char const* format, ...)
  22. {
  23. if (!opterr)
  24. return;
  25. fputs("\033[31m", stderr);
  26. va_list ap;
  27. va_start(ap, format);
  28. vfprintf(stderr, format, ap);
  29. va_end(ap);
  30. fputs("\033[0m\n", stderr);
  31. }
  32. namespace {
  33. class OptionParser {
  34. public:
  35. OptionParser(int argc, char* const* argv, StringView short_options, option const* long_options, int* out_long_option_index = nullptr);
  36. int getopt();
  37. private:
  38. bool lookup_short_option(char option, int& needs_value) const;
  39. int handle_short_option();
  40. option const* lookup_long_option(char* raw) const;
  41. int handle_long_option();
  42. void shift_argv();
  43. bool find_next_option();
  44. StringView current_arg() const
  45. {
  46. auto const* arg_ptr = m_argv[m_arg_index];
  47. if (arg_ptr == NULL)
  48. return {};
  49. return { arg_ptr, strlen(arg_ptr) };
  50. }
  51. size_t m_argc { 0 };
  52. char* const* m_argv { nullptr };
  53. StringView m_short_options;
  54. option const* m_long_options { nullptr };
  55. int* m_out_long_option_index { nullptr };
  56. bool m_stop_on_first_non_option { false };
  57. size_t m_arg_index { 0 };
  58. size_t m_consumed_args { 0 };
  59. };
  60. OptionParser::OptionParser(int argc, char* const* argv, StringView short_options, option const* long_options, int* out_long_option_index)
  61. : m_argc(argc)
  62. , m_argv(argv)
  63. , m_short_options(short_options)
  64. , m_long_options(long_options)
  65. , m_out_long_option_index(out_long_option_index)
  66. {
  67. // In the following case:
  68. // $ foo bar -o baz
  69. // we want to parse the option (-o baz) first, and leave the argument (bar)
  70. // in argv after we return -1 when invoked the second time. So we reorder
  71. // argv to put options first and positional arguments next. To turn this
  72. // behavior off, start the short options spec with a "+". This is a GNU
  73. // extension that we support.
  74. m_stop_on_first_non_option = short_options.starts_with('+');
  75. // See if we should reset the internal state.
  76. if (optreset || optind == 0) {
  77. optreset = 0;
  78. optind = 1;
  79. s_index_into_multioption_argument = 0;
  80. }
  81. optopt = 0;
  82. optarg = nullptr;
  83. }
  84. int OptionParser::getopt()
  85. {
  86. bool should_reorder_argv = !m_stop_on_first_non_option;
  87. int res = -1;
  88. bool found_an_option = find_next_option();
  89. auto arg = current_arg();
  90. if (!found_an_option) {
  91. res = -1;
  92. if (arg == "--")
  93. m_consumed_args = 1;
  94. else
  95. m_consumed_args = 0;
  96. } else {
  97. // Alright, so we have an option on our hands!
  98. bool is_long_option = arg.starts_with("--");
  99. if (is_long_option)
  100. res = handle_long_option();
  101. else
  102. res = handle_short_option();
  103. // If we encountered an error, return immediately.
  104. if (res == '?')
  105. return '?';
  106. }
  107. if (should_reorder_argv)
  108. shift_argv();
  109. else
  110. VERIFY(optind == static_cast<int>(m_arg_index));
  111. optind += m_consumed_args;
  112. return res;
  113. }
  114. bool OptionParser::lookup_short_option(char option, int& needs_value) const
  115. {
  116. Vector<StringView> parts = m_short_options.split_view(option, true);
  117. VERIFY(parts.size() <= 2);
  118. if (parts.size() < 2) {
  119. // Haven't found the option in the spec.
  120. return false;
  121. }
  122. if (parts[1].starts_with("::")) {
  123. // If an option is followed by two colons, it optionally accepts an
  124. // argument.
  125. needs_value = optional_argument;
  126. } else if (parts[1].starts_with(':')) {
  127. // If it's followed by one colon, it requires an argument.
  128. needs_value = required_argument;
  129. } else {
  130. // Otherwise, it doesn't accept arguments.
  131. needs_value = no_argument;
  132. }
  133. return true;
  134. }
  135. int OptionParser::handle_short_option()
  136. {
  137. StringView arg = current_arg();
  138. VERIFY(arg.starts_with('-'));
  139. if (s_index_into_multioption_argument == 0) {
  140. // Just starting to parse this argument, skip the "-".
  141. s_index_into_multioption_argument = 1;
  142. }
  143. char option = arg[s_index_into_multioption_argument];
  144. s_index_into_multioption_argument++;
  145. int needs_value = no_argument;
  146. bool ok = lookup_short_option(option, needs_value);
  147. if (!ok) {
  148. optopt = option;
  149. report_error("Unrecognized option \033[1m-%c\033[22m", option);
  150. return '?';
  151. }
  152. // Let's see if we're at the end of this argument already.
  153. if (s_index_into_multioption_argument < arg.length()) {
  154. // This not yet the end.
  155. if (needs_value == no_argument) {
  156. optarg = nullptr;
  157. m_consumed_args = 0;
  158. } else {
  159. // Treat the rest of the argument as the value, the "-ovalue"
  160. // syntax.
  161. optarg = m_argv[m_arg_index] + s_index_into_multioption_argument;
  162. // Next time, process the next argument.
  163. s_index_into_multioption_argument = 0;
  164. m_consumed_args = 1;
  165. }
  166. } else {
  167. s_index_into_multioption_argument = 0;
  168. if (needs_value != required_argument) {
  169. optarg = nullptr;
  170. m_consumed_args = 1;
  171. } else if (m_arg_index + 1 < m_argc) {
  172. // Treat the next argument as a value, the "-o value" syntax.
  173. optarg = m_argv[m_arg_index + 1];
  174. m_consumed_args = 2;
  175. } else {
  176. report_error("Missing value for option \033[1m-%c\033[22m", option);
  177. return '?';
  178. }
  179. }
  180. return option;
  181. }
  182. option const* OptionParser::lookup_long_option(char* raw) const
  183. {
  184. StringView arg { raw, strlen(raw) };
  185. for (size_t index = 0; m_long_options[index].name; index++) {
  186. auto& option = m_long_options[index];
  187. StringView name { option.name, strlen(option.name) };
  188. if (!arg.starts_with(name))
  189. continue;
  190. // It would be better to not write out the index at all unless we're
  191. // sure we've found the right option, but whatever.
  192. if (m_out_long_option_index)
  193. *m_out_long_option_index = index;
  194. // Can either be "--option" or "--option=value".
  195. if (arg.length() == name.length()) {
  196. optarg = nullptr;
  197. return &option;
  198. }
  199. VERIFY(arg.length() > name.length());
  200. if (arg[name.length()] == '=') {
  201. optarg = raw + name.length() + 1;
  202. return &option;
  203. }
  204. }
  205. return nullptr;
  206. }
  207. int OptionParser::handle_long_option()
  208. {
  209. VERIFY(current_arg().starts_with("--"sv));
  210. // We cannot set optopt to anything sensible for long options, so set it to 0.
  211. optopt = 0;
  212. auto* option = lookup_long_option(m_argv[m_arg_index] + 2);
  213. if (!option) {
  214. report_error("Unrecognized option \033[1m%s\033[22m", m_argv[m_arg_index]);
  215. return '?';
  216. }
  217. // lookup_long_option() will also set optarg if the value of the option is
  218. // specified using "--option=value" syntax.
  219. // Figure out whether this option needs and/or has a value (also called "an
  220. // argument", but let's not call it that to distinguish it from argv
  221. // elements).
  222. switch (option->has_arg) {
  223. case no_argument:
  224. if (optarg) {
  225. report_error("Option \033[1m--%s\033[22m doesn't accept an argument", option->name);
  226. return '?';
  227. }
  228. m_consumed_args = 1;
  229. break;
  230. case optional_argument:
  231. m_consumed_args = 1;
  232. break;
  233. case required_argument:
  234. if (optarg) {
  235. // Value specified using "--option=value" syntax.
  236. m_consumed_args = 1;
  237. } else if (m_arg_index + 1 < m_argc) {
  238. // Treat the next argument as a value in "--option value" syntax.
  239. optarg = m_argv[m_arg_index + 1];
  240. m_consumed_args = 2;
  241. } else {
  242. report_error("Missing value for option \033[1m--%s\033[22m", option->name);
  243. return '?';
  244. }
  245. break;
  246. default:
  247. VERIFY_NOT_REACHED();
  248. }
  249. // Now that we've figured the value out, see about reporting this option to
  250. // our caller.
  251. if (option->flag) {
  252. *option->flag = option->val;
  253. return 0;
  254. }
  255. return option->val;
  256. }
  257. void OptionParser::shift_argv()
  258. {
  259. // We've just parsed an option (which perhaps has a value).
  260. // Put the option (along with it value, if any) in front of other arguments.
  261. VERIFY(optind <= static_cast<int>(m_arg_index));
  262. if (optind == static_cast<int>(m_arg_index) || m_consumed_args == 0) {
  263. // Nothing to do!
  264. return;
  265. }
  266. auto new_argv = const_cast<char**>(m_argv);
  267. char* buffer[m_consumed_args];
  268. memcpy(buffer, &new_argv[m_arg_index], sizeof(char*) * m_consumed_args);
  269. memmove(&new_argv[optind + m_consumed_args], &new_argv[optind], sizeof(char*) * (m_arg_index - optind));
  270. memcpy(&new_argv[optind], buffer, sizeof(char*) * m_consumed_args);
  271. }
  272. bool OptionParser::find_next_option()
  273. {
  274. for (m_arg_index = optind; m_arg_index < m_argc && m_argv[m_arg_index]; m_arg_index++) {
  275. StringView arg = current_arg();
  276. // Anything that doesn't start with a "-" is not an option.
  277. if (!arg.starts_with('-')) {
  278. if (m_stop_on_first_non_option)
  279. return false;
  280. continue;
  281. }
  282. // As a special case, a single "-" is not an option either.
  283. // (It's typically used by programs to refer to stdin).
  284. if (arg == "-")
  285. continue;
  286. // As another special case, a "--" is not an option either, and we stop
  287. // looking for further options if we encounter it.
  288. if (arg == "--")
  289. return false;
  290. // Otherwise, we have found an option!
  291. return true;
  292. }
  293. // Reached the end and still found no options.
  294. return false;
  295. }
  296. }
  297. int getopt(int argc, char* const* argv, char const* short_options)
  298. {
  299. option dummy { nullptr, 0, nullptr, 0 };
  300. OptionParser parser { argc, argv, { short_options, strlen(short_options) }, &dummy };
  301. return parser.getopt();
  302. }
  303. int getopt_long(int argc, char* const* argv, char const* short_options, const struct option* long_options, int* out_long_option_index)
  304. {
  305. OptionParser parser { argc, argv, { short_options, strlen(short_options) }, long_options, out_long_option_index };
  306. return parser.getopt();
  307. }