getopt.cpp 12 KB

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