getopt.cpp 10 KB

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