argp-help.c 59 KB

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