ArgsParser.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /*
  2. * Copyright (c) 2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Format.h>
  7. #include <AK/StringBuilder.h>
  8. #include <LibCore/ArgsParser.h>
  9. #include <LibCore/ConfigFile.h>
  10. #include <getopt.h>
  11. #include <limits.h>
  12. #include <math.h>
  13. #include <stdio.h>
  14. #include <string.h>
  15. static Optional<double> convert_to_double(const char* s)
  16. {
  17. char* p;
  18. double v = strtod(s, &p);
  19. if (isnan(v) || p == s)
  20. return {};
  21. return v;
  22. }
  23. namespace Core {
  24. ArgsParser::ArgsParser()
  25. {
  26. add_option(m_show_help, "Display this message", "help", 0);
  27. add_option(m_show_version, "Print version", "version", 0);
  28. }
  29. bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_behavior)
  30. {
  31. auto fail = [this, argv, failure_behavior] {
  32. if (failure_behavior == FailureBehavior::PrintUsage || failure_behavior == FailureBehavior::PrintUsageAndExit)
  33. print_usage(stderr, argv[0]);
  34. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  35. exit(1);
  36. };
  37. Vector<option> long_options;
  38. StringBuilder short_options_builder;
  39. if (m_stop_on_first_non_option)
  40. short_options_builder.append('+');
  41. int index_of_found_long_option = -1;
  42. // Tell getopt() to reset its internal state, and start scanning from optind = 1.
  43. // We could also set optreset = 1, but the host platform may not support that.
  44. optind = 0;
  45. for (size_t i = 0; i < m_options.size(); i++) {
  46. auto& opt = m_options[i];
  47. if (opt.long_name) {
  48. option long_opt {
  49. opt.long_name,
  50. opt.requires_argument ? required_argument : no_argument,
  51. &index_of_found_long_option,
  52. static_cast<int>(i)
  53. };
  54. long_options.append(long_opt);
  55. }
  56. if (opt.short_name) {
  57. short_options_builder.append(opt.short_name);
  58. if (opt.requires_argument)
  59. short_options_builder.append(':');
  60. }
  61. }
  62. long_options.append({ 0, 0, 0, 0 });
  63. String short_options = short_options_builder.build();
  64. while (true) {
  65. int c = getopt_long(argc, argv, short_options.characters(), long_options.data(), nullptr);
  66. if (c == -1) {
  67. // We have reached the end.
  68. break;
  69. } else if (c == '?') {
  70. // There was an error, and getopt() has already
  71. // printed its error message.
  72. fail();
  73. return false;
  74. }
  75. // Let's see what option we just found.
  76. Option* found_option = nullptr;
  77. if (c == 0) {
  78. // It was a long option.
  79. VERIFY(index_of_found_long_option >= 0);
  80. found_option = &m_options[index_of_found_long_option];
  81. index_of_found_long_option = -1;
  82. } else {
  83. // It was a short option, look it up.
  84. auto it = m_options.find_if([c](auto& opt) { return c == opt.short_name; });
  85. VERIFY(!it.is_end());
  86. found_option = &*it;
  87. }
  88. VERIFY(found_option);
  89. const char* arg = found_option->requires_argument ? optarg : nullptr;
  90. if (!found_option->accept_value(arg)) {
  91. warnln("\033[31mInvalid value for option \033[1m{}\033[22m\033[0m", found_option->name_for_display());
  92. fail();
  93. return false;
  94. }
  95. }
  96. // We're done processing options, now let's parse positional arguments.
  97. int values_left = argc - optind;
  98. Vector<int, 16> num_values_for_arg;
  99. num_values_for_arg.resize(m_positional_args.size(), true);
  100. int total_values_required = 0;
  101. for (size_t i = 0; i < m_positional_args.size(); i++) {
  102. auto& arg = m_positional_args[i];
  103. num_values_for_arg[i] = arg.min_values;
  104. total_values_required += arg.min_values;
  105. }
  106. if (total_values_required > values_left) {
  107. fail();
  108. return false;
  109. }
  110. int extra_values_to_distribute = values_left - total_values_required;
  111. for (size_t i = 0; i < m_positional_args.size(); i++) {
  112. auto& arg = m_positional_args[i];
  113. int extra_values_to_this_arg = min(arg.max_values - arg.min_values, extra_values_to_distribute);
  114. num_values_for_arg[i] += extra_values_to_this_arg;
  115. extra_values_to_distribute -= extra_values_to_this_arg;
  116. if (extra_values_to_distribute == 0)
  117. break;
  118. }
  119. if (extra_values_to_distribute > 0) {
  120. // We still have too many values :(
  121. fail();
  122. return false;
  123. }
  124. for (size_t i = 0; i < m_positional_args.size(); i++) {
  125. auto& arg = m_positional_args[i];
  126. for (int j = 0; j < num_values_for_arg[i]; j++) {
  127. const char* value = argv[optind++];
  128. if (!arg.accept_value(value)) {
  129. warnln("Invalid value for argument {}", arg.name);
  130. fail();
  131. return false;
  132. }
  133. }
  134. }
  135. // We're done parsing! :)
  136. // Now let's show version or help if requested.
  137. if (m_show_version) {
  138. print_version(stdout);
  139. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  140. exit(0);
  141. return false;
  142. }
  143. if (m_show_help) {
  144. print_usage(stdout, argv[0]);
  145. if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
  146. exit(0);
  147. return false;
  148. }
  149. return true;
  150. }
  151. void ArgsParser::print_usage(FILE* file, const char* argv0)
  152. {
  153. out(file, "Usage:\n\t\033[1m{}\033[0m", argv0);
  154. for (auto& opt : m_options) {
  155. if (opt.long_name && !strcmp(opt.long_name, "help"))
  156. continue;
  157. if (opt.requires_argument)
  158. out(file, " [{} {}]", opt.name_for_display(), opt.value_name);
  159. else
  160. out(file, " [{}]", opt.name_for_display());
  161. }
  162. for (auto& arg : m_positional_args) {
  163. bool required = arg.min_values > 0;
  164. bool repeated = arg.max_values > 1;
  165. if (required && repeated)
  166. out(file, " <{}...>", arg.name);
  167. else if (required && !repeated)
  168. out(file, " <{}>", arg.name);
  169. else if (!required && repeated)
  170. out(file, " [{}...]", arg.name);
  171. else if (!required && !repeated)
  172. out(file, " [{}]", arg.name);
  173. }
  174. outln(file);
  175. if (m_general_help != nullptr && m_general_help[0] != '\0') {
  176. outln(file, "\nDescription:");
  177. outln(file, m_general_help);
  178. }
  179. if (!m_options.is_empty())
  180. outln(file, "\nOptions:");
  181. for (auto& opt : m_options) {
  182. auto print_argument = [&]() {
  183. if (opt.value_name) {
  184. if (opt.requires_argument)
  185. out(file, " {}", opt.value_name);
  186. else
  187. out(file, " [{}]", opt.value_name);
  188. }
  189. };
  190. out(file, "\t");
  191. if (opt.short_name) {
  192. out(file, "\033[1m-{}\033[0m", opt.short_name);
  193. print_argument();
  194. }
  195. if (opt.short_name && opt.long_name)
  196. out(file, ", ");
  197. if (opt.long_name) {
  198. out(file, "\033[1m--{}\033[0m", opt.long_name);
  199. print_argument();
  200. }
  201. if (opt.help_string)
  202. out(file, "\t{}", opt.help_string);
  203. outln(file);
  204. }
  205. if (!m_positional_args.is_empty())
  206. outln(file, "\nArguments:");
  207. for (auto& arg : m_positional_args) {
  208. out(file, "\t\033[1m{}\033[0m", arg.name);
  209. if (arg.help_string)
  210. out(file, "\t{}", arg.help_string);
  211. outln(file);
  212. }
  213. }
  214. void ArgsParser::print_version(FILE* file)
  215. {
  216. auto version_config = Core::ConfigFile::open("/res/version.ini");
  217. auto major_version = version_config->read_entry("Version", "Major", "0");
  218. auto minor_version = version_config->read_entry("Version", "Minor", "0");
  219. StringBuilder builder;
  220. builder.appendff("{}.{}", major_version, minor_version);
  221. if (auto git_version = version_config->read_entry("Version", "Git", ""); git_version != "")
  222. builder.appendff(".g{}", git_version);
  223. outln(file, builder.to_string());
  224. }
  225. void ArgsParser::add_option(Option&& option)
  226. {
  227. m_options.append(move(option));
  228. }
  229. void ArgsParser::add_option(bool& value, const char* help_string, const char* long_name, char short_name)
  230. {
  231. Option option {
  232. false,
  233. help_string,
  234. long_name,
  235. short_name,
  236. nullptr,
  237. [&value](const char* s) {
  238. VERIFY(s == nullptr);
  239. value = true;
  240. return true;
  241. }
  242. };
  243. add_option(move(option));
  244. }
  245. void ArgsParser::add_option(const char*& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  246. {
  247. Option option {
  248. true,
  249. help_string,
  250. long_name,
  251. short_name,
  252. value_name,
  253. [&value](const char* s) {
  254. value = s;
  255. return true;
  256. }
  257. };
  258. add_option(move(option));
  259. }
  260. void ArgsParser::add_option(String& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  261. {
  262. Option option {
  263. true,
  264. help_string,
  265. long_name,
  266. short_name,
  267. value_name,
  268. [&value](const char* s) {
  269. value = s;
  270. return true;
  271. }
  272. };
  273. add_option(move(option));
  274. }
  275. void ArgsParser::add_option(StringView& value, char const* help_string, char const* long_name, char short_name, char const* value_name)
  276. {
  277. Option option {
  278. true,
  279. help_string,
  280. long_name,
  281. short_name,
  282. value_name,
  283. [&value](const char* s) {
  284. value = s;
  285. return true;
  286. }
  287. };
  288. add_option(move(option));
  289. }
  290. void ArgsParser::add_option(int& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  291. {
  292. Option option {
  293. true,
  294. help_string,
  295. long_name,
  296. short_name,
  297. value_name,
  298. [&value](const char* s) {
  299. auto opt = StringView(s).to_int();
  300. value = opt.value_or(0);
  301. return opt.has_value();
  302. }
  303. };
  304. add_option(move(option));
  305. }
  306. void ArgsParser::add_option(unsigned& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  307. {
  308. Option option {
  309. true,
  310. help_string,
  311. long_name,
  312. short_name,
  313. value_name,
  314. [&value](const char* s) {
  315. auto opt = StringView(s).to_uint();
  316. value = opt.value_or(0);
  317. return opt.has_value();
  318. }
  319. };
  320. add_option(move(option));
  321. }
  322. void ArgsParser::add_option(double& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
  323. {
  324. Option option {
  325. true,
  326. help_string,
  327. long_name,
  328. short_name,
  329. value_name,
  330. [&value](const char* s) {
  331. auto opt = convert_to_double(s);
  332. value = opt.value_or(0.0);
  333. return opt.has_value();
  334. }
  335. };
  336. add_option(move(option));
  337. }
  338. void ArgsParser::add_positional_argument(Arg&& arg)
  339. {
  340. m_positional_args.append(move(arg));
  341. }
  342. void ArgsParser::add_positional_argument(const char*& value, const char* help_string, const char* name, Required required)
  343. {
  344. Arg arg {
  345. help_string,
  346. name,
  347. required == Required::Yes ? 1 : 0,
  348. 1,
  349. [&value](const char* s) {
  350. value = s;
  351. return true;
  352. }
  353. };
  354. add_positional_argument(move(arg));
  355. }
  356. void ArgsParser::add_positional_argument(String& value, const char* help_string, const char* name, Required required)
  357. {
  358. Arg arg {
  359. help_string,
  360. name,
  361. required == Required::Yes ? 1 : 0,
  362. 1,
  363. [&value](const char* s) {
  364. value = s;
  365. return true;
  366. }
  367. };
  368. add_positional_argument(move(arg));
  369. }
  370. void ArgsParser::add_positional_argument(StringView& value, char const* help_string, char const* name, Required required)
  371. {
  372. Arg arg {
  373. help_string,
  374. name,
  375. required == Required::Yes ? 1 : 0,
  376. 1,
  377. [&value](const char* s) {
  378. value = s;
  379. return true;
  380. }
  381. };
  382. add_positional_argument(move(arg));
  383. }
  384. void ArgsParser::add_positional_argument(int& value, const char* help_string, const char* name, Required required)
  385. {
  386. Arg arg {
  387. help_string,
  388. name,
  389. required == Required::Yes ? 1 : 0,
  390. 1,
  391. [&value](const char* s) {
  392. auto opt = StringView(s).to_int();
  393. value = opt.value_or(0);
  394. return opt.has_value();
  395. }
  396. };
  397. add_positional_argument(move(arg));
  398. }
  399. void ArgsParser::add_positional_argument(unsigned& value, const char* help_string, const char* name, Required required)
  400. {
  401. Arg arg {
  402. help_string,
  403. name,
  404. required == Required::Yes ? 1 : 0,
  405. 1,
  406. [&value](const char* s) {
  407. auto opt = StringView(s).to_uint();
  408. value = opt.value_or(0);
  409. return opt.has_value();
  410. }
  411. };
  412. add_positional_argument(move(arg));
  413. }
  414. void ArgsParser::add_positional_argument(double& value, const char* help_string, const char* name, Required required)
  415. {
  416. Arg arg {
  417. help_string,
  418. name,
  419. required == Required::Yes ? 1 : 0,
  420. 1,
  421. [&value](const char* s) {
  422. auto opt = convert_to_double(s);
  423. value = opt.value_or(0.0);
  424. return opt.has_value();
  425. }
  426. };
  427. add_positional_argument(move(arg));
  428. }
  429. void ArgsParser::add_positional_argument(Vector<const char*>& values, const char* help_string, const char* name, Required required)
  430. {
  431. Arg arg {
  432. help_string,
  433. name,
  434. required == Required::Yes ? 1 : 0,
  435. INT_MAX,
  436. [&values](const char* s) {
  437. values.append(s);
  438. return true;
  439. }
  440. };
  441. add_positional_argument(move(arg));
  442. }
  443. void ArgsParser::add_positional_argument(Vector<String>& values, const char* help_string, const char* name, Required required)
  444. {
  445. Arg arg {
  446. help_string,
  447. name,
  448. required == Required::Yes ? 1 : 0,
  449. INT_MAX,
  450. [&values](const char* s) {
  451. values.append(s);
  452. return true;
  453. }
  454. };
  455. add_positional_argument(move(arg));
  456. }
  457. }