argp-help.c 59 KB

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