• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 4 -*- */
2 
3 /** \ingroup popt
4  * \file popt/popthelp.c
5  */
6 
7 /* (C) 1998-2002 Red Hat, Inc. -- Licensing details are in the COPYING
8    file accompanying popt source distributions, available from
9    ftp://ftp.rpm.org/pub/rpm/dist. */
10 
11 #include "system.h"
12 
13 #define        POPT_USE_TIOCGWINSZ
14 #ifdef POPT_USE_TIOCGWINSZ
15 #include <sys/ioctl.h>
16 #endif
17 
18 #define	POPT_WCHAR_HACK
19 #ifdef 	POPT_WCHAR_HACK
20 #include <wchar.h>			/* for mbsrtowcs */
21 #endif
22 #include "poptint.h"
23 
24 
25 /**
26  * Display arguments.
27  * @param con		context
28  * @param foo		(unused)
29  * @param key		option(s)
30  * @param arg		(unused)
31  * @param data		(unused)
32  */
displayArgs(poptContext con,UNUSED (enum poptCallbackReason foo),struct poptOption * key,UNUSED (const char * arg),UNUSED (void * data))33 static void displayArgs(poptContext con,
34 		UNUSED(enum poptCallbackReason foo),
35 		struct poptOption * key,
36 		UNUSED(const char * arg),
37 		UNUSED(void * data))
38 {
39     if (key->shortName == '?')
40 	poptPrintHelp(con, stdout, 0);
41     else
42 	poptPrintUsage(con, stdout, 0);
43 
44     con = poptFreeContext(con);
45     exit(0);
46 }
47 
48 #ifdef	NOTYET
49 static int show_option_defaults = 0;
50 #endif
51 
52 /**
53  * Empty table marker to enable displaying popt alias/exec options.
54  */
55 struct poptOption poptAliasOptions[] = {
56     POPT_TABLEEND
57 };
58 
59 /**
60  * Auto help table options.
61  */
62 struct poptOption poptHelpOptions[] = {
63   { NULL, '\0', POPT_ARG_CALLBACK, (void *)displayArgs, 0, NULL, NULL },
64   { "help", '?', 0, NULL, (int)'?', N_("Show this help message"), NULL },
65   { "usage", '\0', 0, NULL, (int)'u', N_("Display brief usage message"), NULL },
66     POPT_TABLEEND
67 } ;
68 
69 static struct poptOption poptHelpOptions2[] = {
70   { NULL, '\0', POPT_ARG_INTL_DOMAIN, PACKAGE, 0, NULL, NULL},
71   { NULL, '\0', POPT_ARG_CALLBACK, (void *)displayArgs, 0, NULL, NULL },
72   { "help", '?', 0, NULL, (int)'?', N_("Show this help message"), NULL },
73   { "usage", '\0', 0, NULL, (int)'u', N_("Display brief usage message"), NULL },
74 #ifdef	NOTYET
75   { "defaults", '\0', POPT_ARG_NONE, &show_option_defaults, 0,
76 	N_("Display option defaults in message"), NULL },
77 #endif
78   { NULL, '\0',	0, NULL, 0, N_("Terminate options"), NULL },
79     POPT_TABLEEND
80 } ;
81 
82 struct poptOption * poptHelpOptionsI18N = poptHelpOptions2;
83 
84 #define        _POPTHELP_MAXLINE       ((size_t)79)
85 
86 typedef struct columns_s {
87     size_t cur;
88     size_t max;
89 } * columns_t;
90 
91 /**
92  * Return no. of columns in output window.
93  * @param fp           FILE
94  * @return             no. of columns
95  */
maxColumnWidth(FILE * fp)96 static size_t maxColumnWidth(FILE *fp)
97 {
98     size_t maxcols = _POPTHELP_MAXLINE;
99 #if defined(TIOCGWINSZ)
100     struct winsize ws;
101     int fdno = fileno(fp ? fp : stdout);
102 
103     memset(&ws, 0, sizeof(ws));
104     if (fdno >= 0 && !ioctl(fdno, (unsigned long)TIOCGWINSZ, &ws)) {
105 	size_t ws_col = (size_t)ws.ws_col;
106 	if (ws_col > maxcols && ws_col < (size_t)256)
107 	    maxcols = ws_col - 1;
108     }
109 #endif
110     return maxcols;
111 }
112 
113 /**
114  * Determine number of display characters in a string.
115  * @param s		string
116  * @return		no. of display characters.
117  */
stringDisplayWidth(const char * s)118 static inline size_t stringDisplayWidth(const char *s)
119 {
120     size_t n = strlen(s);
121 #ifdef	POPT_WCHAR_HACK
122     mbstate_t t;
123 
124     memset ((void *)&t, 0, sizeof (t));	/* In initial state.  */
125     /* Determine number of display characters.  */
126     n = mbsrtowcs (NULL, &s, n, &t);
127 #else
128     n = 0;
129     for (; *s; s = POPT_next_char(s))
130 	n++;
131 #endif
132 
133     return n;
134 }
135 
136 /**
137  * @param opt		option(s)
138  */
139 static const char *
getTableTranslationDomain(const struct poptOption * opt)140 getTableTranslationDomain(const struct poptOption *opt)
141 {
142     if (opt != NULL)
143     for (; opt->longName || opt->shortName || opt->arg; opt++) {
144 	if (opt->argInfo == POPT_ARG_INTL_DOMAIN)
145 	    return opt->arg;
146     }
147     return NULL;
148 }
149 
150 /**
151  * @param opt		option(s)
152  * @param translation_domain	translation domain
153  */
154 static const char *
getArgDescrip(const struct poptOption * opt,const char * translation_domain)155 getArgDescrip(const struct poptOption * opt,
156 		/* FIX: i18n macros disabled with lclint */
157 		const char * translation_domain)
158 {
159     if (!poptArgType(opt)) return NULL;
160 
161     if (poptArgType(opt) == POPT_ARG_MAINCALL)
162 	return opt->argDescrip;
163     if (poptArgType(opt) == POPT_ARG_ARGV)
164 	return opt->argDescrip;
165 
166     if (opt->argDescrip) {
167 	/* Some strings need popt library, not application, i18n domain. */
168 	if (opt == (poptHelpOptions + 1)
169 	 || opt == (poptHelpOptions + 2)
170 	 || !strcmp(opt->argDescrip, N_("Help options:"))
171 	 || !strcmp(opt->argDescrip, N_("Options implemented via popt alias/exec:")))
172 	    return POPT_(opt->argDescrip);
173 
174 	/* Use the application i18n domain. */
175 	return D_(translation_domain, opt->argDescrip);
176     }
177 
178     switch (poptArgType(opt)) {
179     case POPT_ARG_NONE:		return POPT_("NONE");
180 #ifdef	DYING
181     case POPT_ARG_VAL:		return POPT_("VAL");
182 #else
183     case POPT_ARG_VAL:		return NULL;
184 #endif
185     case POPT_ARG_INT:		return POPT_("INT");
186     case POPT_ARG_SHORT:	return POPT_("SHORT");
187     case POPT_ARG_LONG:		return POPT_("LONG");
188     case POPT_ARG_LONGLONG:	return POPT_("LONGLONG");
189     case POPT_ARG_STRING:	return POPT_("STRING");
190     case POPT_ARG_FLOAT:	return POPT_("FLOAT");
191     case POPT_ARG_DOUBLE:	return POPT_("DOUBLE");
192     case POPT_ARG_MAINCALL:	return NULL;
193     case POPT_ARG_ARGV:		return NULL;
194     default:			return POPT_("ARG");
195     }
196 }
197 
198 /**
199  * Display default value for an option.
200  * @param lineLength	display positions remaining
201  * @param opt		option(s)
202  * @param translation_domain	translation domain
203  * @return
204  */
205 static char *
singleOptionDefaultValue(size_t lineLength,const struct poptOption * opt,const char * translation_domain)206 singleOptionDefaultValue(size_t lineLength,
207 		const struct poptOption * opt,
208 		/* FIX: i18n macros disabled with lclint */
209 		const char * translation_domain)
210 {
211     const char * defstr = D_(translation_domain, "default");
212     char * le = malloc(4*lineLength + 1);
213     char * l = le;
214 
215     if (le == NULL) return NULL;	/* XXX can't happen */
216     *le = '\0';
217     *le++ = '(';
218     le = stpcpy(le, defstr);
219     *le++ = ':';
220     *le++ = ' ';
221   if (opt->arg) {	/* XXX programmer error */
222     poptArg arg = { .ptr = opt->arg };
223     switch (poptArgType(opt)) {
224     case POPT_ARG_VAL:
225     case POPT_ARG_INT:
226 	le += sprintf(le, "%d", arg.intp[0]);
227 	break;
228     case POPT_ARG_SHORT:
229 	le += sprintf(le, "%hd", arg.shortp[0]);
230 	break;
231     case POPT_ARG_LONG:
232 	le += sprintf(le, "%ld", arg.longp[0]);
233 	break;
234     case POPT_ARG_LONGLONG:
235 	le += sprintf(le, "%lld", arg.longlongp[0]);
236 	break;
237     case POPT_ARG_FLOAT:
238     {	double aDouble = (double) arg.floatp[0];
239 	le += sprintf(le, "%g", aDouble);
240     }	break;
241     case POPT_ARG_DOUBLE:
242 	le += sprintf(le, "%g", arg.doublep[0]);
243 	break;
244     case POPT_ARG_MAINCALL:
245 	le += sprintf(le, "%p", opt->arg);
246 	break;
247     case POPT_ARG_ARGV:
248 	le += sprintf(le, "%p", opt->arg);
249 	break;
250     case POPT_ARG_STRING:
251     {	const char * s = arg.argv[0];
252 	if (s == NULL)
253 	    le = stpcpy(le, "null");
254 	else {
255 	    size_t limit = 4*lineLength - (le - l) - sizeof("\"\")");
256 	    size_t slen;
257 	    *le++ = '"';
258 	    strncpy(le, s, limit); le[limit] = '\0'; le += (slen = strlen(le));
259 	    if (slen == limit && s[limit])
260 		le[-1] = le[-2] = le[-3] = '.';
261 	    *le++ = '"';
262 	}
263     }	break;
264     case POPT_ARG_NONE:
265     default:
266 	l = _free(l);
267 	return NULL;
268 	break;
269     }
270   }
271     *le++ = ')';
272     *le = '\0';
273 
274     return l;
275 }
276 
277 /**
278  * Display help text for an option.
279  * @param fp		output file handle
280  * @param columns	output display width control
281  * @param opt		option(s)
282  * @param translation_domain	translation domain
283  */
singleOptionHelp(FILE * fp,columns_t columns,const struct poptOption * opt,const char * translation_domain)284 static void singleOptionHelp(FILE * fp, columns_t columns,
285 		const struct poptOption * opt,
286 		const char * translation_domain)
287 {
288     size_t maxLeftCol = columns->cur;
289     size_t indentLength = maxLeftCol + 5;
290     size_t lineLength = columns->max - indentLength;
291     const char * help = D_(translation_domain, opt->descrip);
292     const char * argDescrip = getArgDescrip(opt, translation_domain);
293     /* Display shortName iff printable non-space. */
294     int prtshort = (int)(isprint((int)opt->shortName) && opt->shortName != ' ');
295     size_t helpLength;
296     char * defs = NULL;
297     char * left;
298     size_t nb = maxLeftCol + 1;
299     int displaypad = 0;
300 
301     /* Make sure there's more than enough room in target buffer. */
302     if (opt->longName)	nb += strlen(opt->longName);
303     if (F_ISSET(opt, TOGGLE)) nb += sizeof("[no]") - 1;
304     if (argDescrip)	nb += strlen(argDescrip);
305 
306     left = malloc(nb);
307     if (left == NULL) return;	/* XXX can't happen */
308     left[0] = '\0';
309     left[maxLeftCol] = '\0';
310 
311 #define	prtlong	(opt->longName != NULL)	/* XXX splint needs a clue */
312     if (!(prtshort || prtlong))
313 	goto out;
314     if (prtshort && prtlong) {
315 	char *dash = F_ISSET(opt, ONEDASH) ? "-" : "--";
316 	left[0] = '-';
317 	left[1] = opt->shortName;
318 	(void) stpcpy(stpcpy(stpcpy(left+2, ", "), dash), opt->longName);
319     } else if (prtshort) {
320 	left[0] = '-';
321 	left[1] = opt->shortName;
322 	left[2] = '\0';
323     } else if (prtlong) {
324 	/* XXX --long always padded for alignment with/without "-X, ". */
325 	char *dash = poptArgType(opt) == POPT_ARG_MAINCALL ? ""
326 		   : (F_ISSET(opt, ONEDASH) ? "-" : "--");
327 	const char *longName = opt->longName;
328 	const char *toggle;
329 	if (F_ISSET(opt, TOGGLE)) {
330 	    toggle = "[no]";
331 	    if (longName[0] == 'n' && longName[1] == 'o') {
332 		longName += sizeof("no") - 1;
333 		if (longName[0] == '-')
334 		    longName++;
335 	    }
336 	} else
337 	    toggle = "";
338 	(void) stpcpy(stpcpy(stpcpy(stpcpy(left, "    "), dash), toggle), longName);
339     }
340 #undef	prtlong
341 
342     if (argDescrip) {
343 	char * le = left + strlen(left);
344 
345 	if (F_ISSET(opt, OPTIONAL))
346 	    *le++ = '[';
347 
348 	/* Choose type of output */
349 	if (F_ISSET(opt, SHOW_DEFAULT)) {
350 	    defs = singleOptionDefaultValue(lineLength, opt, translation_domain);
351 	    if (defs) {
352 		char * t = malloc((help ? strlen(help) : 0) +
353 				strlen(defs) + sizeof(" "));
354 		if (t) {
355 		    char * te = t;
356 		    if (help)
357 			te = stpcpy(te, help);
358 		    *te++ = ' ';
359 		    strcpy(te, defs);
360 		    defs = _free(defs);
361 		    defs = t;
362 		}
363 	    }
364 	}
365 
366 	if (opt->argDescrip == NULL) {
367 	    switch (poptArgType(opt)) {
368 	    case POPT_ARG_NONE:
369 		break;
370 	    case POPT_ARG_VAL:
371 #ifdef	NOTNOW	/* XXX pug ugly nerdy output */
372 	    {	long aLong = opt->val;
373 		int ops = F_ISSET(opt, LOGICALOPS);
374 		int negate = F_ISSET(opt, NOT);
375 
376 		/* Don't bother displaying typical values */
377 		if (!ops && (aLong == 0L || aLong == 1L || aLong == -1L))
378 		    break;
379 		*le++ = '[';
380 		switch (ops) {
381 		case POPT_ARGFLAG_OR:
382 		    *le++ = '|';
383 		    break;
384 		case POPT_ARGFLAG_AND:
385 		    *le++ = '&';
386 		    break;
387 		case POPT_ARGFLAG_XOR:
388 		    *le++ = '^';
389 		    break;
390 		default:
391 		    break;
392 		}
393 		*le++ = (opt->longName != NULL ? '=' : ' ');
394 		if (negate) *le++ = '~';
395 		le += sprintf(le, (ops ? "0x%lx" : "%ld"), aLong);
396 		*le++ = ']';
397 	    }
398 #endif
399 		break;
400 	    case POPT_ARG_INT:
401 	    case POPT_ARG_SHORT:
402 	    case POPT_ARG_LONG:
403 	    case POPT_ARG_LONGLONG:
404 	    case POPT_ARG_FLOAT:
405 	    case POPT_ARG_DOUBLE:
406 	    case POPT_ARG_STRING:
407 		*le++ = (opt->longName != NULL ? '=' : ' ');
408 		le = stpcpy(le, argDescrip);
409 		break;
410 	    default:
411 		break;
412 	    }
413 	} else {
414 	    char *leo;
415 
416 	    /* XXX argDescrip[0] determines "--foo=bar" or "--foo bar". */
417 	    if (!strchr(" =(", argDescrip[0]))
418 		*le++ = ((poptArgType(opt) == POPT_ARG_MAINCALL) ? ' ' :
419 			 (poptArgType(opt) == POPT_ARG_ARGV) ? ' ' : '=');
420 	    le = stpcpy(leo = le, argDescrip);
421 
422 	    /* Adjust for (possible) wide characters. */
423 	    displaypad = (int)((le - leo) - stringDisplayWidth(argDescrip));
424 	}
425 	if (F_ISSET(opt, OPTIONAL))
426 	    *le++ = ']';
427 	*le = '\0';
428     }
429 
430     if (help)
431 	POPT_fprintf(fp,"  %-*s   ", (int)(maxLeftCol+displaypad), left);
432     else {
433 	POPT_fprintf(fp,"  %s\n", left);
434 	goto out;
435     }
436 
437     left = _free(left);
438     if (defs)
439 	help = defs;
440 
441     helpLength = strlen(help);
442     while (helpLength > lineLength) {
443 	const char * ch;
444 	char format[16];
445 
446 	ch = help + lineLength - 1;
447 	while (ch > help && !_isspaceptr(ch))
448 	    ch = POPT_prev_char(ch);
449 	if (ch == help) break;		/* give up */
450 	while (ch > (help + 1) && _isspaceptr(ch))
451 	    ch = POPT_prev_char (ch);
452 	ch = POPT_next_char(ch);
453 
454 	/*
455 	 *  XXX strdup is necessary to add NUL terminator so that an unknown
456 	 *  no. of (possible) multi-byte characters can be displayed.
457 	 */
458 	{   char * fmthelp = xstrdup(help);
459 	    if (fmthelp) {
460 		fmthelp[ch - help] = '\0';
461 		sprintf(format, "%%s\n%%%ds", (int) indentLength);
462 		POPT_fprintf(fp, format, fmthelp, " ");
463 		free(fmthelp);
464 	    }
465 	}
466 
467 	help = ch;
468 	while (_isspaceptr(help) && *help)
469 	    help = POPT_next_char(help);
470 	helpLength = strlen(help);
471     }
472 
473     if (helpLength) fprintf(fp, "%s\n", help);
474     help = NULL;
475 
476 out:
477     defs = _free(defs);
478     left = _free(left);
479 }
480 
481 /**
482  * Find display width for longest argument string.
483  * @param opt		option(s)
484  * @param translation_domain	translation domain
485  * @return		display width
486  */
maxArgWidth(const struct poptOption * opt,const char * translation_domain)487 static size_t maxArgWidth(const struct poptOption * opt,
488 		       const char * translation_domain)
489 {
490     size_t max = 0;
491     size_t len = 0;
492     const char * argDescrip;
493 
494     if (opt != NULL)
495     while (opt->longName || opt->shortName || opt->arg) {
496 	if (poptArgType(opt) == POPT_ARG_INCLUDE_TABLE) {
497 	    void * arg = opt->arg;
498 	    /* XXX sick hack to preserve pretense of ABI. */
499 	    if (arg == poptHelpOptions)
500 		arg = poptHelpOptionsI18N;
501 	    if (arg)	/* XXX program error */
502 		len = maxArgWidth(arg, translation_domain);
503 	    if (len > max) max = len;
504 	} else if (!F_ISSET(opt, DOC_HIDDEN)) {
505 	    len = sizeof("  ")-1;
506 	    /* XXX --long always padded for alignment with/without "-X, ". */
507 	    len += sizeof("-X, ")-1;
508 	    if (opt->longName) {
509 		len += (F_ISSET(opt, ONEDASH) ? sizeof("-") : sizeof("--")) - 1;
510 		len += strlen(opt->longName);
511 	    }
512 
513 	    argDescrip = getArgDescrip(opt, translation_domain);
514 
515 	    if (argDescrip) {
516 
517 		/* XXX argDescrip[0] determines "--foo=bar" or "--foo bar". */
518 		if (!strchr(" =(", argDescrip[0])) len += sizeof("=")-1;
519 
520 		/* Adjust for (possible) wide characters. */
521 		len += stringDisplayWidth(argDescrip);
522 	    }
523 
524 	    if (F_ISSET(opt, OPTIONAL)) len += sizeof("[]")-1;
525 	    if (len > max) max = len;
526 	}
527 	opt++;
528     }
529 
530     return max;
531 }
532 
533 /**
534  * Display popt alias and exec help.
535  * @param fp		output file handle
536  * @param items		alias/exec array
537  * @param nitems	no. of alias/exec entries
538  * @param columns	output display width control
539  * @param translation_domain	translation domain
540  */
itemHelp(FILE * fp,poptItem items,int nitems,columns_t columns,const char * translation_domain)541 static void itemHelp(FILE * fp,
542 		poptItem items, int nitems,
543 		columns_t columns,
544 		const char * translation_domain)
545 {
546     poptItem item;
547     int i;
548 
549     if (items != NULL)
550     for (i = 0, item = items; i < nitems; i++, item++) {
551 	const struct poptOption * opt;
552 	opt = &item->option;
553 	if ((opt->longName || opt->shortName) && !F_ISSET(opt, DOC_HIDDEN))
554 	    singleOptionHelp(fp, columns, opt, translation_domain);
555     }
556 }
557 
558 /**
559  * Display help text for a table of options.
560  * @param con		context
561  * @param fp		output file handle
562  * @param table		option(s)
563  * @param columns	output display width control
564  * @param translation_domain	translation domain
565  */
singleTableHelp(poptContext con,FILE * fp,const struct poptOption * table,columns_t columns,const char * translation_domain)566 static void singleTableHelp(poptContext con, FILE * fp,
567 		const struct poptOption * table,
568 		columns_t columns,
569 		const char * translation_domain)
570 {
571     const struct poptOption * opt;
572     const char *sub_transdom;
573 
574     if (table == poptAliasOptions) {
575 	itemHelp(fp, con->aliases, con->numAliases, columns, NULL);
576 	itemHelp(fp, con->execs, con->numExecs, columns, NULL);
577 	return;
578     }
579 
580     if (table != NULL)
581     for (opt = table; opt->longName || opt->shortName || opt->arg; opt++) {
582 	if ((opt->longName || opt->shortName) && !F_ISSET(opt, DOC_HIDDEN))
583 	    singleOptionHelp(fp, columns, opt, translation_domain);
584     }
585 
586     if (table != NULL)
587     for (opt = table; opt->longName || opt->shortName || opt->arg; opt++) {
588 	void * arg = opt->arg;
589 	if (poptArgType(opt) != POPT_ARG_INCLUDE_TABLE)
590 	    continue;
591 	/* XXX sick hack to preserve pretense of ABI. */
592 	if (arg == poptHelpOptions)
593 	    arg = poptHelpOptionsI18N;
594 	sub_transdom = getTableTranslationDomain(arg);
595 	if (sub_transdom == NULL)
596 	    sub_transdom = translation_domain;
597 
598 	/* If no popt aliases/execs, skip poptAliasOption processing. */
599 	if (arg == poptAliasOptions && !(con->numAliases || con->numExecs))
600 	    continue;
601 	if (opt->descrip)
602 	    POPT_fprintf(fp, "\n%s\n", D_(sub_transdom, opt->descrip));
603 
604 	singleTableHelp(con, fp, arg, columns, sub_transdom);
605     }
606 }
607 
608 /**
609  * @param con		context
610  * @param fp		output file handle
611  */
showHelpIntro(poptContext con,FILE * fp)612 static size_t showHelpIntro(poptContext con, FILE * fp)
613 {
614     size_t len = (size_t)6;
615 
616     POPT_fprintf(fp, POPT_("Usage:"));
617     if (!(con->flags & POPT_CONTEXT_KEEP_FIRST)) {
618 	struct optionStackEntry * os = con->optionStack;
619 	const char * fn = (os->argv ? os->argv[0] : NULL);
620 	if (fn == NULL) return len;
621 	if (strchr(fn, '/')) fn = strrchr(fn, '/') + 1;
622 	/* XXX POPT_fprintf not needed for argv[0] display. */
623 	fprintf(fp, " %s", fn);
624 	len += strlen(fn) + 1;
625     }
626 
627     return len;
628 }
629 
poptPrintHelp(poptContext con,FILE * fp,UNUSED (int flags))630 void poptPrintHelp(poptContext con, FILE * fp, UNUSED(int flags))
631 {
632     columns_t columns = calloc((size_t)1, sizeof(*columns));
633 
634     (void) showHelpIntro(con, fp);
635     if (con->otherHelp)
636 	POPT_fprintf(fp, " %s\n", con->otherHelp);
637     else
638 	POPT_fprintf(fp, " %s\n", POPT_("[OPTION...]"));
639 
640     if (columns) {
641 	columns->cur = maxArgWidth(con->options, NULL);
642 	columns->max = maxColumnWidth(fp);
643 	singleTableHelp(con, fp, con->options, columns, NULL);
644 	free(columns);
645     }
646 }
647 
648 /**
649  * Display usage text for an option.
650  * @param fp		output file handle
651  * @param columns	output display width control
652  * @param opt		option(s)
653  * @param translation_domain	translation domain
654  */
singleOptionUsage(FILE * fp,columns_t columns,const struct poptOption * opt,const char * translation_domain)655 static size_t singleOptionUsage(FILE * fp, columns_t columns,
656 		const struct poptOption * opt,
657 		const char *translation_domain)
658 {
659     size_t len = sizeof(" []")-1;
660     const char * argDescrip = getArgDescrip(opt, translation_domain);
661     /* Display shortName iff printable non-space. */
662     int prtshort = (int)(isprint((int)opt->shortName) && opt->shortName != ' ');
663 
664 #define	prtlong	(opt->longName != NULL)	/* XXX splint needs a clue */
665     if (!(prtshort || prtlong))
666 	return columns->cur;
667 
668     len = sizeof(" []")-1;
669     if (prtshort)
670 	len += sizeof("-c")-1;
671     if (prtlong) {
672 	if (prtshort) len += sizeof("|")-1;
673 	len += (F_ISSET(opt, ONEDASH) ? sizeof("-") : sizeof("--")) - 1;
674 	len += strlen(opt->longName);
675     }
676 
677     if (argDescrip) {
678 
679 	/* XXX argDescrip[0] determines "--foo=bar" or "--foo bar". */
680 	if (!strchr(" =(", argDescrip[0])) len += sizeof("=")-1;
681 
682 	/* Adjust for (possible) wide characters. */
683 	len += stringDisplayWidth(argDescrip);
684     }
685 
686     if ((columns->cur + len) > columns->max) {
687 	fprintf(fp, "\n       ");
688 	columns->cur = (size_t)7;
689     }
690 
691     fprintf(fp, " [");
692     if (prtshort)
693 	fprintf(fp, "-%c", opt->shortName);
694     if (prtlong)
695 	fprintf(fp, "%s%s%s",
696 		(prtshort ? "|" : ""),
697 		(F_ISSET(opt, ONEDASH) ? "-" : "--"),
698 		opt->longName);
699 #undef	prtlong
700 
701     if (argDescrip) {
702 	/* XXX argDescrip[0] determines "--foo=bar" or "--foo bar". */
703 	if (!strchr(" =(", argDescrip[0])) fprintf(fp, "=");
704 	fprintf(fp, "%s", argDescrip);
705     }
706     fprintf(fp, "]");
707 
708     return columns->cur + len + 1;
709 }
710 
711 /**
712  * Display popt alias and exec usage.
713  * @param fp		output file handle
714  * @param columns	output display width control
715  * @param item		alias/exec array
716  * @param nitems	no. of ara/exec entries
717  * @param translation_domain	translation domain
718  */
itemUsage(FILE * fp,columns_t columns,poptItem item,int nitems,const char * translation_domain)719 static size_t itemUsage(FILE * fp, columns_t columns,
720 		poptItem item, int nitems,
721 		const char * translation_domain)
722 {
723     int i;
724 
725     if (item != NULL)
726     for (i = 0; i < nitems; i++, item++) {
727 	const struct poptOption * opt;
728 	opt = &item->option;
729         if (poptArgType(opt) == POPT_ARG_INTL_DOMAIN) {
730 	    translation_domain = (const char *)opt->arg;
731 	} else
732 	if ((opt->longName || opt->shortName) && !F_ISSET(opt, DOC_HIDDEN)) {
733 	    columns->cur = singleOptionUsage(fp, columns, opt, translation_domain);
734 	}
735     }
736 
737     return columns->cur;
738 }
739 
740 /**
741  * Keep track of option tables already processed.
742  */
743 typedef struct poptDone_s {
744     int nopts;
745     int maxopts;
746     const void ** opts;
747 } * poptDone;
748 
749 /**
750  * Display usage text for a table of options.
751  * @param con		context
752  * @param fp		output file handle
753  * @param columns	output display width control
754  * @param opt		option(s)
755  * @param translation_domain	translation domain
756  * @param done		tables already processed
757  * @return
758  */
singleTableUsage(poptContext con,FILE * fp,columns_t columns,const struct poptOption * opt,const char * translation_domain,poptDone done)759 static size_t singleTableUsage(poptContext con, FILE * fp, columns_t columns,
760 		const struct poptOption * opt,
761 		const char * translation_domain,
762 		poptDone done)
763 {
764     if (opt != NULL)
765     for (; (opt->longName || opt->shortName || opt->arg) ; opt++) {
766         if (poptArgType(opt) == POPT_ARG_INTL_DOMAIN) {
767 	    translation_domain = (const char *)opt->arg;
768 	} else
769 	if (poptArgType(opt) == POPT_ARG_INCLUDE_TABLE) {
770 	    void * arg = opt->arg;
771 	    /* XXX sick hack to preserve pretense of ABI. */
772 	    if (arg == poptHelpOptions)
773 		arg = poptHelpOptionsI18N;
774 	    if (done) {
775 		int i = 0;
776 		if (done->opts != NULL)
777 		for (i = 0; i < done->nopts; i++) {
778 		    const void * that = done->opts[i];
779 		    if (that == NULL || that != arg)
780 			continue;
781 		    break;
782 		}
783 		/* Skip if this table has already been processed. */
784 		if (arg == NULL || i < done->nopts)
785 		    continue;
786 		if (done->opts != NULL && done->nopts < done->maxopts)
787 		    done->opts[done->nopts++] = (const void *) arg;
788 	    }
789 	    columns->cur = singleTableUsage(con, fp, columns, opt->arg,
790 			translation_domain, done);
791 	} else
792 	if ((opt->longName || opt->shortName) && !F_ISSET(opt, DOC_HIDDEN)) {
793 	    columns->cur = singleOptionUsage(fp, columns, opt, translation_domain);
794 	}
795     }
796 
797     return columns->cur;
798 }
799 
800 /**
801  * Return concatenated short options for display.
802  * @todo Sub-tables should be recursed.
803  * @param opt		option(s)
804  * @param fp		output file handle
805  * @retval str		concatenation of short options
806  * @return		length of display string
807  */
showShortOptions(const struct poptOption * opt,FILE * fp,char * str)808 static size_t showShortOptions(const struct poptOption * opt, FILE * fp,
809 		char * str)
810 {
811     /* bufsize larger then the ascii set, lazy allocation on top level call. */
812     size_t nb = (size_t)300;
813     char * s = (str != NULL ? str : calloc((size_t)1, nb));
814     size_t len = (size_t)0;
815 
816     if (s == NULL)
817 	return 0;
818 
819     if (opt != NULL)
820     for (; (opt->longName || opt->shortName || opt->arg); opt++) {
821 	if (!F_ISSET(opt, DOC_HIDDEN) && opt->shortName && !poptArgType(opt))
822 	{
823 	    /* Display shortName iff unique printable non-space. */
824 	    if (!strchr(s, opt->shortName) && isprint((int)opt->shortName)
825 	     && opt->shortName != ' ')
826 		s[strlen(s)] = opt->shortName;
827 	} else if (poptArgType(opt) == POPT_ARG_INCLUDE_TABLE) {
828 	    void * arg = opt->arg;
829 	    /* XXX sick hack to preserve pretense of ABI. */
830 	    if (arg == poptHelpOptions)
831 		arg = poptHelpOptionsI18N;
832 	    if (arg)	/* XXX program error */
833 		len = showShortOptions(arg, fp, s);
834 	}
835     }
836 
837     /* On return to top level, print the short options, return print length. */
838     if (s != str && *s != '\0') {
839 	fprintf(fp, " [-%s]", s);
840 	len = strlen(s) + sizeof(" [-]")-1;
841     }
842     if (s != str)
843 	free(s);
844     return len;
845 }
846 
poptPrintUsage(poptContext con,FILE * fp,UNUSED (int flags))847 void poptPrintUsage(poptContext con, FILE * fp, UNUSED(int flags))
848 {
849     columns_t columns = calloc((size_t)1, sizeof(*columns));
850     struct poptDone_s done_buf;
851     poptDone done = &done_buf;
852 
853     memset(done, 0, sizeof(*done));
854     done->nopts = 0;
855     done->maxopts = 64;
856   if (columns) {
857     columns->cur = done->maxopts * sizeof(*done->opts);
858     columns->max = maxColumnWidth(fp);
859     done->opts = calloc((size_t)1, columns->cur);
860     if (done->opts != NULL)
861 	done->opts[done->nopts++] = (const void *) con->options;
862 
863     columns->cur = showHelpIntro(con, fp);
864     columns->cur += showShortOptions(con->options, fp, NULL);
865     columns->cur = singleTableUsage(con, fp, columns, con->options, NULL, done);
866     columns->cur = itemUsage(fp, columns, con->aliases, con->numAliases, NULL);
867     columns->cur = itemUsage(fp, columns, con->execs, con->numExecs, NULL);
868 
869     if (con->otherHelp) {
870 	columns->cur += strlen(con->otherHelp) + 1;
871 	if (columns->cur > columns->max) fprintf(fp, "\n       ");
872 	fprintf(fp, " %s", con->otherHelp);
873     }
874 
875     fprintf(fp, "\n");
876     if (done->opts != NULL)
877 	free(done->opts);
878     free(columns);
879   }
880 }
881 
poptSetOtherOptionHelp(poptContext con,const char * text)882 void poptSetOtherOptionHelp(poptContext con, const char * text)
883 {
884     con->otherHelp = _free(con->otherHelp);
885     con->otherHelp = xstrdup(text);
886 }
887