argp-help.c 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894
  1. /* Hierarchial argument parsing help output
  2. Copyright (C) 1995-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Written by Miles Bader <miles@gnu.ai.mit.edu>.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public
  7. License as published by the Free Software Foundation; either
  8. version 2.1 of the License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; if not, see
  15. <http://www.gnu.org/licenses/>. */
  16. #ifndef _GNU_SOURCE
  17. # define _GNU_SOURCE 1
  18. #endif
  19. #ifdef HAVE_CONFIG_H
  20. #include <config.h>
  21. #endif
  22. /* AIX requires this to be the first thing in the file. */
  23. #ifndef __GNUC__
  24. # if HAVE_ALLOCA_H || defined _LIBC
  25. # include <alloca.h>
  26. # else
  27. # ifdef _AIX
  28. #pragma alloca
  29. # else
  30. # ifndef alloca /* predefined by HP cc +Olibcalls */
  31. char *alloca ();
  32. # endif
  33. # endif
  34. # endif
  35. #endif
  36. #include <stdbool.h>
  37. #include <stddef.h>
  38. #include <stdlib.h>
  39. #include <string.h>
  40. #include <assert.h>
  41. #include <stdarg.h>
  42. #include <ctype.h>
  43. #include <limits.h>
  44. #ifdef _LIBC
  45. # include <../libio/libioP.h>
  46. # include <wchar.h>
  47. #endif
  48. #ifndef _
  49. /* This is for other GNU distributions with internationalized messages. */
  50. # if defined HAVE_LIBINTL_H || defined _LIBC
  51. # include <libintl.h>
  52. # ifdef _LIBC
  53. # undef dgettext
  54. # define dgettext(domain, msgid) \
  55. __dcgettext (domain, msgid, LC_MESSAGES)
  56. # endif
  57. # else
  58. # define dgettext(domain, msgid) (msgid)
  59. # endif
  60. #endif
  61. #ifndef _LIBC
  62. # if HAVE_STRERROR_R
  63. # if !HAVE_DECL_STRERROR_R
  64. char *strerror_r (int errnum, char *buf, size_t buflen);
  65. # endif
  66. # else
  67. # if !HAVE_DECL_STRERROR
  68. char *strerror (int errnum);
  69. # endif
  70. # endif
  71. #endif
  72. #include <argp.h>
  73. #include <argp-fmtstream.h>
  74. #include "argp-namefrob.h"
  75. #ifndef SIZE_MAX
  76. # define SIZE_MAX ((size_t) -1)
  77. #endif
  78. /* User-selectable (using an environment variable) formatting parameters.
  79. These may be specified in an environment variable called `ARGP_HELP_FMT',
  80. with a contents like: VAR1=VAL1,VAR2=VAL2,BOOLVAR2,no-BOOLVAR2
  81. Where VALn must be a positive integer. The list of variables is in the
  82. UPARAM_NAMES vector, below. */
  83. /* Default parameters. */
  84. #define DUP_ARGS 0 /* True if option argument can be duplicated. */
  85. #define DUP_ARGS_NOTE 1 /* True to print a note about duplicate args. */
  86. #define SHORT_OPT_COL 2 /* column in which short options start */
  87. #define LONG_OPT_COL 6 /* column in which long options start */
  88. #define DOC_OPT_COL 2 /* column in which doc options start */
  89. #define OPT_DOC_COL 29 /* column in which option text starts */
  90. #define HEADER_COL 1 /* column in which group headers are printed */
  91. #define USAGE_INDENT 12 /* indentation of wrapped usage lines */
  92. #define RMARGIN 79 /* right margin used for wrapping */
  93. /* User-selectable (using an environment variable) formatting parameters.
  94. They must all be of type `int' for the parsing code to work. */
  95. struct uparams
  96. {
  97. /* If true, arguments for an option are shown with both short and long
  98. options, even when a given option has both, e.g. `-x ARG, --longx=ARG'.
  99. If false, then if an option has both, the argument is only shown with
  100. the long one, e.g., `-x, --longx=ARG', and a message indicating that
  101. this really means both is printed below the options. */
  102. int dup_args;
  103. /* This is true if when DUP_ARGS is false, and some duplicate arguments have
  104. been suppressed, an explanatory message should be printed. */
  105. int dup_args_note;
  106. /* Various output columns. */
  107. int short_opt_col;
  108. int long_opt_col;
  109. int doc_opt_col;
  110. int opt_doc_col;
  111. int header_col;
  112. int usage_indent;
  113. int rmargin;
  114. };
  115. /* This is a global variable, as user options are only ever read once. */
  116. static struct uparams uparams = {
  117. DUP_ARGS, DUP_ARGS_NOTE,
  118. SHORT_OPT_COL, LONG_OPT_COL, DOC_OPT_COL, OPT_DOC_COL, HEADER_COL,
  119. USAGE_INDENT, RMARGIN
  120. };
  121. /* A particular uparam, and what the user name is. */
  122. struct uparam_name
  123. {
  124. const char name[14]; /* User name. */
  125. bool is_bool; /* Whether it's `boolean'. */
  126. uint8_t uparams_offs; /* Location of the (int) field in UPARAMS. */
  127. };
  128. /* The name-field mappings we know about. */
  129. static const struct uparam_name uparam_names[] =
  130. {
  131. { "dup-args", true, offsetof (struct uparams, dup_args) },
  132. { "dup-args-note", true, offsetof (struct uparams, dup_args_note) },
  133. { "short-opt-col", false, offsetof (struct uparams, short_opt_col) },
  134. { "long-opt-col", false, offsetof (struct uparams, long_opt_col) },
  135. { "doc-opt-col", false, offsetof (struct uparams, doc_opt_col) },
  136. { "opt-doc-col", false, offsetof (struct uparams, opt_doc_col) },
  137. { "header-col", false, offsetof (struct uparams, header_col) },
  138. { "usage-indent", false, offsetof (struct uparams, usage_indent) },
  139. { "rmargin", false, offsetof (struct uparams, rmargin) }
  140. };
  141. #define nuparam_names (sizeof (uparam_names) / sizeof (uparam_names[0]))
  142. /* Read user options from the environment, and fill in UPARAMS appropriately. */
  143. static void
  144. fill_in_uparams (const struct argp_state *state)
  145. {
  146. const char *var = getenv ("ARGP_HELP_FMT");
  147. #define SKIPWS(p) do { while (isspace (*p)) p++; } while (0);
  148. if (var)
  149. /* Parse var. */
  150. while (*var)
  151. {
  152. SKIPWS (var);
  153. if (isalpha (*var))
  154. {
  155. size_t var_len;
  156. const struct uparam_name *un;
  157. int unspec = 0, val = 0;
  158. const char *arg = var;
  159. while (isalnum (*arg) || *arg == '-' || *arg == '_')
  160. arg++;
  161. var_len = arg - var;
  162. SKIPWS (arg);
  163. if (*arg == '\0' || *arg == ',')
  164. unspec = 1;
  165. else if (*arg == '=')
  166. {
  167. arg++;
  168. SKIPWS (arg);
  169. }
  170. if (unspec)
  171. {
  172. if (var[0] == 'n' && var[1] == 'o' && var[2] == '-')
  173. {
  174. val = 0;
  175. var += 3;
  176. var_len -= 3;
  177. }
  178. else
  179. val = 1;
  180. }
  181. else if (isdigit (*arg))
  182. {
  183. val = atoi (arg);
  184. while (isdigit (*arg))
  185. arg++;
  186. SKIPWS (arg);
  187. }
  188. un = uparam_names;
  189. size_t u;
  190. for (u = 0; u < nuparam_names; ++un, ++u)
  191. if (strlen (un->name) == var_len
  192. && strncmp (var, un->name, var_len) == 0)
  193. {
  194. if (unspec && !un->is_bool)
  195. __argp_failure (state, 0, 0,
  196. dgettext (state == NULL ? NULL
  197. : state->root_argp->argp_domain,
  198. "\
  199. %.*s: ARGP_HELP_FMT parameter requires a value"),
  200. (int) var_len, var);
  201. else
  202. *(int *)((char *)&uparams + un->uparams_offs) = val;
  203. break;
  204. }
  205. if (u == nuparam_names)
  206. __argp_failure (state, 0, 0,
  207. dgettext (state == NULL ? NULL
  208. : state->root_argp->argp_domain, "\
  209. %.*s: Unknown ARGP_HELP_FMT parameter"),
  210. (int) var_len, var);
  211. var = arg;
  212. if (*var == ',')
  213. var++;
  214. }
  215. else if (*var)
  216. {
  217. __argp_failure (state, 0, 0,
  218. dgettext (state == NULL ? NULL
  219. : state->root_argp->argp_domain,
  220. "Garbage in ARGP_HELP_FMT: %s"), var);
  221. break;
  222. }
  223. }
  224. }
  225. /* Returns true if OPT hasn't been marked invisible. Visibility only affects
  226. whether OPT is displayed or used in sorting, not option shadowing. */
  227. #define ovisible(opt) (! ((opt)->flags & OPTION_HIDDEN))
  228. /* Returns true if OPT is an alias for an earlier option. */
  229. #define oalias(opt) ((opt)->flags & OPTION_ALIAS)
  230. /* Returns true if OPT is an documentation-only entry. */
  231. #define odoc(opt) ((opt)->flags & OPTION_DOC)
  232. /* Returns true if OPT is the end-of-list marker for a list of options. */
  233. #define oend(opt) __option_is_end (opt)
  234. /* Returns true if OPT has a short option. */
  235. #define oshort(opt) __option_is_short (opt)
  236. /*
  237. The help format for a particular option is like:
  238. -xARG, -yARG, --long1=ARG, --long2=ARG Documentation...
  239. Where ARG will be omitted if there's no argument, for this option, or
  240. will be surrounded by "[" and "]" appropriately if the argument is
  241. optional. The documentation string is word-wrapped appropriately, and if
  242. the list of options is long enough, it will be started on a separate line.
  243. If there are no short options for a given option, the first long option is
  244. indented slightly in a way that's supposed to make most long options appear
  245. to be in a separate column.
  246. For example, the following output (from ps):
  247. -p PID, --pid=PID List the process PID
  248. --pgrp=PGRP List processes in the process group PGRP
  249. -P, -x, --no-parent Include processes without parents
  250. -Q, --all-fields Don't elide unusable fields (normally if there's
  251. some reason ps can't print a field for any
  252. process, it's removed from the output entirely)
  253. -r, --reverse, --gratuitously-long-reverse-option
  254. Reverse the order of any sort
  255. --session[=SID] Add the processes from the session SID (which
  256. defaults to the sid of the current process)
  257. Here are some more options:
  258. -f ZOT, --foonly=ZOT Glork a foonly
  259. -z, --zaza Snit a zar
  260. -?, --help Give this help list
  261. --usage Give a short usage message
  262. -V, --version Print program version
  263. The struct argp_option array for the above could look like:
  264. {
  265. {"pid", 'p', "PID", 0, "List the process PID"},
  266. {"pgrp", OPT_PGRP, "PGRP", 0, "List processes in the process group PGRP"},
  267. {"no-parent", 'P', 0, 0, "Include processes without parents"},
  268. {0, 'x', 0, OPTION_ALIAS},
  269. {"all-fields",'Q', 0, 0, "Don't elide unusable fields (normally"
  270. " if there's some reason ps can't"
  271. " print a field for any process, it's"
  272. " removed from the output entirely)" },
  273. {"reverse", 'r', 0, 0, "Reverse the order of any sort"},
  274. {"gratuitously-long-reverse-option", 0, 0, OPTION_ALIAS},
  275. {"session", OPT_SESS, "SID", OPTION_ARG_OPTIONAL,
  276. "Add the processes from the session"
  277. " SID (which defaults to the sid of"
  278. " the current process)" },
  279. {0,0,0,0, "Here are some more options:"},
  280. {"foonly", 'f', "ZOT", 0, "Glork a foonly"},
  281. {"zaza", 'z', 0, 0, "Snit a zar"},
  282. {0}
  283. }
  284. Note that the last three options are automatically supplied by argp_parse,
  285. unless you tell it not to with ARGP_NO_HELP.
  286. */
  287. /* Returns true if CH occurs between BEG and END. */
  288. static int
  289. find_char (char ch, char *beg, char *end)
  290. {
  291. while (beg < end)
  292. if (*beg == ch)
  293. return 1;
  294. else
  295. beg++;
  296. return 0;
  297. }
  298. struct hol_cluster; /* fwd decl */
  299. struct hol_entry
  300. {
  301. /* First option. */
  302. const struct argp_option *opt;
  303. /* Number of options (including aliases). */
  304. unsigned num;
  305. /* A pointers into the HOL's short_options field, to the first short option
  306. letter for this entry. The order of the characters following this point
  307. corresponds to the order of options pointed to by OPT, and there are at
  308. most NUM. A short option recorded in an option following OPT is only
  309. valid if it occurs in the right place in SHORT_OPTIONS (otherwise it's
  310. probably been shadowed by some other entry). */
  311. char *short_options;
  312. /* Entries are sorted by their group first, in the order:
  313. 1, 2, ..., n, 0, -m, ..., -2, -1
  314. and then alphabetically within each group. The default is 0. */
  315. int group;
  316. /* The cluster of options this entry belongs to, or 0 if none. */
  317. struct hol_cluster *cluster;
  318. /* The argp from which this option came. */
  319. const struct argp *argp;
  320. };
  321. /* A cluster of entries to reflect the argp tree structure. */
  322. struct hol_cluster
  323. {
  324. /* A descriptive header printed before options in this cluster. */
  325. const char *header;
  326. /* Used to order clusters within the same group with the same parent,
  327. according to the order in which they occurred in the parent argp's child
  328. list. */
  329. int index;
  330. /* How to sort this cluster with respect to options and other clusters at the
  331. same depth (clusters always follow options in the same group). */
  332. int group;
  333. /* The cluster to which this cluster belongs, or 0 if it's at the base
  334. level. */
  335. struct hol_cluster *parent;
  336. /* The argp from which this cluster is (eventually) derived. */
  337. const struct argp *argp;
  338. /* The distance this cluster is from the root. */
  339. int depth;
  340. /* Clusters in a given hol are kept in a linked list, to make freeing them
  341. possible. */
  342. struct hol_cluster *next;
  343. };
  344. /* A list of options for help. */
  345. struct hol
  346. {
  347. /* An array of hol_entry's. */
  348. struct hol_entry *entries;
  349. /* The number of entries in this hol. If this field is zero, the others
  350. are undefined. */
  351. unsigned num_entries;
  352. /* A string containing all short options in this HOL. Each entry contains
  353. pointers into this string, so the order can't be messed with blindly. */
  354. char *short_options;
  355. /* Clusters of entries in this hol. */
  356. struct hol_cluster *clusters;
  357. };
  358. /* Create a struct hol from the options in ARGP. CLUSTER is the
  359. hol_cluster in which these entries occur, or 0, if at the root. */
  360. static struct hol *
  361. make_hol (const struct argp *argp, struct hol_cluster *cluster)
  362. {
  363. char *so;
  364. const struct argp_option *o;
  365. const struct argp_option *opts = argp->options;
  366. struct hol_entry *entry;
  367. unsigned num_short_options = 0;
  368. struct hol *hol = malloc (sizeof (struct hol));
  369. assert (hol);
  370. hol->num_entries = 0;
  371. hol->clusters = 0;
  372. if (opts)
  373. {
  374. int cur_group = 0;
  375. /* The first option must not be an alias. */
  376. assert (! oalias (opts));
  377. /* Calculate the space needed. */
  378. for (o = opts; ! oend (o); o++)
  379. {
  380. if (! oalias (o))
  381. hol->num_entries++;
  382. if (oshort (o))
  383. num_short_options++; /* This is an upper bound. */
  384. }
  385. hol->entries = malloc (sizeof (struct hol_entry) * hol->num_entries);
  386. hol->short_options = malloc (num_short_options + 1);
  387. assert (hol->entries && hol->short_options);
  388. #if SIZE_MAX <= UINT_MAX
  389. assert (hol->num_entries <= SIZE_MAX / sizeof (struct hol_entry));
  390. #endif
  391. /* Fill in the entries. */
  392. so = hol->short_options;
  393. for (o = opts, entry = hol->entries; ! oend (o); entry++)
  394. {
  395. entry->opt = o;
  396. entry->num = 0;
  397. entry->short_options = so;
  398. entry->group = cur_group =
  399. o->group
  400. ? o->group
  401. : ((!o->name && !o->key)
  402. ? cur_group + 1
  403. : cur_group);
  404. entry->cluster = cluster;
  405. entry->argp = argp;
  406. do
  407. {
  408. entry->num++;
  409. if (oshort (o) && ! find_char (o->key, hol->short_options, so))
  410. /* O has a valid short option which hasn't already been used.*/
  411. *so++ = o->key;
  412. o++;
  413. }
  414. while (! oend (o) && oalias (o));
  415. }
  416. *so = '\0'; /* null terminated so we can find the length */
  417. }
  418. return hol;
  419. }
  420. /* Add a new cluster to HOL, with the given GROUP and HEADER (taken from the
  421. associated argp child list entry), INDEX, and PARENT, and return a pointer
  422. to it. ARGP is the argp that this cluster results from. */
  423. static struct hol_cluster *
  424. hol_add_cluster (struct hol *hol, int group, const char *header, int index,
  425. struct hol_cluster *parent, const struct argp *argp)
  426. {
  427. struct hol_cluster *cl = malloc (sizeof (struct hol_cluster));
  428. if (cl)
  429. {
  430. cl->group = group;
  431. cl->header = header;
  432. cl->index = index;
  433. cl->parent = parent;
  434. cl->argp = argp;
  435. cl->depth = parent ? parent->depth + 1 : 0;
  436. cl->next = hol->clusters;
  437. hol->clusters = cl;
  438. }
  439. return cl;
  440. }
  441. /* Free HOL and any resources it uses. */
  442. static void
  443. hol_free (struct hol *hol)
  444. {
  445. struct hol_cluster *cl = hol->clusters;
  446. while (cl)
  447. {
  448. struct hol_cluster *next = cl->next;
  449. free (cl);
  450. cl = next;
  451. }
  452. if (hol->num_entries > 0)
  453. {
  454. free (hol->entries);
  455. free (hol->short_options);
  456. }
  457. free (hol);
  458. }
  459. static int
  460. hol_entry_short_iterate (const struct hol_entry *entry,
  461. int (*func)(const struct argp_option *opt,
  462. const struct argp_option *real,
  463. const char *domain, void *cookie),
  464. const char *domain, void *cookie)
  465. {
  466. unsigned nopts;
  467. int val = 0;
  468. const struct argp_option *opt, *real = entry->opt;
  469. char *so = entry->short_options;
  470. for (opt = real, nopts = entry->num; nopts > 0 && !val; opt++, nopts--)
  471. if (oshort (opt) && *so == opt->key)
  472. {
  473. if (!oalias (opt))
  474. real = opt;
  475. if (ovisible (opt))
  476. val = (*func)(opt, real, domain, cookie);
  477. so++;
  478. }
  479. return val;
  480. }
  481. static inline int
  482. __attribute__ ((always_inline))
  483. hol_entry_long_iterate (const struct hol_entry *entry,
  484. int (*func)(const struct argp_option *opt,
  485. const struct argp_option *real,
  486. const char *domain, void *cookie),
  487. const char *domain, void *cookie)
  488. {
  489. unsigned nopts;
  490. int val = 0;
  491. const struct argp_option *opt, *real = entry->opt;
  492. for (opt = real, nopts = entry->num; nopts > 0 && !val; opt++, nopts--)
  493. if (opt->name)
  494. {
  495. if (!oalias (opt))
  496. real = opt;
  497. if (ovisible (opt))
  498. val = (*func)(opt, real, domain, cookie);
  499. }
  500. return val;
  501. }
  502. /* Iterator that returns true for the first short option. */
  503. static inline int
  504. until_short (const struct argp_option *opt, const struct argp_option *real,
  505. const char *domain, void *cookie)
  506. {
  507. return oshort (opt) ? opt->key : 0;
  508. }
  509. /* Returns the first valid short option in ENTRY, or 0 if there is none. */
  510. static char
  511. hol_entry_first_short (const struct hol_entry *entry)
  512. {
  513. return hol_entry_short_iterate (entry, until_short,
  514. entry->argp->argp_domain, 0);
  515. }
  516. /* Returns the first valid long option in ENTRY, or 0 if there is none. */
  517. static const char *
  518. hol_entry_first_long (const struct hol_entry *entry)
  519. {
  520. const struct argp_option *opt;
  521. unsigned num;
  522. for (opt = entry->opt, num = entry->num; num > 0; opt++, num--)
  523. if (opt->name && ovisible (opt))
  524. return opt->name;
  525. return 0;
  526. }
  527. /* Returns the entry in HOL with the long option name NAME, or 0 if there is
  528. none. */
  529. static struct hol_entry *
  530. hol_find_entry (struct hol *hol, const char *name)
  531. {
  532. struct hol_entry *entry = hol->entries;
  533. unsigned num_entries = hol->num_entries;
  534. while (num_entries-- > 0)
  535. {
  536. const struct argp_option *opt = entry->opt;
  537. unsigned num_opts = entry->num;
  538. while (num_opts-- > 0)
  539. if (opt->name && ovisible (opt) && strcmp (opt->name, name) == 0)
  540. return entry;
  541. else
  542. opt++;
  543. entry++;
  544. }
  545. return 0;
  546. }
  547. /* If an entry with the long option NAME occurs in HOL, set it's special
  548. sort position to GROUP. */
  549. static void
  550. hol_set_group (struct hol *hol, const char *name, int group)
  551. {
  552. struct hol_entry *entry = hol_find_entry (hol, name);
  553. if (entry)
  554. entry->group = group;
  555. }
  556. /* Order by group: 0, 1, 2, ..., n, -m, ..., -2, -1.
  557. EQ is what to return if GROUP1 and GROUP2 are the same. */
  558. static int
  559. group_cmp (int group1, int group2, int eq)
  560. {
  561. if (group1 == group2)
  562. return eq;
  563. else if ((group1 < 0 && group2 < 0) || (group1 >= 0 && group2 >= 0))
  564. return group1 - group2;
  565. else
  566. return group2 - group1;
  567. }
  568. /* Compare clusters CL1 & CL2 by the order that they should appear in
  569. output. */
  570. static int
  571. hol_cluster_cmp (const struct hol_cluster *cl1, const struct hol_cluster *cl2)
  572. {
  573. /* If one cluster is deeper than the other, use its ancestor at the same
  574. level, so that finding the common ancestor is straightforward. */
  575. while (cl1->depth > cl2->depth)
  576. cl1 = cl1->parent;
  577. while (cl2->depth > cl1->depth)
  578. cl2 = cl2->parent;
  579. /* Now reduce both clusters to their ancestors at the point where both have
  580. a common parent; these can be directly compared. */
  581. while (cl1->parent != cl2->parent)
  582. cl1 = cl1->parent, cl2 = cl2->parent;
  583. return group_cmp (cl1->group, cl2->group, cl2->index - cl1->index);
  584. }
  585. /* Return the ancestor of CL that's just below the root (i.e., has a parent
  586. of 0). */
  587. static struct hol_cluster *
  588. hol_cluster_base (struct hol_cluster *cl)
  589. {
  590. while (cl->parent)
  591. cl = cl->parent;
  592. return cl;
  593. }
  594. /* Return true if CL1 is a child of CL2. */
  595. static int
  596. hol_cluster_is_child (const struct hol_cluster *cl1,
  597. const struct hol_cluster *cl2)
  598. {
  599. while (cl1 && cl1 != cl2)
  600. cl1 = cl1->parent;
  601. return cl1 == cl2;
  602. }
  603. /* Given the name of a OPTION_DOC option, modifies NAME to start at the tail
  604. that should be used for comparisons, and returns true iff it should be
  605. treated as a non-option. */
  606. static int
  607. canon_doc_option (const char **name)
  608. {
  609. int non_opt;
  610. /* Skip initial whitespace. */
  611. while (isspace (**name))
  612. (*name)++;
  613. /* Decide whether this looks like an option (leading `-') or not. */
  614. non_opt = (**name != '-');
  615. /* Skip until part of name used for sorting. */
  616. while (**name && !isalnum (**name))
  617. (*name)++;
  618. return non_opt;
  619. }
  620. /* Order ENTRY1 & ENTRY2 by the order which they should appear in a help
  621. listing. */
  622. static int
  623. hol_entry_cmp (const struct hol_entry *entry1,
  624. const struct hol_entry *entry2)
  625. {
  626. /* The group numbers by which the entries should be ordered; if either is
  627. in a cluster, then this is just the group within the cluster. */
  628. int group1 = entry1->group, group2 = entry2->group;
  629. if (entry1->cluster != entry2->cluster)
  630. {
  631. /* The entries are not within the same cluster, so we can't compare them
  632. directly, we have to use the appropriate clustering level too. */
  633. if (! entry1->cluster)
  634. /* ENTRY1 is at the `base level', not in a cluster, so we have to
  635. compare it's group number with that of the base cluster in which
  636. ENTRY2 resides. Note that if they're in the same group, the
  637. clustered option always comes last. */
  638. return group_cmp (group1, hol_cluster_base (entry2->cluster)->group, -1);
  639. else if (! entry2->cluster)
  640. /* Likewise, but ENTRY2's not in a cluster. */
  641. return group_cmp (hol_cluster_base (entry1->cluster)->group, group2, 1);
  642. else
  643. /* Both entries are in clusters, we can just compare the clusters. */
  644. return hol_cluster_cmp (entry1->cluster, entry2->cluster);
  645. }
  646. else if (group1 == group2)
  647. /* The entries are both in the same cluster and group, so compare them
  648. alphabetically. */
  649. {
  650. int short1 = hol_entry_first_short (entry1);
  651. int short2 = hol_entry_first_short (entry2);
  652. int doc1 = odoc (entry1->opt);
  653. int doc2 = odoc (entry2->opt);
  654. const char *long1 = hol_entry_first_long (entry1);
  655. const char *long2 = hol_entry_first_long (entry2);
  656. if (doc1)
  657. doc1 = long1 != NULL && canon_doc_option (&long1);
  658. if (doc2)
  659. doc2 = long2 != NULL && canon_doc_option (&long2);
  660. if (doc1 != doc2)
  661. /* `documentation' options always follow normal options (or
  662. documentation options that *look* like normal options). */
  663. return doc1 - doc2;
  664. else if (!short1 && !short2 && long1 && long2)
  665. /* Only long options. */
  666. return __strcasecmp (long1, long2);
  667. else
  668. /* Compare short/short, long/short, short/long, using the first
  669. character of long options. Entries without *any* valid
  670. options (such as options with OPTION_HIDDEN set) will be put
  671. first, but as they're not displayed, it doesn't matter where
  672. they are. */
  673. {
  674. char first1 = short1 ? short1 : long1 ? *long1 : 0;
  675. char first2 = short2 ? short2 : long2 ? *long2 : 0;
  676. #ifdef _tolower
  677. int lower_cmp = _tolower (first1) - _tolower (first2);
  678. #else
  679. int lower_cmp = tolower (first1) - tolower (first2);
  680. #endif
  681. /* Compare ignoring case, except when the options are both the
  682. same letter, in which case lower-case always comes first. */
  683. return lower_cmp ? lower_cmp : first2 - first1;
  684. }
  685. }
  686. else
  687. /* Within the same cluster, but not the same group, so just compare
  688. groups. */
  689. return group_cmp (group1, group2, 0);
  690. }
  691. /* Version of hol_entry_cmp with correct signature for qsort. */
  692. static int
  693. hol_entry_qcmp (const void *entry1_v, const void *entry2_v)
  694. {
  695. return hol_entry_cmp (entry1_v, entry2_v);
  696. }
  697. /* Sort HOL by group and alphabetically by option name (with short options
  698. taking precedence over long). Since the sorting is for display purposes
  699. only, the shadowing of options isn't effected. */
  700. static void
  701. hol_sort (struct hol *hol)
  702. {
  703. if (hol->num_entries > 0)
  704. qsort (hol->entries, hol->num_entries, sizeof (struct hol_entry),
  705. hol_entry_qcmp);
  706. }
  707. /* Append MORE to HOL, destroying MORE in the process. Options in HOL shadow
  708. any in MORE with the same name. */
  709. static void
  710. hol_append (struct hol *hol, struct hol *more)
  711. {
  712. struct hol_cluster **cl_end = &hol->clusters;
  713. /* Steal MORE's cluster list, and add it to the end of HOL's. */
  714. while (*cl_end)
  715. cl_end = &(*cl_end)->next;
  716. *cl_end = more->clusters;
  717. more->clusters = 0;
  718. /* Merge entries. */
  719. if (more->num_entries > 0)
  720. {
  721. if (hol->num_entries == 0)
  722. {
  723. hol->num_entries = more->num_entries;
  724. hol->entries = more->entries;
  725. hol->short_options = more->short_options;
  726. more->num_entries = 0; /* Mark MORE's fields as invalid. */
  727. }
  728. else
  729. /* Append the entries in MORE to those in HOL, taking care to only add
  730. non-shadowed SHORT_OPTIONS values. */
  731. {
  732. unsigned left;
  733. char *so, *more_so;
  734. struct hol_entry *e;
  735. unsigned num_entries = hol->num_entries + more->num_entries;
  736. struct hol_entry *entries =
  737. malloc (num_entries * sizeof (struct hol_entry));
  738. unsigned hol_so_len = strlen (hol->short_options);
  739. char *short_options =
  740. malloc (hol_so_len + strlen (more->short_options) + 1);
  741. assert (entries && short_options);
  742. #if SIZE_MAX <= UINT_MAX
  743. assert (num_entries <= SIZE_MAX / sizeof (struct hol_entry));
  744. #endif
  745. __mempcpy (__mempcpy (entries, hol->entries,
  746. hol->num_entries * sizeof (struct hol_entry)),
  747. more->entries,
  748. more->num_entries * sizeof (struct hol_entry));
  749. __mempcpy (short_options, hol->short_options, hol_so_len);
  750. /* Fix up the short options pointers from HOL. */
  751. for (e = entries, left = hol->num_entries; left > 0; e++, left--)
  752. e->short_options += (short_options - hol->short_options);
  753. /* Now add the short options from MORE, fixing up its entries
  754. too. */
  755. so = short_options + hol_so_len;
  756. more_so = more->short_options;
  757. for (left = more->num_entries; left > 0; e++, left--)
  758. {
  759. int opts_left;
  760. const struct argp_option *opt;
  761. e->short_options = so;
  762. for (opts_left = e->num, opt = e->opt; opts_left; opt++, opts_left--)
  763. {
  764. int ch = *more_so;
  765. if (oshort (opt) && ch == opt->key)
  766. /* The next short option in MORE_SO, CH, is from OPT. */
  767. {
  768. if (! find_char (ch, short_options,
  769. short_options + hol_so_len))
  770. /* The short option CH isn't shadowed by HOL's options,
  771. so add it to the sum. */
  772. *so++ = ch;
  773. more_so++;
  774. }
  775. }
  776. }
  777. *so = '\0';
  778. free (hol->entries);
  779. free (hol->short_options);
  780. hol->entries = entries;
  781. hol->num_entries = num_entries;
  782. hol->short_options = short_options;
  783. }
  784. }
  785. hol_free (more);
  786. }
  787. /* Inserts enough spaces to make sure STREAM is at column COL. */
  788. static void
  789. indent_to (argp_fmtstream_t stream, unsigned col)
  790. {
  791. int needed = col - __argp_fmtstream_point (stream);
  792. while (needed-- > 0)
  793. __argp_fmtstream_putc (stream, ' ');
  794. }
  795. /* Output to STREAM either a space, or a newline if there isn't room for at
  796. least ENSURE characters before the right margin. */
  797. static void
  798. space (argp_fmtstream_t stream, size_t ensure)
  799. {
  800. if (__argp_fmtstream_point (stream) + ensure
  801. >= __argp_fmtstream_rmargin (stream))
  802. __argp_fmtstream_putc (stream, '\n');
  803. else
  804. __argp_fmtstream_putc (stream, ' ');
  805. }
  806. /* If the option REAL has an argument, we print it in using the printf
  807. format REQ_FMT or OPT_FMT depending on whether it's a required or
  808. optional argument. */
  809. static void
  810. arg (const struct argp_option *real, const char *req_fmt, const char *opt_fmt,
  811. const char *domain, argp_fmtstream_t stream)
  812. {
  813. if (real->arg)
  814. {
  815. if (real->flags & OPTION_ARG_OPTIONAL)
  816. __argp_fmtstream_printf (stream, opt_fmt,
  817. dgettext (domain, real->arg));
  818. else
  819. __argp_fmtstream_printf (stream, req_fmt,
  820. dgettext (domain, real->arg));
  821. }
  822. }
  823. /* Helper functions for hol_entry_help. */
  824. /* State used during the execution of hol_help. */
  825. struct hol_help_state
  826. {
  827. /* PREV_ENTRY should contain the previous entry printed, or 0. */
  828. struct hol_entry *prev_entry;
  829. /* If an entry is in a different group from the previous one, and SEP_GROUPS
  830. is true, then a blank line will be printed before any output. */
  831. int sep_groups;
  832. /* True if a duplicate option argument was suppressed (only ever set if
  833. UPARAMS.dup_args is false). */
  834. int suppressed_dup_arg;
  835. };
  836. /* Some state used while printing a help entry (used to communicate with
  837. helper functions). See the doc for hol_entry_help for more info, as most
  838. of the fields are copied from its arguments. */
  839. struct pentry_state
  840. {
  841. const struct hol_entry *entry;
  842. argp_fmtstream_t stream;
  843. struct hol_help_state *hhstate;
  844. /* True if nothing's been printed so far. */
  845. int first;
  846. /* If non-zero, the state that was used to print this help. */
  847. const struct argp_state *state;
  848. };
  849. /* If a user doc filter should be applied to DOC, do so. */
  850. static const char *
  851. filter_doc (const char *doc, int key, const struct argp *argp,
  852. const struct argp_state *state)
  853. {
  854. if (argp && argp->help_filter)
  855. /* We must apply a user filter to this output. */
  856. {
  857. void *input = __argp_input (argp, state);
  858. return (*argp->help_filter) (key, doc, input);
  859. }
  860. else
  861. /* No filter. */
  862. return doc;
  863. }
  864. /* Prints STR as a header line, with the margin lines set appropriately, and
  865. notes the fact that groups should be separated with a blank line. ARGP is
  866. the argp that should dictate any user doc filtering to take place. Note
  867. that the previous wrap margin isn't restored, but the left margin is reset
  868. to 0. */
  869. static void
  870. print_header (const char *str, const struct argp *argp,
  871. struct pentry_state *pest)
  872. {
  873. const char *tstr = dgettext (argp->argp_domain, str);
  874. const char *fstr = filter_doc (tstr, ARGP_KEY_HELP_HEADER, argp, pest->state);
  875. if (fstr)
  876. {
  877. if (*fstr)
  878. {
  879. if (pest->hhstate->prev_entry)
  880. /* Precede with a blank line. */
  881. __argp_fmtstream_putc (pest->stream, '\n');
  882. indent_to (pest->stream, uparams.header_col);
  883. __argp_fmtstream_set_lmargin (pest->stream, uparams.header_col);
  884. __argp_fmtstream_set_wmargin (pest->stream, uparams.header_col);
  885. __argp_fmtstream_puts (pest->stream, fstr);
  886. __argp_fmtstream_set_lmargin (pest->stream, 0);
  887. __argp_fmtstream_putc (pest->stream, '\n');
  888. }
  889. pest->hhstate->sep_groups = 1; /* Separate subsequent groups. */
  890. }
  891. if (fstr != tstr)
  892. free ((char *) fstr);
  893. }
  894. /* Inserts a comma if this isn't the first item on the line, and then makes
  895. sure we're at least to column COL. If this *is* the first item on a line,
  896. prints any pending whitespace/headers that should precede this line. Also
  897. clears FIRST. */
  898. static void
  899. comma (unsigned col, struct pentry_state *pest)
  900. {
  901. if (pest->first)
  902. {
  903. const struct hol_entry *pe = pest->hhstate->prev_entry;
  904. const struct hol_cluster *cl = pest->entry->cluster;
  905. if (pest->hhstate->sep_groups && pe && pest->entry->group != pe->group)
  906. __argp_fmtstream_putc (pest->stream, '\n');
  907. if (cl && cl->header && *cl->header
  908. && (!pe
  909. || (pe->cluster != cl
  910. && !hol_cluster_is_child (pe->cluster, cl))))
  911. /* If we're changing clusters, then this must be the start of the
  912. ENTRY's cluster unless that is an ancestor of the previous one
  913. (in which case we had just popped into a sub-cluster for a bit).
  914. If so, then print the cluster's header line. */
  915. {
  916. int old_wm = __argp_fmtstream_wmargin (pest->stream);
  917. print_header (cl->header, cl->argp, pest);
  918. __argp_fmtstream_set_wmargin (pest->stream, old_wm);
  919. }
  920. pest->first = 0;
  921. }
  922. else
  923. __argp_fmtstream_puts (pest->stream, ", ");
  924. indent_to (pest->stream, col);
  925. }
  926. /* Print help for ENTRY to STREAM. */
  927. static void
  928. hol_entry_help (struct hol_entry *entry, const struct argp_state *state,
  929. argp_fmtstream_t stream, struct hol_help_state *hhstate)
  930. {
  931. unsigned num;
  932. const struct argp_option *real = entry->opt, *opt;
  933. char *so = entry->short_options;
  934. int have_long_opt = 0; /* We have any long options. */
  935. /* Saved margins. */
  936. int old_lm = __argp_fmtstream_set_lmargin (stream, 0);
  937. int old_wm = __argp_fmtstream_wmargin (stream);
  938. /* PEST is a state block holding some of our variables that we'd like to
  939. share with helper functions. */
  940. struct pentry_state pest = { entry, stream, hhstate, 1, state };
  941. if (! odoc (real))
  942. for (opt = real, num = entry->num; num > 0; opt++, num--)
  943. if (opt->name && ovisible (opt))
  944. {
  945. have_long_opt = 1;
  946. break;
  947. }
  948. /* First emit short options. */
  949. __argp_fmtstream_set_wmargin (stream, uparams.short_opt_col); /* For truly bizarre cases. */
  950. for (opt = real, num = entry->num; num > 0; opt++, num--)
  951. if (oshort (opt) && opt->key == *so)
  952. /* OPT has a valid (non shadowed) short option. */
  953. {
  954. if (ovisible (opt))
  955. {
  956. comma (uparams.short_opt_col, &pest);
  957. __argp_fmtstream_putc (stream, '-');
  958. __argp_fmtstream_putc (stream, *so);
  959. if (!have_long_opt || uparams.dup_args)
  960. arg (real, " %s", "[%s]",
  961. state == NULL ? NULL : state->root_argp->argp_domain,
  962. stream);
  963. else if (real->arg)
  964. hhstate->suppressed_dup_arg = 1;
  965. }
  966. so++;
  967. }
  968. /* Now, long options. */
  969. if (odoc (real))
  970. /* A `documentation' option. */
  971. {
  972. __argp_fmtstream_set_wmargin (stream, uparams.doc_opt_col);
  973. for (opt = real, num = entry->num; num > 0; opt++, num--)
  974. if (opt->name && ovisible (opt))
  975. {
  976. comma (uparams.doc_opt_col, &pest);
  977. /* Calling gettext here isn't quite right, since sorting will
  978. have been done on the original; but documentation options
  979. should be pretty rare anyway... */
  980. __argp_fmtstream_puts (stream,
  981. dgettext (state == NULL ? NULL
  982. : state->root_argp->argp_domain,
  983. opt->name));
  984. }
  985. }
  986. else
  987. /* A real long option. */
  988. {
  989. __argp_fmtstream_set_wmargin (stream, uparams.long_opt_col);
  990. for (opt = real, num = entry->num; num > 0; opt++, num--)
  991. if (opt->name && ovisible (opt))
  992. {
  993. comma (uparams.long_opt_col, &pest);
  994. __argp_fmtstream_printf (stream, "--%s", opt->name);
  995. arg (real, "=%s", "[=%s]",
  996. state == NULL ? NULL : state->root_argp->argp_domain, stream);
  997. }
  998. }
  999. /* Next, documentation strings. */
  1000. __argp_fmtstream_set_lmargin (stream, 0);
  1001. if (pest.first)
  1002. {
  1003. /* Didn't print any switches, what's up? */
  1004. if (!oshort (real) && !real->name)
  1005. /* This is a group header, print it nicely. */
  1006. print_header (real->doc, entry->argp, &pest);
  1007. else
  1008. /* Just a totally shadowed option or null header; print nothing. */
  1009. goto cleanup; /* Just return, after cleaning up. */
  1010. }
  1011. else
  1012. {
  1013. const char *tstr = real->doc ? dgettext (state == NULL ? NULL
  1014. : state->root_argp->argp_domain,
  1015. real->doc) : 0;
  1016. const char *fstr = filter_doc (tstr, real->key, entry->argp, state);
  1017. if (fstr && *fstr)
  1018. {
  1019. unsigned int col = __argp_fmtstream_point (stream);
  1020. __argp_fmtstream_set_lmargin (stream, uparams.opt_doc_col);
  1021. __argp_fmtstream_set_wmargin (stream, uparams.opt_doc_col);
  1022. if (col > (unsigned int) (uparams.opt_doc_col + 3))
  1023. __argp_fmtstream_putc (stream, '\n');
  1024. else if (col >= (unsigned int) uparams.opt_doc_col)
  1025. __argp_fmtstream_puts (stream, " ");
  1026. else
  1027. indent_to (stream, uparams.opt_doc_col);
  1028. __argp_fmtstream_puts (stream, fstr);
  1029. }
  1030. if (fstr && fstr != tstr)
  1031. free ((char *) fstr);
  1032. /* Reset the left margin. */
  1033. __argp_fmtstream_set_lmargin (stream, 0);
  1034. __argp_fmtstream_putc (stream, '\n');
  1035. }
  1036. hhstate->prev_entry = entry;
  1037. cleanup:
  1038. __argp_fmtstream_set_lmargin (stream, old_lm);
  1039. __argp_fmtstream_set_wmargin (stream, old_wm);
  1040. }
  1041. /* Output a long help message about the options in HOL to STREAM. */
  1042. static void
  1043. hol_help (struct hol *hol, const struct argp_state *state,
  1044. argp_fmtstream_t stream)
  1045. {
  1046. unsigned num;
  1047. struct hol_entry *entry;
  1048. struct hol_help_state hhstate = { 0, 0, 0 };
  1049. for (entry = hol->entries, num = hol->num_entries; num > 0; entry++, num--)
  1050. hol_entry_help (entry, state, stream, &hhstate);
  1051. if (hhstate.suppressed_dup_arg && uparams.dup_args_note)
  1052. {
  1053. const char *tstr = dgettext (state == NULL ? NULL
  1054. : state->root_argp->argp_domain, "\
  1055. Mandatory or optional arguments to long options are also mandatory or \
  1056. optional for any corresponding short options.");
  1057. const char *fstr = filter_doc (tstr, ARGP_KEY_HELP_DUP_ARGS_NOTE,
  1058. state ? state->root_argp : 0, state);
  1059. if (fstr && *fstr)
  1060. {
  1061. __argp_fmtstream_putc (stream, '\n');
  1062. __argp_fmtstream_puts (stream, fstr);
  1063. __argp_fmtstream_putc (stream, '\n');
  1064. }
  1065. if (fstr && fstr != tstr)
  1066. free ((char *) fstr);
  1067. }
  1068. }
  1069. /* Helper functions for hol_usage. */
  1070. /* If OPT is a short option without an arg, append its key to the string
  1071. pointer pointer to by COOKIE, and advance the pointer. */
  1072. static int
  1073. add_argless_short_opt (const struct argp_option *opt,
  1074. const struct argp_option *real,
  1075. const char *domain, void *cookie)
  1076. {
  1077. char **snao_end = cookie;
  1078. if (!(opt->arg || real->arg)
  1079. && !((opt->flags | real->flags) & OPTION_NO_USAGE))
  1080. *(*snao_end)++ = opt->key;
  1081. return 0;
  1082. }
  1083. /* If OPT is a short option with an arg, output a usage entry for it to the
  1084. stream pointed at by COOKIE. */
  1085. static int
  1086. usage_argful_short_opt (const struct argp_option *opt,
  1087. const struct argp_option *real,
  1088. const char *domain, void *cookie)
  1089. {
  1090. argp_fmtstream_t stream = cookie;
  1091. const char *arg = opt->arg;
  1092. int flags = opt->flags | real->flags;
  1093. if (! arg)
  1094. arg = real->arg;
  1095. if (arg && !(flags & OPTION_NO_USAGE))
  1096. {
  1097. arg = dgettext (domain, arg);
  1098. if (flags & OPTION_ARG_OPTIONAL)
  1099. __argp_fmtstream_printf (stream, " [-%c[%s]]", opt->key, arg);
  1100. else
  1101. {
  1102. /* Manually do line wrapping so that it (probably) won't
  1103. get wrapped at the embedded space. */
  1104. space (stream, 6 + strlen (arg));
  1105. __argp_fmtstream_printf (stream, "[-%c %s]", opt->key, arg);
  1106. }
  1107. }
  1108. return 0;
  1109. }
  1110. /* Output a usage entry for the long option opt to the stream pointed at by
  1111. COOKIE. */
  1112. static int
  1113. usage_long_opt (const struct argp_option *opt,
  1114. const struct argp_option *real,
  1115. const char *domain, void *cookie)
  1116. {
  1117. argp_fmtstream_t stream = cookie;
  1118. const char *arg = opt->arg;
  1119. int flags = opt->flags | real->flags;
  1120. if (! arg)
  1121. arg = real->arg;
  1122. if (! (flags & OPTION_NO_USAGE))
  1123. {
  1124. if (arg)
  1125. {
  1126. arg = dgettext (domain, arg);
  1127. if (flags & OPTION_ARG_OPTIONAL)
  1128. __argp_fmtstream_printf (stream, " [--%s[=%s]]", opt->name, arg);
  1129. else
  1130. __argp_fmtstream_printf (stream, " [--%s=%s]", opt->name, arg);
  1131. }
  1132. else
  1133. __argp_fmtstream_printf (stream, " [--%s]", opt->name);
  1134. }
  1135. return 0;
  1136. }
  1137. /* Print a short usage description for the arguments in HOL to STREAM. */
  1138. static void
  1139. hol_usage (struct hol *hol, argp_fmtstream_t stream)
  1140. {
  1141. if (hol->num_entries > 0)
  1142. {
  1143. unsigned nentries;
  1144. struct hol_entry *entry;
  1145. char *short_no_arg_opts = alloca (strlen (hol->short_options) + 1);
  1146. char *snao_end = short_no_arg_opts;
  1147. /* First we put a list of short options without arguments. */
  1148. for (entry = hol->entries, nentries = hol->num_entries
  1149. ; nentries > 0
  1150. ; entry++, nentries--)
  1151. hol_entry_short_iterate (entry, add_argless_short_opt,
  1152. entry->argp->argp_domain, &snao_end);
  1153. if (snao_end > short_no_arg_opts)
  1154. {
  1155. *snao_end++ = 0;
  1156. __argp_fmtstream_printf (stream, " [-%s]", short_no_arg_opts);
  1157. }
  1158. /* Now a list of short options *with* arguments. */
  1159. for (entry = hol->entries, nentries = hol->num_entries
  1160. ; nentries > 0
  1161. ; entry++, nentries--)
  1162. hol_entry_short_iterate (entry, usage_argful_short_opt,
  1163. entry->argp->argp_domain, stream);
  1164. /* Finally, a list of long options (whew!). */
  1165. for (entry = hol->entries, nentries = hol->num_entries
  1166. ; nentries > 0
  1167. ; entry++, nentries--)
  1168. hol_entry_long_iterate (entry, usage_long_opt,
  1169. entry->argp->argp_domain, stream);
  1170. }
  1171. }
  1172. /* Make a HOL containing all levels of options in ARGP. CLUSTER is the
  1173. cluster in which ARGP's entries should be clustered, or 0. */
  1174. static struct hol *
  1175. argp_hol (const struct argp *argp, struct hol_cluster *cluster)
  1176. {
  1177. const struct argp_child *child = argp->children;
  1178. struct hol *hol = make_hol (argp, cluster);
  1179. if (child)
  1180. while (child->argp)
  1181. {
  1182. struct hol_cluster *child_cluster =
  1183. ((child->group || child->header)
  1184. /* Put CHILD->argp within its own cluster. */
  1185. ? hol_add_cluster (hol, child->group, child->header,
  1186. child - argp->children, cluster, argp)
  1187. /* Just merge it into the parent's cluster. */
  1188. : cluster);
  1189. hol_append (hol, argp_hol (child->argp, child_cluster)) ;
  1190. child++;
  1191. }
  1192. return hol;
  1193. }
  1194. /* Calculate how many different levels with alternative args strings exist in
  1195. ARGP. */
  1196. static size_t
  1197. argp_args_levels (const struct argp *argp)
  1198. {
  1199. size_t levels = 0;
  1200. const struct argp_child *child = argp->children;
  1201. if (argp->args_doc && strchr (argp->args_doc, '\n'))
  1202. levels++;
  1203. if (child)
  1204. while (child->argp)
  1205. levels += argp_args_levels ((child++)->argp);
  1206. return levels;
  1207. }
  1208. /* Print all the non-option args documented in ARGP to STREAM. Any output is
  1209. preceded by a space. LEVELS is a pointer to a byte vector the length
  1210. returned by argp_args_levels; it should be initialized to zero, and
  1211. updated by this routine for the next call if ADVANCE is true. True is
  1212. returned as long as there are more patterns to output. */
  1213. static int
  1214. argp_args_usage (const struct argp *argp, const struct argp_state *state,
  1215. char **levels, int advance, argp_fmtstream_t stream)
  1216. {
  1217. char *our_level = *levels;
  1218. int multiple = 0;
  1219. const struct argp_child *child = argp->children;
  1220. const char *tdoc = dgettext (argp->argp_domain, argp->args_doc), *nl = 0;
  1221. const char *fdoc = filter_doc (tdoc, ARGP_KEY_HELP_ARGS_DOC, argp, state);
  1222. if (fdoc)
  1223. {
  1224. const char *cp = fdoc;
  1225. nl = __strchrnul (cp, '\n');
  1226. if (*nl != '\0')
  1227. /* This is a `multi-level' args doc; advance to the correct position
  1228. as determined by our state in LEVELS, and update LEVELS. */
  1229. {
  1230. int i;
  1231. multiple = 1;
  1232. for (i = 0; i < *our_level; i++)
  1233. cp = nl + 1, nl = __strchrnul (cp, '\n');
  1234. (*levels)++;
  1235. }
  1236. /* Manually do line wrapping so that it (probably) won't get wrapped at
  1237. any embedded spaces. */
  1238. space (stream, 1 + nl - cp);
  1239. __argp_fmtstream_write (stream, cp, nl - cp);
  1240. }
  1241. if (fdoc && fdoc != tdoc)
  1242. free ((char *)fdoc); /* Free user's modified doc string. */
  1243. if (child)
  1244. while (child->argp)
  1245. advance = !argp_args_usage ((child++)->argp, state, levels, advance, stream);
  1246. if (advance && multiple)
  1247. {
  1248. /* Need to increment our level. */
  1249. if (*nl)
  1250. /* There's more we can do here. */
  1251. {
  1252. (*our_level)++;
  1253. advance = 0; /* Our parent shouldn't advance also. */
  1254. }
  1255. else if (*our_level > 0)
  1256. /* We had multiple levels, but used them up; reset to zero. */
  1257. *our_level = 0;
  1258. }
  1259. return !advance;
  1260. }
  1261. /* Print the documentation for ARGP to STREAM; if POST is false, then
  1262. everything preceeding a `\v' character in the documentation strings (or
  1263. the whole string, for those with none) is printed, otherwise, everything
  1264. following the `\v' character (nothing for strings without). Each separate
  1265. bit of documentation is separated a blank line, and if PRE_BLANK is true,
  1266. then the first is as well. If FIRST_ONLY is true, only the first
  1267. occurrence is output. Returns true if anything was output. */
  1268. static int
  1269. argp_doc (const struct argp *argp, const struct argp_state *state,
  1270. int post, int pre_blank, int first_only,
  1271. argp_fmtstream_t stream)
  1272. {
  1273. const char *text;
  1274. const char *inp_text;
  1275. void *input = 0;
  1276. int anything = 0;
  1277. size_t inp_text_limit = 0;
  1278. const char *doc = dgettext (argp->argp_domain, argp->doc);
  1279. const struct argp_child *child = argp->children;
  1280. if (doc)
  1281. {
  1282. char *vt = strchr (doc, '\v');
  1283. inp_text = post ? (vt ? vt + 1 : 0) : doc;
  1284. inp_text_limit = (!post && vt) ? (vt - doc) : 0;
  1285. }
  1286. else
  1287. inp_text = 0;
  1288. if (argp->help_filter)
  1289. /* We have to filter the doc strings. */
  1290. {
  1291. if (inp_text_limit)
  1292. /* Copy INP_TEXT so that it's nul-terminated. */
  1293. inp_text = __strndup (inp_text, inp_text_limit);
  1294. input = __argp_input (argp, state);
  1295. text =
  1296. (*argp->help_filter) (post
  1297. ? ARGP_KEY_HELP_POST_DOC
  1298. : ARGP_KEY_HELP_PRE_DOC,
  1299. inp_text, input);
  1300. }
  1301. else
  1302. text = (const char *) inp_text;
  1303. if (text)
  1304. {
  1305. if (pre_blank)
  1306. __argp_fmtstream_putc (stream, '\n');
  1307. if (text == inp_text && inp_text_limit)
  1308. __argp_fmtstream_write (stream, inp_text, inp_text_limit);
  1309. else
  1310. __argp_fmtstream_puts (stream, text);
  1311. if (__argp_fmtstream_point (stream) > __argp_fmtstream_lmargin (stream))
  1312. __argp_fmtstream_putc (stream, '\n');
  1313. anything = 1;
  1314. }
  1315. if (text && text != inp_text)
  1316. free ((char *) text); /* Free TEXT returned from the help filter. */
  1317. if (inp_text && inp_text_limit && argp->help_filter)
  1318. free ((char *) inp_text); /* We copied INP_TEXT, so free it now. */
  1319. if (post && argp->help_filter)
  1320. /* Now see if we have to output a ARGP_KEY_HELP_EXTRA text. */
  1321. {
  1322. text = (*argp->help_filter) (ARGP_KEY_HELP_EXTRA, 0, input);
  1323. if (text)
  1324. {
  1325. if (anything || pre_blank)
  1326. __argp_fmtstream_putc (stream, '\n');
  1327. __argp_fmtstream_puts (stream, text);
  1328. free ((char *) text);
  1329. if (__argp_fmtstream_point (stream)
  1330. > __argp_fmtstream_lmargin (stream))
  1331. __argp_fmtstream_putc (stream, '\n');
  1332. anything = 1;
  1333. }
  1334. }
  1335. if (child)
  1336. while (child->argp && !(first_only && anything))
  1337. anything |=
  1338. argp_doc ((child++)->argp, state,
  1339. post, anything || pre_blank, first_only,
  1340. stream);
  1341. return anything;
  1342. }
  1343. /* Output a usage message for ARGP to STREAM. If called from
  1344. argp_state_help, STATE is the relevant parsing state. FLAGS are from the
  1345. set ARGP_HELP_*. NAME is what to use wherever a `program name' is
  1346. needed. */
  1347. static void
  1348. _help (const struct argp *argp, const struct argp_state *state, FILE *stream,
  1349. unsigned flags, char *name)
  1350. {
  1351. int anything = 0; /* Whether we've output anything. */
  1352. struct hol *hol = 0;
  1353. argp_fmtstream_t fs;
  1354. if (! stream)
  1355. return;
  1356. #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
  1357. __flockfile (stream);
  1358. #endif
  1359. fill_in_uparams (state);
  1360. fs = __argp_make_fmtstream (stream, 0, uparams.rmargin, 0);
  1361. if (! fs)
  1362. {
  1363. #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
  1364. __funlockfile (stream);
  1365. #endif
  1366. return;
  1367. }
  1368. if (flags & (ARGP_HELP_USAGE | ARGP_HELP_SHORT_USAGE | ARGP_HELP_LONG))
  1369. {
  1370. hol = argp_hol (argp, 0);
  1371. /* If present, these options always come last. */
  1372. hol_set_group (hol, "help", -1);
  1373. hol_set_group (hol, "version", -1);
  1374. hol_sort (hol);
  1375. }
  1376. if (flags & (ARGP_HELP_USAGE | ARGP_HELP_SHORT_USAGE))
  1377. /* Print a short `Usage:' message. */
  1378. {
  1379. int first_pattern = 1, more_patterns;
  1380. size_t num_pattern_levels = argp_args_levels (argp);
  1381. char *pattern_levels = alloca (num_pattern_levels);
  1382. memset (pattern_levels, 0, num_pattern_levels);
  1383. do
  1384. {
  1385. int old_lm;
  1386. int old_wm = __argp_fmtstream_set_wmargin (fs, uparams.usage_indent);
  1387. char *levels = pattern_levels;
  1388. if (first_pattern)
  1389. __argp_fmtstream_printf (fs, "%s %s",
  1390. dgettext (argp->argp_domain, "Usage:"),
  1391. name);
  1392. else
  1393. __argp_fmtstream_printf (fs, "%s %s",
  1394. dgettext (argp->argp_domain, " or: "),
  1395. name);
  1396. /* We set the lmargin as well as the wmargin, because hol_usage
  1397. manually wraps options with newline to avoid annoying breaks. */
  1398. old_lm = __argp_fmtstream_set_lmargin (fs, uparams.usage_indent);
  1399. if (flags & ARGP_HELP_SHORT_USAGE)
  1400. /* Just show where the options go. */
  1401. {
  1402. if (hol->num_entries > 0)
  1403. __argp_fmtstream_puts (fs, dgettext (argp->argp_domain,
  1404. " [OPTION...]"));
  1405. }
  1406. else
  1407. /* Actually print the options. */
  1408. {
  1409. hol_usage (hol, fs);
  1410. flags |= ARGP_HELP_SHORT_USAGE; /* But only do so once. */
  1411. }
  1412. more_patterns = argp_args_usage (argp, state, &levels, 1, fs);
  1413. __argp_fmtstream_set_wmargin (fs, old_wm);
  1414. __argp_fmtstream_set_lmargin (fs, old_lm);
  1415. __argp_fmtstream_putc (fs, '\n');
  1416. anything = 1;
  1417. first_pattern = 0;
  1418. }
  1419. while (more_patterns);
  1420. }
  1421. if (flags & ARGP_HELP_PRE_DOC)
  1422. anything |= argp_doc (argp, state, 0, 0, 1, fs);
  1423. if (flags & ARGP_HELP_SEE)
  1424. {
  1425. __argp_fmtstream_printf (fs, dgettext (argp->argp_domain, "\
  1426. Try `%s --help' or `%s --usage' for more information.\n"),
  1427. name, name);
  1428. anything = 1;
  1429. }
  1430. if (flags & ARGP_HELP_LONG)
  1431. /* Print a long, detailed help message. */
  1432. {
  1433. /* Print info about all the options. */
  1434. if (hol->num_entries > 0)
  1435. {
  1436. if (anything)
  1437. __argp_fmtstream_putc (fs, '\n');
  1438. hol_help (hol, state, fs);
  1439. anything = 1;
  1440. }
  1441. }
  1442. if (flags & ARGP_HELP_POST_DOC)
  1443. /* Print any documentation strings at the end. */
  1444. anything |= argp_doc (argp, state, 1, anything, 0, fs);
  1445. if ((flags & ARGP_HELP_BUG_ADDR) && argp_program_bug_address)
  1446. {
  1447. if (anything)
  1448. __argp_fmtstream_putc (fs, '\n');
  1449. __argp_fmtstream_printf (fs, dgettext (argp->argp_domain,
  1450. "Report bugs to %s.\n"),
  1451. argp_program_bug_address);
  1452. anything = 1;
  1453. }
  1454. #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
  1455. __funlockfile (stream);
  1456. #endif
  1457. if (hol)
  1458. hol_free (hol);
  1459. __argp_fmtstream_free (fs);
  1460. }
  1461. /* Output a usage message for ARGP to STREAM. FLAGS are from the set
  1462. ARGP_HELP_*. NAME is what to use wherever a `program name' is needed. */
  1463. void __argp_help (const struct argp *argp, FILE *stream,
  1464. unsigned flags, char *name)
  1465. {
  1466. _help (argp, 0, stream, flags, name);
  1467. }
  1468. #ifdef weak_alias
  1469. weak_alias (__argp_help, argp_help)
  1470. #endif
  1471. #ifndef _LIBC
  1472. char *__argp_basename (char *name)
  1473. {
  1474. char *short_name = strrchr (name, '/');
  1475. return short_name ? short_name + 1 : name;
  1476. }
  1477. char *
  1478. __argp_short_program_name (void)
  1479. {
  1480. # if HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
  1481. return program_invocation_short_name;
  1482. # elif HAVE_DECL_PROGRAM_INVOCATION_NAME
  1483. return __argp_basename (program_invocation_name);
  1484. # else
  1485. /* FIXME: What now? Miles suggests that it is better to use NULL,
  1486. but currently the value is passed on directly to fputs_unlocked,
  1487. so that requires more changes. */
  1488. # if __GNUC__
  1489. # warning No reasonable value to return
  1490. # endif /* __GNUC__ */
  1491. return "";
  1492. # endif
  1493. }
  1494. #endif
  1495. /* Output, if appropriate, a usage message for STATE to STREAM. FLAGS are
  1496. from the set ARGP_HELP_*. */
  1497. void
  1498. __argp_state_help (const struct argp_state *state, FILE *stream, unsigned flags)
  1499. {
  1500. if ((!state || ! (state->flags & ARGP_NO_ERRS)) && stream)
  1501. {
  1502. if (state && (state->flags & ARGP_LONG_ONLY))
  1503. flags |= ARGP_HELP_LONG_ONLY;
  1504. _help (state ? state->root_argp : 0, state, stream, flags,
  1505. state ? state->name : __argp_short_program_name ());
  1506. if (!state || ! (state->flags & ARGP_NO_EXIT))
  1507. {
  1508. if (flags & ARGP_HELP_EXIT_ERR)
  1509. exit (argp_err_exit_status);
  1510. if (flags & ARGP_HELP_EXIT_OK)
  1511. exit (0);
  1512. }
  1513. }
  1514. }
  1515. #ifdef weak_alias
  1516. weak_alias (__argp_state_help, argp_state_help)
  1517. #endif
  1518. /* If appropriate, print the printf string FMT and following args, preceded
  1519. by the program name and `:', to stderr, and followed by a `Try ... --help'
  1520. message, then exit (1). */
  1521. void
  1522. __argp_error (const struct argp_state *state, const char *fmt, ...)
  1523. {
  1524. if (!state || !(state->flags & ARGP_NO_ERRS))
  1525. {
  1526. FILE *stream = state ? state->err_stream : stderr;
  1527. if (stream)
  1528. {
  1529. va_list ap;
  1530. #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
  1531. __flockfile (stream);
  1532. #endif
  1533. va_start (ap, fmt);
  1534. #ifdef _LIBC
  1535. char *buf;
  1536. if (__vasprintf_internal (&buf, fmt, ap, 0) < 0)
  1537. buf = NULL;
  1538. __fxprintf (stream, "%s: %s\n",
  1539. state ? state->name : __argp_short_program_name (), buf);
  1540. free (buf);
  1541. #else
  1542. fputs_unlocked (state ? state->name : __argp_short_program_name (),
  1543. stream);
  1544. putc_unlocked (':', stream);
  1545. putc_unlocked (' ', stream);
  1546. vfprintf (stream, fmt, ap);
  1547. putc_unlocked ('\n', stream);
  1548. #endif
  1549. __argp_state_help (state, stream, ARGP_HELP_STD_ERR);
  1550. va_end (ap);
  1551. #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
  1552. __funlockfile (stream);
  1553. #endif
  1554. }
  1555. }
  1556. }
  1557. #ifdef weak_alias
  1558. weak_alias (__argp_error, argp_error)
  1559. #endif
  1560. /* Similar to the standard gnu error-reporting function error(), but will
  1561. respect the ARGP_NO_EXIT and ARGP_NO_ERRS flags in STATE, and will print
  1562. to STATE->err_stream. This is useful for argument parsing code that is
  1563. shared between program startup (when exiting is desired) and runtime
  1564. option parsing (when typically an error code is returned instead). The
  1565. difference between this function and argp_error is that the latter is for
  1566. *parsing errors*, and the former is for other problems that occur during
  1567. parsing but don't reflect a (syntactic) problem with the input. */
  1568. void
  1569. __argp_failure (const struct argp_state *state, int status, int errnum,
  1570. const char *fmt, ...)
  1571. {
  1572. if (!state || !(state->flags & ARGP_NO_ERRS))
  1573. {
  1574. FILE *stream = state ? state->err_stream : stderr;
  1575. if (stream)
  1576. {
  1577. #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
  1578. __flockfile (stream);
  1579. #endif
  1580. #ifdef _LIBC
  1581. __fxprintf (stream, "%s",
  1582. state ? state->name : __argp_short_program_name ());
  1583. #else
  1584. fputs_unlocked (state ? state->name : __argp_short_program_name (),
  1585. stream);
  1586. #endif
  1587. if (fmt)
  1588. {
  1589. va_list ap;
  1590. va_start (ap, fmt);
  1591. #ifdef _LIBC
  1592. char *buf;
  1593. if (__vasprintf_internal (&buf, fmt, ap, 0) < 0)
  1594. buf = NULL;
  1595. __fxprintf (stream, ": %s", buf);
  1596. free (buf);
  1597. #else
  1598. putc_unlocked (':', stream);
  1599. putc_unlocked (' ', stream);
  1600. vfprintf (stream, fmt, ap);
  1601. #endif
  1602. va_end (ap);
  1603. }
  1604. if (errnum)
  1605. {
  1606. char buf[200];
  1607. #ifdef _LIBC
  1608. __fxprintf (stream, ": %s",
  1609. __strerror_r (errnum, buf, sizeof (buf)));
  1610. #else
  1611. putc_unlocked (':', stream);
  1612. putc_unlocked (' ', stream);
  1613. # ifdef HAVE_STRERROR_R
  1614. fputs (__strerror_r (errnum, buf, sizeof (buf)), stream);
  1615. # else
  1616. fputs (strerror (errnum), stream);
  1617. # endif
  1618. #endif
  1619. }
  1620. #ifdef _LIBC
  1621. if (_IO_fwide (stream, 0) > 0)
  1622. putwc_unlocked (L'\n', stream);
  1623. else
  1624. #endif
  1625. putc_unlocked ('\n', stream);
  1626. #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
  1627. __funlockfile (stream);
  1628. #endif
  1629. if (status && (!state || !(state->flags & ARGP_NO_EXIT)))
  1630. exit (status);
  1631. }
  1632. }
  1633. }
  1634. #ifdef weak_alias
  1635. weak_alias (__argp_failure, argp_failure)
  1636. #endif