parse-options.c 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <linux/compiler.h>
  3. #include <linux/string.h>
  4. #include <linux/types.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <stdint.h>
  8. #include <string.h>
  9. #include <ctype.h>
  10. #include "subcmd-util.h"
  11. #include "parse-options.h"
  12. #include "subcmd-config.h"
  13. #include "pager.h"
  14. #define OPT_SHORT 1
  15. #define OPT_UNSET 2
  16. char *error_buf;
  17. static int opterror(const struct option *opt, const char *reason, int flags)
  18. {
  19. if (flags & OPT_SHORT)
  20. fprintf(stderr, " Error: switch `%c' %s", opt->short_name, reason);
  21. else if (flags & OPT_UNSET)
  22. fprintf(stderr, " Error: option `no-%s' %s", opt->long_name, reason);
  23. else
  24. fprintf(stderr, " Error: option `%s' %s", opt->long_name, reason);
  25. return -1;
  26. }
  27. static const char *skip_prefix(const char *str, const char *prefix)
  28. {
  29. size_t len = strlen(prefix);
  30. return strncmp(str, prefix, len) ? NULL : str + len;
  31. }
  32. static void optwarning(const struct option *opt, const char *reason, int flags)
  33. {
  34. if (flags & OPT_SHORT)
  35. fprintf(stderr, " Warning: switch `%c' %s", opt->short_name, reason);
  36. else if (flags & OPT_UNSET)
  37. fprintf(stderr, " Warning: option `no-%s' %s", opt->long_name, reason);
  38. else
  39. fprintf(stderr, " Warning: option `%s' %s", opt->long_name, reason);
  40. }
  41. static int get_arg(struct parse_opt_ctx_t *p, const struct option *opt,
  42. int flags, const char **arg)
  43. {
  44. const char *res;
  45. if (p->opt) {
  46. res = p->opt;
  47. p->opt = NULL;
  48. } else if ((opt->flags & PARSE_OPT_LASTARG_DEFAULT) && (p->argc == 1 ||
  49. **(p->argv + 1) == '-')) {
  50. res = (const char *)opt->defval;
  51. } else if (p->argc > 1) {
  52. p->argc--;
  53. res = *++p->argv;
  54. } else
  55. return opterror(opt, "requires a value", flags);
  56. if (arg)
  57. *arg = res;
  58. return 0;
  59. }
  60. static int get_value(struct parse_opt_ctx_t *p,
  61. const struct option *opt, int flags)
  62. {
  63. const char *s, *arg = NULL;
  64. const int unset = flags & OPT_UNSET;
  65. int err;
  66. if (unset && p->opt)
  67. return opterror(opt, "takes no value", flags);
  68. if (unset && (opt->flags & PARSE_OPT_NONEG))
  69. return opterror(opt, "isn't available", flags);
  70. if (opt->flags & PARSE_OPT_DISABLED)
  71. return opterror(opt, "is not usable", flags);
  72. if (opt->flags & PARSE_OPT_EXCLUSIVE) {
  73. if (p->excl_opt && p->excl_opt != opt) {
  74. char msg[128];
  75. if (((flags & OPT_SHORT) && p->excl_opt->short_name) ||
  76. p->excl_opt->long_name == NULL) {
  77. snprintf(msg, sizeof(msg), "cannot be used with switch `%c'",
  78. p->excl_opt->short_name);
  79. } else {
  80. snprintf(msg, sizeof(msg), "cannot be used with %s",
  81. p->excl_opt->long_name);
  82. }
  83. opterror(opt, msg, flags);
  84. return -3;
  85. }
  86. p->excl_opt = opt;
  87. }
  88. if (!(flags & OPT_SHORT) && p->opt) {
  89. switch (opt->type) {
  90. case OPTION_CALLBACK:
  91. if (!(opt->flags & PARSE_OPT_NOARG))
  92. break;
  93. /* FALLTHROUGH */
  94. case OPTION_BOOLEAN:
  95. case OPTION_INCR:
  96. case OPTION_BIT:
  97. case OPTION_SET_UINT:
  98. case OPTION_SET_PTR:
  99. return opterror(opt, "takes no value", flags);
  100. case OPTION_END:
  101. case OPTION_ARGUMENT:
  102. case OPTION_GROUP:
  103. case OPTION_STRING:
  104. case OPTION_INTEGER:
  105. case OPTION_UINTEGER:
  106. case OPTION_LONG:
  107. case OPTION_ULONG:
  108. case OPTION_U64:
  109. default:
  110. break;
  111. }
  112. }
  113. if (opt->flags & PARSE_OPT_NOBUILD) {
  114. char reason[128];
  115. bool noarg = false;
  116. err = snprintf(reason, sizeof(reason),
  117. opt->flags & PARSE_OPT_CANSKIP ?
  118. "is being ignored because %s " :
  119. "is not available because %s",
  120. opt->build_opt);
  121. reason[sizeof(reason) - 1] = '\0';
  122. if (err < 0)
  123. strncpy(reason, opt->flags & PARSE_OPT_CANSKIP ?
  124. "is being ignored" :
  125. "is not available",
  126. sizeof(reason));
  127. if (!(opt->flags & PARSE_OPT_CANSKIP))
  128. return opterror(opt, reason, flags);
  129. err = 0;
  130. if (unset)
  131. noarg = true;
  132. if (opt->flags & PARSE_OPT_NOARG)
  133. noarg = true;
  134. if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
  135. noarg = true;
  136. switch (opt->type) {
  137. case OPTION_BOOLEAN:
  138. case OPTION_INCR:
  139. case OPTION_BIT:
  140. case OPTION_SET_UINT:
  141. case OPTION_SET_PTR:
  142. case OPTION_END:
  143. case OPTION_ARGUMENT:
  144. case OPTION_GROUP:
  145. noarg = true;
  146. break;
  147. case OPTION_CALLBACK:
  148. case OPTION_STRING:
  149. case OPTION_INTEGER:
  150. case OPTION_UINTEGER:
  151. case OPTION_LONG:
  152. case OPTION_ULONG:
  153. case OPTION_U64:
  154. default:
  155. break;
  156. }
  157. if (!noarg)
  158. err = get_arg(p, opt, flags, NULL);
  159. if (err)
  160. return err;
  161. optwarning(opt, reason, flags);
  162. return 0;
  163. }
  164. switch (opt->type) {
  165. case OPTION_BIT:
  166. if (unset)
  167. *(int *)opt->value &= ~opt->defval;
  168. else
  169. *(int *)opt->value |= opt->defval;
  170. return 0;
  171. case OPTION_BOOLEAN:
  172. *(bool *)opt->value = unset ? false : true;
  173. if (opt->set)
  174. *(bool *)opt->set = true;
  175. return 0;
  176. case OPTION_INCR:
  177. *(int *)opt->value = unset ? 0 : *(int *)opt->value + 1;
  178. return 0;
  179. case OPTION_SET_UINT:
  180. *(unsigned int *)opt->value = unset ? 0 : opt->defval;
  181. return 0;
  182. case OPTION_SET_PTR:
  183. *(void **)opt->value = unset ? NULL : (void *)opt->defval;
  184. return 0;
  185. case OPTION_STRING:
  186. err = 0;
  187. if (unset)
  188. *(const char **)opt->value = NULL;
  189. else if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
  190. *(const char **)opt->value = (const char *)opt->defval;
  191. else
  192. err = get_arg(p, opt, flags, (const char **)opt->value);
  193. if (opt->set)
  194. *(bool *)opt->set = true;
  195. /* PARSE_OPT_NOEMPTY: Allow NULL but disallow empty string. */
  196. if (opt->flags & PARSE_OPT_NOEMPTY) {
  197. const char *val = *(const char **)opt->value;
  198. if (!val)
  199. return err;
  200. /* Similar to unset if we are given an empty string. */
  201. if (val[0] == '\0') {
  202. *(const char **)opt->value = NULL;
  203. return 0;
  204. }
  205. }
  206. return err;
  207. case OPTION_CALLBACK:
  208. if (opt->set)
  209. *(bool *)opt->set = true;
  210. if (unset)
  211. return (*opt->callback)(opt, NULL, 1) ? (-1) : 0;
  212. if (opt->flags & PARSE_OPT_NOARG)
  213. return (*opt->callback)(opt, NULL, 0) ? (-1) : 0;
  214. if (opt->flags & PARSE_OPT_OPTARG && !p->opt)
  215. return (*opt->callback)(opt, NULL, 0) ? (-1) : 0;
  216. if (get_arg(p, opt, flags, &arg))
  217. return -1;
  218. return (*opt->callback)(opt, arg, 0) ? (-1) : 0;
  219. case OPTION_INTEGER:
  220. if (unset) {
  221. *(int *)opt->value = 0;
  222. return 0;
  223. }
  224. if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
  225. *(int *)opt->value = opt->defval;
  226. return 0;
  227. }
  228. if (get_arg(p, opt, flags, &arg))
  229. return -1;
  230. *(int *)opt->value = strtol(arg, (char **)&s, 10);
  231. if (*s)
  232. return opterror(opt, "expects a numerical value", flags);
  233. return 0;
  234. case OPTION_UINTEGER:
  235. if (unset) {
  236. *(unsigned int *)opt->value = 0;
  237. return 0;
  238. }
  239. if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
  240. *(unsigned int *)opt->value = opt->defval;
  241. return 0;
  242. }
  243. if (get_arg(p, opt, flags, &arg))
  244. return -1;
  245. if (arg[0] == '-')
  246. return opterror(opt, "expects an unsigned numerical value", flags);
  247. *(unsigned int *)opt->value = strtol(arg, (char **)&s, 10);
  248. if (*s)
  249. return opterror(opt, "expects a numerical value", flags);
  250. return 0;
  251. case OPTION_LONG:
  252. if (unset) {
  253. *(long *)opt->value = 0;
  254. return 0;
  255. }
  256. if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
  257. *(long *)opt->value = opt->defval;
  258. return 0;
  259. }
  260. if (get_arg(p, opt, flags, &arg))
  261. return -1;
  262. *(long *)opt->value = strtol(arg, (char **)&s, 10);
  263. if (*s)
  264. return opterror(opt, "expects a numerical value", flags);
  265. return 0;
  266. case OPTION_ULONG:
  267. if (unset) {
  268. *(unsigned long *)opt->value = 0;
  269. return 0;
  270. }
  271. if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
  272. *(unsigned long *)opt->value = opt->defval;
  273. return 0;
  274. }
  275. if (get_arg(p, opt, flags, &arg))
  276. return -1;
  277. *(unsigned long *)opt->value = strtoul(arg, (char **)&s, 10);
  278. if (*s)
  279. return opterror(opt, "expects a numerical value", flags);
  280. return 0;
  281. case OPTION_U64:
  282. if (unset) {
  283. *(u64 *)opt->value = 0;
  284. return 0;
  285. }
  286. if (opt->flags & PARSE_OPT_OPTARG && !p->opt) {
  287. *(u64 *)opt->value = opt->defval;
  288. return 0;
  289. }
  290. if (get_arg(p, opt, flags, &arg))
  291. return -1;
  292. if (arg[0] == '-')
  293. return opterror(opt, "expects an unsigned numerical value", flags);
  294. *(u64 *)opt->value = strtoull(arg, (char **)&s, 10);
  295. if (*s)
  296. return opterror(opt, "expects a numerical value", flags);
  297. return 0;
  298. case OPTION_END:
  299. case OPTION_ARGUMENT:
  300. case OPTION_GROUP:
  301. default:
  302. die("should not happen, someone must be hit on the forehead");
  303. }
  304. }
  305. static int parse_short_opt(struct parse_opt_ctx_t *p, const struct option *options)
  306. {
  307. retry:
  308. for (; options->type != OPTION_END; options++) {
  309. if (options->short_name == *p->opt) {
  310. p->opt = p->opt[1] ? p->opt + 1 : NULL;
  311. return get_value(p, options, OPT_SHORT);
  312. }
  313. }
  314. if (options->parent) {
  315. options = options->parent;
  316. goto retry;
  317. }
  318. return -2;
  319. }
  320. static int parse_long_opt(struct parse_opt_ctx_t *p, const char *arg,
  321. const struct option *options)
  322. {
  323. const char *arg_end = strchr(arg, '=');
  324. const struct option *abbrev_option = NULL, *ambiguous_option = NULL;
  325. int abbrev_flags = 0, ambiguous_flags = 0;
  326. if (!arg_end)
  327. arg_end = arg + strlen(arg);
  328. retry:
  329. for (; options->type != OPTION_END; options++) {
  330. const char *rest;
  331. int flags = 0;
  332. if (!options->long_name)
  333. continue;
  334. rest = skip_prefix(arg, options->long_name);
  335. if (options->type == OPTION_ARGUMENT) {
  336. if (!rest)
  337. continue;
  338. if (*rest == '=')
  339. return opterror(options, "takes no value", flags);
  340. if (*rest)
  341. continue;
  342. p->out[p->cpidx++] = arg - 2;
  343. return 0;
  344. }
  345. if (!rest) {
  346. if (strstarts(options->long_name, "no-")) {
  347. /*
  348. * The long name itself starts with "no-", so
  349. * accept the option without "no-" so that users
  350. * do not have to enter "no-no-" to get the
  351. * negation.
  352. */
  353. rest = skip_prefix(arg, options->long_name + 3);
  354. if (rest) {
  355. flags |= OPT_UNSET;
  356. goto match;
  357. }
  358. /* Abbreviated case */
  359. if (strstarts(options->long_name + 3, arg)) {
  360. flags |= OPT_UNSET;
  361. goto is_abbreviated;
  362. }
  363. }
  364. /* abbreviated? */
  365. if (!strncmp(options->long_name, arg, arg_end - arg)) {
  366. is_abbreviated:
  367. if (abbrev_option) {
  368. /*
  369. * If this is abbreviated, it is
  370. * ambiguous. So when there is no
  371. * exact match later, we need to
  372. * error out.
  373. */
  374. ambiguous_option = abbrev_option;
  375. ambiguous_flags = abbrev_flags;
  376. }
  377. if (!(flags & OPT_UNSET) && *arg_end)
  378. p->opt = arg_end + 1;
  379. abbrev_option = options;
  380. abbrev_flags = flags;
  381. continue;
  382. }
  383. /* negated and abbreviated very much? */
  384. if (strstarts("no-", arg)) {
  385. flags |= OPT_UNSET;
  386. goto is_abbreviated;
  387. }
  388. /* negated? */
  389. if (strncmp(arg, "no-", 3))
  390. continue;
  391. flags |= OPT_UNSET;
  392. rest = skip_prefix(arg + 3, options->long_name);
  393. /* abbreviated and negated? */
  394. if (!rest && strstarts(options->long_name, arg + 3))
  395. goto is_abbreviated;
  396. if (!rest)
  397. continue;
  398. }
  399. match:
  400. if (*rest) {
  401. if (*rest != '=')
  402. continue;
  403. p->opt = rest + 1;
  404. }
  405. return get_value(p, options, flags);
  406. }
  407. if (ambiguous_option) {
  408. fprintf(stderr,
  409. " Error: Ambiguous option: %s (could be --%s%s or --%s%s)\n",
  410. arg,
  411. (ambiguous_flags & OPT_UNSET) ? "no-" : "",
  412. ambiguous_option->long_name,
  413. (abbrev_flags & OPT_UNSET) ? "no-" : "",
  414. abbrev_option->long_name);
  415. return -1;
  416. }
  417. if (abbrev_option)
  418. return get_value(p, abbrev_option, abbrev_flags);
  419. if (options->parent) {
  420. options = options->parent;
  421. goto retry;
  422. }
  423. return -2;
  424. }
  425. static void check_typos(const char *arg, const struct option *options)
  426. {
  427. if (strlen(arg) < 3)
  428. return;
  429. if (strstarts(arg, "no-")) {
  430. fprintf(stderr, " Error: did you mean `--%s` (with two dashes ?)\n", arg);
  431. exit(129);
  432. }
  433. for (; options->type != OPTION_END; options++) {
  434. if (!options->long_name)
  435. continue;
  436. if (strstarts(options->long_name, arg)) {
  437. fprintf(stderr, " Error: did you mean `--%s` (with two dashes ?)\n", arg);
  438. exit(129);
  439. }
  440. }
  441. }
  442. static void parse_options_start(struct parse_opt_ctx_t *ctx,
  443. int argc, const char **argv, int flags)
  444. {
  445. memset(ctx, 0, sizeof(*ctx));
  446. ctx->argc = argc - 1;
  447. ctx->argv = argv + 1;
  448. ctx->out = argv;
  449. ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0);
  450. ctx->flags = flags;
  451. if ((flags & PARSE_OPT_KEEP_UNKNOWN) &&
  452. (flags & PARSE_OPT_STOP_AT_NON_OPTION))
  453. die("STOP_AT_NON_OPTION and KEEP_UNKNOWN don't go together");
  454. }
  455. static int usage_with_options_internal(const char * const *,
  456. const struct option *, int,
  457. struct parse_opt_ctx_t *);
  458. static int parse_options_step(struct parse_opt_ctx_t *ctx,
  459. const struct option *options,
  460. const char * const usagestr[])
  461. {
  462. int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
  463. int excl_short_opt = 1;
  464. const char *arg;
  465. /* we must reset ->opt, unknown short option leave it dangling */
  466. ctx->opt = NULL;
  467. for (; ctx->argc; ctx->argc--, ctx->argv++) {
  468. arg = ctx->argv[0];
  469. if (*arg != '-' || !arg[1]) {
  470. if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION)
  471. break;
  472. ctx->out[ctx->cpidx++] = ctx->argv[0];
  473. continue;
  474. }
  475. if (arg[1] != '-') {
  476. ctx->opt = ++arg;
  477. if (internal_help && *ctx->opt == 'h') {
  478. return usage_with_options_internal(usagestr, options, 0, ctx);
  479. }
  480. switch (parse_short_opt(ctx, options)) {
  481. case -1:
  482. return parse_options_usage(usagestr, options, arg, 1);
  483. case -2:
  484. goto unknown;
  485. case -3:
  486. goto exclusive;
  487. default:
  488. break;
  489. }
  490. if (ctx->opt)
  491. check_typos(arg, options);
  492. while (ctx->opt) {
  493. if (internal_help && *ctx->opt == 'h')
  494. return usage_with_options_internal(usagestr, options, 0, ctx);
  495. arg = ctx->opt;
  496. switch (parse_short_opt(ctx, options)) {
  497. case -1:
  498. return parse_options_usage(usagestr, options, arg, 1);
  499. case -2:
  500. /* fake a short option thing to hide the fact that we may have
  501. * started to parse aggregated stuff
  502. *
  503. * This is leaky, too bad.
  504. */
  505. ctx->argv[0] = strdup(ctx->opt - 1);
  506. *(char *)ctx->argv[0] = '-';
  507. goto unknown;
  508. case -3:
  509. goto exclusive;
  510. default:
  511. break;
  512. }
  513. }
  514. continue;
  515. }
  516. if (!arg[2]) { /* "--" */
  517. if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) {
  518. ctx->argc--;
  519. ctx->argv++;
  520. }
  521. break;
  522. }
  523. arg += 2;
  524. if (internal_help && !strcmp(arg, "help-all"))
  525. return usage_with_options_internal(usagestr, options, 1, ctx);
  526. if (internal_help && !strcmp(arg, "help"))
  527. return usage_with_options_internal(usagestr, options, 0, ctx);
  528. if (!strcmp(arg, "list-opts"))
  529. return PARSE_OPT_LIST_OPTS;
  530. if (!strcmp(arg, "list-cmds"))
  531. return PARSE_OPT_LIST_SUBCMDS;
  532. switch (parse_long_opt(ctx, arg, options)) {
  533. case -1:
  534. return parse_options_usage(usagestr, options, arg, 0);
  535. case -2:
  536. goto unknown;
  537. case -3:
  538. excl_short_opt = 0;
  539. goto exclusive;
  540. default:
  541. break;
  542. }
  543. continue;
  544. unknown:
  545. if (!(ctx->flags & PARSE_OPT_KEEP_UNKNOWN))
  546. return PARSE_OPT_UNKNOWN;
  547. ctx->out[ctx->cpidx++] = ctx->argv[0];
  548. ctx->opt = NULL;
  549. }
  550. return PARSE_OPT_DONE;
  551. exclusive:
  552. parse_options_usage(usagestr, options, arg, excl_short_opt);
  553. if ((excl_short_opt && ctx->excl_opt->short_name) ||
  554. ctx->excl_opt->long_name == NULL) {
  555. char opt = ctx->excl_opt->short_name;
  556. parse_options_usage(NULL, options, &opt, 1);
  557. } else {
  558. parse_options_usage(NULL, options, ctx->excl_opt->long_name, 0);
  559. }
  560. return PARSE_OPT_HELP;
  561. }
  562. static int parse_options_end(struct parse_opt_ctx_t *ctx)
  563. {
  564. memmove(ctx->out + ctx->cpidx, ctx->argv, ctx->argc * sizeof(*ctx->out));
  565. ctx->out[ctx->cpidx + ctx->argc] = NULL;
  566. return ctx->cpidx + ctx->argc;
  567. }
  568. int parse_options_subcommand(int argc, const char **argv, const struct option *options,
  569. const char *const subcommands[], const char *usagestr[], int flags)
  570. {
  571. struct parse_opt_ctx_t ctx;
  572. /* build usage string if it's not provided */
  573. if (subcommands && !usagestr[0]) {
  574. char *buf = NULL;
  575. astrcatf(&buf, "%s %s [<options>] {", subcmd_config.exec_name, argv[0]);
  576. for (int i = 0; subcommands[i]; i++) {
  577. if (i)
  578. astrcat(&buf, "|");
  579. astrcat(&buf, subcommands[i]);
  580. }
  581. astrcat(&buf, "}");
  582. usagestr[0] = buf;
  583. }
  584. parse_options_start(&ctx, argc, argv, flags);
  585. switch (parse_options_step(&ctx, options, usagestr)) {
  586. case PARSE_OPT_HELP:
  587. exit(129);
  588. case PARSE_OPT_DONE:
  589. break;
  590. case PARSE_OPT_LIST_OPTS:
  591. while (options->type != OPTION_END) {
  592. if (options->long_name)
  593. printf("--%s ", options->long_name);
  594. options++;
  595. }
  596. putchar('\n');
  597. exit(130);
  598. case PARSE_OPT_LIST_SUBCMDS:
  599. if (subcommands) {
  600. for (int i = 0; subcommands[i]; i++)
  601. printf("%s ", subcommands[i]);
  602. }
  603. putchar('\n');
  604. exit(130);
  605. default: /* PARSE_OPT_UNKNOWN */
  606. if (ctx.argv[0][1] == '-')
  607. astrcatf(&error_buf, "unknown option `%s'",
  608. ctx.argv[0] + 2);
  609. else
  610. astrcatf(&error_buf, "unknown switch `%c'", *ctx.opt);
  611. usage_with_options(usagestr, options);
  612. }
  613. return parse_options_end(&ctx);
  614. }
  615. int parse_options(int argc, const char **argv, const struct option *options,
  616. const char * const usagestr[], int flags)
  617. {
  618. return parse_options_subcommand(argc, argv, options, NULL,
  619. (const char **) usagestr, flags);
  620. }
  621. #define USAGE_OPTS_WIDTH 24
  622. #define USAGE_GAP 2
  623. static void print_option_help(const struct option *opts, int full)
  624. {
  625. size_t pos;
  626. int pad;
  627. if (opts->type == OPTION_GROUP) {
  628. fputc('\n', stderr);
  629. if (*opts->help)
  630. fprintf(stderr, "%s\n", opts->help);
  631. return;
  632. }
  633. if (!full && (opts->flags & PARSE_OPT_HIDDEN))
  634. return;
  635. if (opts->flags & PARSE_OPT_DISABLED)
  636. return;
  637. pos = fprintf(stderr, " ");
  638. if (opts->short_name)
  639. pos += fprintf(stderr, "-%c", opts->short_name);
  640. else
  641. pos += fprintf(stderr, " ");
  642. if (opts->long_name && opts->short_name)
  643. pos += fprintf(stderr, ", ");
  644. if (opts->long_name)
  645. pos += fprintf(stderr, "--%s", opts->long_name);
  646. switch (opts->type) {
  647. case OPTION_ARGUMENT:
  648. break;
  649. case OPTION_LONG:
  650. case OPTION_ULONG:
  651. case OPTION_U64:
  652. case OPTION_INTEGER:
  653. case OPTION_UINTEGER:
  654. if (opts->flags & PARSE_OPT_OPTARG)
  655. if (opts->long_name)
  656. pos += fprintf(stderr, "[=<n>]");
  657. else
  658. pos += fprintf(stderr, "[<n>]");
  659. else
  660. pos += fprintf(stderr, " <n>");
  661. break;
  662. case OPTION_CALLBACK:
  663. if (opts->flags & PARSE_OPT_NOARG)
  664. break;
  665. /* FALLTHROUGH */
  666. case OPTION_STRING:
  667. if (opts->argh) {
  668. if (opts->flags & PARSE_OPT_OPTARG)
  669. if (opts->long_name)
  670. pos += fprintf(stderr, "[=<%s>]", opts->argh);
  671. else
  672. pos += fprintf(stderr, "[<%s>]", opts->argh);
  673. else
  674. pos += fprintf(stderr, " <%s>", opts->argh);
  675. } else {
  676. if (opts->flags & PARSE_OPT_OPTARG)
  677. if (opts->long_name)
  678. pos += fprintf(stderr, "[=...]");
  679. else
  680. pos += fprintf(stderr, "[...]");
  681. else
  682. pos += fprintf(stderr, " ...");
  683. }
  684. break;
  685. default: /* OPTION_{BIT,BOOLEAN,SET_UINT,SET_PTR} */
  686. case OPTION_END:
  687. case OPTION_GROUP:
  688. case OPTION_BIT:
  689. case OPTION_BOOLEAN:
  690. case OPTION_INCR:
  691. case OPTION_SET_UINT:
  692. case OPTION_SET_PTR:
  693. break;
  694. }
  695. if (pos <= USAGE_OPTS_WIDTH)
  696. pad = USAGE_OPTS_WIDTH - pos;
  697. else {
  698. fputc('\n', stderr);
  699. pad = USAGE_OPTS_WIDTH;
  700. }
  701. fprintf(stderr, "%*s%s\n", pad + USAGE_GAP, "", opts->help);
  702. if (opts->flags & PARSE_OPT_NOBUILD)
  703. fprintf(stderr, "%*s(not built-in because %s)\n",
  704. USAGE_OPTS_WIDTH + USAGE_GAP, "",
  705. opts->build_opt);
  706. }
  707. static int option__cmp(const void *va, const void *vb)
  708. {
  709. const struct option *a = va, *b = vb;
  710. int sa = tolower(a->short_name), sb = tolower(b->short_name), ret;
  711. if (sa == 0)
  712. sa = 'z' + 1;
  713. if (sb == 0)
  714. sb = 'z' + 1;
  715. ret = sa - sb;
  716. if (ret == 0) {
  717. const char *la = a->long_name ?: "",
  718. *lb = b->long_name ?: "";
  719. ret = strcmp(la, lb);
  720. }
  721. return ret;
  722. }
  723. static struct option *options__order(const struct option *opts)
  724. {
  725. int nr_opts = 0, nr_group = 0, len;
  726. const struct option *o = opts;
  727. struct option *opt, *ordered, *group;
  728. for (o = opts; o->type != OPTION_END; o++)
  729. ++nr_opts;
  730. len = sizeof(*o) * (nr_opts + 1);
  731. ordered = malloc(len);
  732. if (!ordered)
  733. goto out;
  734. memcpy(ordered, opts, len);
  735. /* sort each option group individually */
  736. for (opt = group = ordered; opt->type != OPTION_END; opt++) {
  737. if (opt->type == OPTION_GROUP) {
  738. qsort(group, nr_group, sizeof(*opt), option__cmp);
  739. group = opt + 1;
  740. nr_group = 0;
  741. continue;
  742. }
  743. nr_group++;
  744. }
  745. qsort(group, nr_group, sizeof(*opt), option__cmp);
  746. out:
  747. return ordered;
  748. }
  749. static bool option__in_argv(const struct option *opt, const struct parse_opt_ctx_t *ctx)
  750. {
  751. int i;
  752. for (i = 1; i < ctx->argc; ++i) {
  753. const char *arg = ctx->argv[i];
  754. if (arg[0] != '-') {
  755. if (arg[1] == '\0') {
  756. if (arg[0] == opt->short_name)
  757. return true;
  758. continue;
  759. }
  760. if (opt->long_name && strcmp(opt->long_name, arg) == 0)
  761. return true;
  762. if (opt->help && strcasestr(opt->help, arg) != NULL)
  763. return true;
  764. continue;
  765. }
  766. if (arg[1] == opt->short_name ||
  767. (arg[1] == '-' && opt->long_name && strcmp(opt->long_name, arg + 2) == 0))
  768. return true;
  769. }
  770. return false;
  771. }
  772. static int usage_with_options_internal(const char * const *usagestr,
  773. const struct option *opts, int full,
  774. struct parse_opt_ctx_t *ctx)
  775. {
  776. struct option *ordered;
  777. if (!usagestr)
  778. return PARSE_OPT_HELP;
  779. setup_pager();
  780. if (error_buf) {
  781. fprintf(stderr, " Error: %s\n", error_buf);
  782. zfree(&error_buf);
  783. }
  784. fprintf(stderr, "\n Usage: %s\n", *usagestr++);
  785. while (*usagestr && **usagestr)
  786. fprintf(stderr, " or: %s\n", *usagestr++);
  787. while (*usagestr) {
  788. fprintf(stderr, "%s%s\n",
  789. **usagestr ? " " : "",
  790. *usagestr);
  791. usagestr++;
  792. }
  793. if (opts->type != OPTION_GROUP)
  794. fputc('\n', stderr);
  795. ordered = options__order(opts);
  796. if (ordered)
  797. opts = ordered;
  798. for ( ; opts->type != OPTION_END; opts++) {
  799. if (ctx && ctx->argc > 1 && !option__in_argv(opts, ctx))
  800. continue;
  801. print_option_help(opts, full);
  802. }
  803. fputc('\n', stderr);
  804. free(ordered);
  805. return PARSE_OPT_HELP;
  806. }
  807. void usage_with_options(const char * const *usagestr,
  808. const struct option *opts)
  809. {
  810. usage_with_options_internal(usagestr, opts, 0, NULL);
  811. exit(129);
  812. }
  813. void usage_with_options_msg(const char * const *usagestr,
  814. const struct option *opts, const char *fmt, ...)
  815. {
  816. va_list ap;
  817. char *tmp = error_buf;
  818. va_start(ap, fmt);
  819. if (vasprintf(&error_buf, fmt, ap) == -1)
  820. die("vasprintf failed");
  821. va_end(ap);
  822. free(tmp);
  823. usage_with_options_internal(usagestr, opts, 0, NULL);
  824. exit(129);
  825. }
  826. int parse_options_usage(const char * const *usagestr,
  827. const struct option *opts,
  828. const char *optstr, bool short_opt)
  829. {
  830. if (!usagestr)
  831. goto opt;
  832. fprintf(stderr, "\n Usage: %s\n", *usagestr++);
  833. while (*usagestr && **usagestr)
  834. fprintf(stderr, " or: %s\n", *usagestr++);
  835. while (*usagestr) {
  836. fprintf(stderr, "%s%s\n",
  837. **usagestr ? " " : "",
  838. *usagestr);
  839. usagestr++;
  840. }
  841. fputc('\n', stderr);
  842. opt:
  843. for ( ; opts->type != OPTION_END; opts++) {
  844. if (short_opt) {
  845. if (opts->short_name == *optstr) {
  846. print_option_help(opts, 0);
  847. break;
  848. }
  849. continue;
  850. }
  851. if (opts->long_name == NULL)
  852. continue;
  853. if (strstarts(opts->long_name, optstr))
  854. print_option_help(opts, 0);
  855. if (strstarts("no-", optstr) &&
  856. strstarts(opts->long_name, optstr + 3))
  857. print_option_help(opts, 0);
  858. }
  859. return PARSE_OPT_HELP;
  860. }
  861. int parse_opt_verbosity_cb(const struct option *opt,
  862. const char *arg __maybe_unused,
  863. int unset)
  864. {
  865. int *target = opt->value;
  866. if (unset)
  867. /* --no-quiet, --no-verbose */
  868. *target = 0;
  869. else if (opt->short_name == 'v') {
  870. if (*target >= 0)
  871. (*target)++;
  872. else
  873. *target = 1;
  874. } else {
  875. if (*target <= 0)
  876. (*target)--;
  877. else
  878. *target = -1;
  879. }
  880. return 0;
  881. }
  882. static struct option *
  883. find_option(struct option *opts, int shortopt, const char *longopt)
  884. {
  885. for (; opts->type != OPTION_END; opts++) {
  886. if ((shortopt && opts->short_name == shortopt) ||
  887. (opts->long_name && longopt &&
  888. !strcmp(opts->long_name, longopt)))
  889. return opts;
  890. }
  891. return NULL;
  892. }
  893. void set_option_flag(struct option *opts, int shortopt, const char *longopt,
  894. int flag)
  895. {
  896. struct option *opt = find_option(opts, shortopt, longopt);
  897. if (opt)
  898. opt->flags |= flag;
  899. return;
  900. }
  901. void set_option_nobuild(struct option *opts, int shortopt,
  902. const char *longopt,
  903. const char *build_opt,
  904. bool can_skip)
  905. {
  906. struct option *opt = find_option(opts, shortopt, longopt);
  907. if (!opt)
  908. return;
  909. opt->flags |= PARSE_OPT_NOBUILD;
  910. opt->flags |= can_skip ? PARSE_OPT_CANSKIP : 0;
  911. opt->build_opt = build_opt;
  912. }