getopt.cpp 11 KB

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