argp-help.c 59 KB

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