test harness: improve catching of usage errors in script 'test-driver'
[platform/upstream/automake.git] / doc / help2man
1 #!/usr/bin/perl -w
2
3 # Generate a short man page from --help and --version output.
4 # Copyright (C) 1997-2013 Free Software Foundation, Inc.
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3, or (at your option)
9 # any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, see <http://www.gnu.org/licenses/>.
18
19 # Written by Brendan O'Dea <bod@debian.org>
20 # Available from ftp://ftp.gnu.org/gnu/help2man/
21
22 use 5.006;
23 use strict;
24 use Getopt::Long;
25 use Text::Tabs qw(expand);
26 use POSIX qw(strftime setlocale LC_ALL);
27
28 my $this_program = 'help2man';
29 my $this_version = '1.40.8';
30
31 sub _ { $_[0] }
32 sub configure_locale
33 {
34     my $locale = shift;
35     die "$this_program: no locale support (Locale::gettext required)\n"
36         unless $locale eq 'C';
37 }
38
39 sub dec { $_[0] }
40 sub enc { $_[0] }
41 sub enc_user { $_[0] }
42 sub kark { die +(sprintf shift, @_), "\n" }
43 sub N_ { $_[0] }
44
45 my $version_info = enc_user sprintf _(<<'EOT'), $this_program, $this_version;
46 GNU %s %s
47
48 Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2009, 2010,
49 2011, 2012 Free Software Foundation, Inc.
50 This is free software; see the source for copying conditions.  There is NO
51 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
52
53 Written by Brendan O'Dea <bod@debian.org>
54 EOT
55
56 my $help_info = enc_user sprintf _(<<'EOT'), $this_program, $this_program;
57 `%s' generates a man page out of `--help' and `--version' output.
58
59 Usage: %s [OPTION]... EXECUTABLE
60
61  -n, --name=STRING       description for the NAME paragraph
62  -s, --section=SECTION   section number for manual page (1, 6, 8)
63  -m, --manual=TEXT       name of manual (User Commands, ...)
64  -S, --source=TEXT       source of program (FSF, Debian, ...)
65  -L, --locale=STRING     select locale (default "C")
66  -i, --include=FILE      include material from `FILE'
67  -I, --opt-include=FILE  include material from `FILE' if it exists
68  -o, --output=FILE       send output to `FILE'
69  -p, --info-page=TEXT    name of Texinfo manual
70  -N, --no-info           suppress pointer to Texinfo manual
71  -l, --libtool           exclude the `lt-' from the program name
72      --help              print this help, then exit
73      --version           print version number, then exit
74
75 EXECUTABLE should accept `--help' and `--version' options and produce output on
76 stdout although alternatives may be specified using:
77
78  -h, --help-option=STRING     help option string
79  -v, --version-option=STRING  version option string
80  --version-string=STRING      version string
81  --no-discard-stderr          include stderr when parsing option output
82
83 Report bugs to <bug-help2man@gnu.org>.
84 EOT
85
86 my $section = 1;
87 my $manual = '';
88 my $source = '';
89 my $help_option = '--help';
90 my $version_option = '--version';
91 my $discard_stderr = 1;
92 my ($opt_name, @opt_include, $opt_output, $opt_info, $opt_no_info, $opt_libtool,
93     $version_text);
94
95 my %opt_def = (
96     'n|name=s'           => \$opt_name,
97     's|section=s'        => \$section,
98     'm|manual=s'         => \$manual,
99     'S|source=s'         => \$source,
100     'L|locale=s'         => sub { configure_locale pop },
101     'i|include=s'        => sub { push @opt_include, [ pop, 1 ] },
102     'I|opt-include=s'    => sub { push @opt_include, [ pop, 0 ] },
103     'o|output=s'         => \$opt_output,
104     'p|info-page=s'      => \$opt_info,
105     'N|no-info'          => \$opt_no_info,
106     'l|libtool'          => \$opt_libtool,
107     'help'               => sub { print $help_info; exit },
108     'version'            => sub { print $version_info; exit },
109     'h|help-option=s'    => \$help_option,
110     'v|version-option=s' => \$version_option,
111     'version-string=s'   => \$version_text,
112     'discard-stderr!'    => \$discard_stderr,
113 );
114
115 # Parse options.
116 Getopt::Long::config('bundling');
117 die $help_info unless GetOptions %opt_def and @ARGV == 1;
118
119 my %include = ();
120 my %append = ();
121 my @include = (); # retain order given in include file
122
123 # Process include file (if given).  Format is:
124 #
125 #   [section name]
126 #   verbatim text
127 #
128 # or
129 #
130 #   /pattern/
131 #   verbatim text
132 #
133
134 while (@opt_include)
135 {
136     my ($inc, $required) = @{shift @opt_include};
137
138     next unless -f $inc or $required;
139     kark N_("%s: can't open `%s' (%s)"), $this_program, $inc, $!
140         unless open INC, $inc;
141
142     my $key;
143     my $hash = \%include;
144
145     while (<INC>)
146     {
147         # Convert input to internal Perl format, so that multibyte
148         # sequences are treated as single characters.
149         $_ = dec $_;
150
151         # [section]
152         if (/^\[([^]]+)\]\s*$/)
153         {
154             $key = uc $1;
155             $key =~ s/^\s+//;
156             $key =~ s/\s+$//;
157             $hash = \%include;
158             push @include, $key unless $include{$key};
159             next;
160         }
161
162         # /pattern/
163         if (m!^/(.*)/([ims]*)\s*$!)
164         {
165             my $pat = $2 ? "(?$2)$1" : $1;
166
167             # Check pattern.
168             eval { $key = qr($pat) };
169             if ($@)
170             {
171                 $@ =~ s/ at .*? line \d.*//;
172                 die "$inc:$.:$@";
173             }
174
175             $hash = \%append;
176             next;
177         }
178
179         # Check for options before the first section--anything else is
180         # silently ignored, allowing the first for comments and
181         # revision info.
182         unless ($key)
183         {
184             # handle options
185             if (/^-/)
186             {
187                 local @ARGV = split;
188                 GetOptions %opt_def;
189             }
190
191             next;
192         }
193
194         $hash->{$key} ||= '';
195         $hash->{$key} .= $_;
196     }
197
198     close INC;
199
200     kark N_("%s: no valid information found in `%s'"), $this_program, $inc
201         unless $key;
202 }
203
204 # Compress trailing blank lines.
205 for my $hash (\(%include, %append))
206 {
207     for (keys %$hash) { $hash->{$_} =~ s/\n+$/\n/ }
208 }
209
210 sub get_option_value;
211
212 # Grab help and version info from executable.
213 my $help_text   = get_option_value $ARGV[0], $help_option;
214 $version_text ||= get_option_value $ARGV[0], $version_option;
215
216 # Translators: the following message is a strftime(3) format string, which in
217 # the English version expands to the month as a word and the full year.  It
218 # is used on the footer of the generated manual pages.  If in doubt, you may
219 # just use %x as the value (which should be the full locale-specific date).
220 my $date = enc strftime _("%B %Y"), localtime;
221 (my $program = $ARGV[0]) =~ s!.*/!!;
222 my $package = $program;
223 my $version;
224
225 if ($opt_output)
226 {
227     unlink $opt_output or kark N_("%s: can't unlink %s (%s)"),
228         $this_program, $opt_output, $! if -e $opt_output;
229
230     open STDOUT, ">$opt_output"
231         or kark N_("%s: can't create %s (%s)"), $this_program, $opt_output, $!;
232 }
233
234 # The first line of the --version information is assumed to be in one
235 # of the following formats:
236 #
237 #   <version>
238 #   <program> <version>
239 #   {GNU,Free} <program> <version>
240 #   <program> ({GNU,Free} <package>) <version>
241 #   <program> - {GNU,Free} <package> <version>
242 #
243 # and separated from any copyright/author details by a blank line.
244
245 ($_, $version_text) = ((split /\n+/, $version_text, 2), '');
246
247 if (/^(\S+) +\(((?:GNU|Free) +[^)]+)\) +(.*)/ or
248     /^(\S+) +- *((?:GNU|Free) +\S+) +(.*)/)
249 {
250     $program = $1;
251     $package = $2;
252     $version = $3;
253 }
254 elsif (/^((?:GNU|Free) +)?(\S+) +(.*)/)
255 {
256     $program = $2;
257     $package = $1 ? "$1$2" : $2;
258     $version = $3;
259 }
260 else
261 {
262     $version = $_;
263 }
264
265 $program =~ s!.*/!!;
266
267 # No info for `info' itself.
268 $opt_no_info = 1 if $program eq 'info';
269
270 # Translators: "NAME", "SYNOPSIS" and other one or two word strings in all
271 # upper case are manual page section headings.  The man(1) manual page in your
272 # language, if available should provide the conventional translations.
273 for ($include{_('NAME')})
274 {
275     if ($opt_name) # --name overrides --include contents.
276     {
277         $_ = "$program \\- $opt_name\n";
278     }
279     elsif ($_) # Use first name given as $program
280     {
281         $program = $1 if /^([^\s,]+)(?:,?\s*[^\s,\\-]+)*\s+\\?-/;
282     }
283     else # Set a default (useless) NAME paragraph.
284     {
285         $_ = sprintf _("%s \\- manual page for %s %s") . "\n", $program,
286             $program, $version;
287     }
288 }
289
290 # Man pages traditionally have the page title in caps.
291 my $PROGRAM = uc $program;
292
293 # Set default page head/footers
294 $source ||= "$program $version";
295 unless ($manual)
296 {
297     for ($section)
298     {
299         if (/^(1[Mm]|8)/) { $manual = enc _('System Administration Utilities') }
300         elsif (/^6/)      { $manual = enc _('Games') }
301         else              { $manual = enc _('User Commands') }
302     }
303 }
304
305 # Extract usage clause(s) [if any] for SYNOPSIS.
306 # Translators: "Usage" and "or" here are patterns (regular expressions) which
307 # are used to match the usage synopsis in program output.  An example from cp
308 # (GNU coreutils) which contains both strings:
309 #  Usage: cp [OPTION]... [-T] SOURCE DEST
310 #    or:  cp [OPTION]... SOURCE... DIRECTORY
311 #    or:  cp [OPTION]... -t DIRECTORY SOURCE...
312 my $PAT_USAGE = _('Usage');
313 my $PAT_USAGE_CONT = _('or');
314 if ($help_text =~ s/^($PAT_USAGE):( +(\S+))(.*)((?:\n(?: {6}\1| *($PAT_USAGE_CONT): +\S).*)*)//om)
315 {
316     my @syn = $3 . $4;
317
318     if ($_ = $5)
319     {
320         s/^\n//;
321         for (split /\n/) { s/^ *(($PAT_USAGE_CONT): +)?//o; push @syn, $_ }
322     }
323
324     my $synopsis = '';
325     for (@syn)
326     {
327         $synopsis .= ".br\n" if $synopsis;
328         s!^\S*/!!;
329         s/^lt-// if $opt_libtool;
330         s/^(\S+) *//;
331         $synopsis .= ".B $1\n";
332         s/\s+$//;
333         s/(([][]|\.\.+)+)/\\fR$1\\fI/g;
334         s/^/\\fI/ unless s/^\\fR//;
335         $_ .= '\fR';
336         s/(\\fI)( *)/$2$1/g;
337         s/\\fI\\fR//g;
338         s/^\\fR//;
339         s/\\fI$//;
340         s/^\./\\&./;
341
342         $synopsis .= "$_\n";
343     }
344
345     $include{_('SYNOPSIS')} ||= $synopsis;
346 }
347
348 # Process text, initial section is DESCRIPTION.
349 my $sect = _('DESCRIPTION');
350 $_ = "$help_text\n\n$version_text";
351
352 # Normalise paragraph breaks.
353 s/^\n+//;
354 s/\n*$/\n/;
355 s/\n\n+/\n\n/g;
356
357 # Join hyphenated lines.
358 s/([A-Za-z])-\n *([A-Za-z])/$1$2/g;
359
360 # Temporarily exchange leading dots, apostrophes and backslashes for
361 # tokens.
362 s/^\./\x80/mg;
363 s/^'/\x81/mg;
364 s/\\/\x82/g;
365
366 # Translators: patterns are used to match common program output. In the source
367 # these strings are all of the form of "my $PAT_something = _('...');" and are
368 # regular expressions.  If there is more than one commonly used string, you
369 # may separate alternatives with "|".  Spaces in these expressions are written
370 # as " +" to indicate that more than one space may be matched.  The string
371 # "(?:[\\w-]+ +)?" in the bug reporting pattern is used to indicate an
372 # optional word, so that either "Report bugs" or "Report _program_ bugs" will
373 # be matched.
374 my $PAT_BUGS            = _('Report +(?:[\w-]+ +)?bugs|Email +bug +reports +to');
375 my $PAT_AUTHOR          = _('Written +by');
376 my $PAT_OPTIONS         = _('Options');
377 my $PAT_ENVIRONMENT     = _('Environment');
378 my $PAT_FILES           = _('Files');
379 my $PAT_EXAMPLES        = _('Examples');
380 my $PAT_FREE_SOFTWARE   = _('This +is +free +software');
381
382 # Start a new paragraph (if required) for these.
383 s/([^\n])\n($PAT_BUGS|$PAT_AUTHOR) /$1\n\n$2 /og;
384
385 # Convert iso-8859-1 copyright symbol or (c) to nroff
386 # character.
387 s/^Copyright +(?:\xa9|\([Cc]\))/Copyright \\(co/mg;
388
389 sub convert_option;
390
391 while (length)
392 {
393     # Convert some standard paragraph names.
394     if (s/^($PAT_OPTIONS): *\n//o)
395     {
396         $sect = _('OPTIONS');
397         next;
398     }
399     if (s/^($PAT_ENVIRONMENT): *\n//o)
400     {
401         $sect = _('ENVIRONMENT');
402         next;
403     }
404     if (s/^($PAT_FILES): *\n//o)
405     {
406         $sect = _('FILES');
407         next;
408     }
409     elsif (s/^($PAT_EXAMPLES): *\n//o)
410     {
411         $sect = _('EXAMPLES');
412         next;
413     }
414
415     # Copyright section
416     if (/^Copyright /)
417     {
418         $sect = _('COPYRIGHT');
419     }
420
421     # Bug reporting section.
422     elsif (/^($PAT_BUGS) /o)
423     {
424         $sect = _('REPORTING BUGS');
425     }
426
427     # Author section.
428     elsif (/^($PAT_AUTHOR)/o)
429     {
430         $sect = _('AUTHOR');
431     }
432
433     # Examples, indicated by an indented leading $, % or > are
434     # rendered in a constant width font.
435     if (/^( +)([\$\%>] )\S/)
436     {
437         my $indent = $1;
438         my $prefix = $2;
439         my $break = '.IP';
440         $include{$sect} ||= '';
441         while (s/^$indent\Q$prefix\E(\S.*)\n*//)
442         {
443             $include{$sect} .= "$break\n\\f(CW$prefix$1\\fR\n";
444             $break = '.br';
445         }
446
447         next;
448     }
449
450     my $matched = '';
451     $include{$sect} ||= '';
452
453     # Sub-sections have a trailing colon and the second line indented.
454     if (s/^(\S.*:) *\n / /)
455     {
456         $matched .= $& if %append;
457         $include{$sect} .= qq(.SS "$1"\n);
458     }
459
460     my $indent = 0;
461     my $content = '';
462
463     # Option with description.
464     if (s/^( {1,10}([+-]\S.*?))(?:(  +(?!-))|\n( {20,}))(\S.*)\n//)
465     {
466         $matched .= $& if %append;
467         $indent = length ($4 || "$1$3");
468         $content = ".TP\n\x84$2\n\x84$5\n";
469         unless ($4)
470         {
471             # Indent may be different on second line.
472             $indent = length $& if /^ {20,}/;
473         }
474     }
475
476     # Option without description.
477     elsif (s/^ {1,10}([+-]\S.*)\n//)
478     {
479         $matched .= $& if %append;
480         $content = ".HP\n\x84$1\n";
481         $indent = 80; # not continued
482     }
483
484     # Indented paragraph with tag.
485     elsif (s/^( +(\S.*?)  +)(\S.*)\n//)
486     {
487         $matched .= $& if %append;
488         $indent = length $1;
489         $content = ".TP\n\x84$2\n\x84$3\n";
490     }
491
492     # Indented paragraph.
493     elsif (s/^( +)(\S.*)\n//)
494     {
495         $matched .= $& if %append;
496         $indent = length $1;
497         $content = ".IP\n\x84$2\n";
498     }
499
500     # Left justified paragraph.
501     else
502     {
503         s/(.*)\n//;
504         $matched .= $& if %append;
505         $content = ".PP\n" if $include{$sect};
506         $content .= "$1\n";
507     }
508
509     # Append continuations.
510     while ($indent ? s/^ {$indent}(\S.*)\n// : s/^(\S.*)\n//)
511     {
512         $matched .= $& if %append;
513         $content .= "\x84$1\n";
514     }
515
516     # Move to next paragraph.
517     s/^\n+//;
518
519     for ($content)
520     {
521         # Leading dot and apostrophe protection.
522         s/\x84\./\x80/g;
523         s/\x84'/\x81/g;
524         s/\x84//g;
525
526         # Convert options.
527         s/(^| |\()(-[][\w=-]+)/$1 . convert_option $2/mge;
528
529         # Escape remaining hyphens
530         s/-/\x83/g;
531
532         if ($sect eq 'COPYRIGHT')
533         {
534             # Insert line breaks before additional copyright messages
535             # and the disclaimer.
536             s/\n(Copyright |$PAT_FREE_SOFTWARE)/\n.br\n$1/og;
537         }
538         elsif ($sect eq 'REPORTING BUGS')
539         {
540             # Handle multi-line bug reporting sections of the form:
541             #
542             #   Report <program> bugs to <addr>
543             #   GNU <package> home page: <url>
544             #   ...
545             s/\n([[:upper:]])/\n.br\n$1/g;
546         }
547     }
548
549     # Check if matched paragraph contains /pat/.
550     if (%append)
551     {
552         for my $pat (keys %append)
553         {
554             if ($matched =~ $pat)
555             {
556                 $content .= ".PP\n" unless $append{$pat} =~ /^\./;
557                 $content .= $append{$pat};
558             }
559         }
560     }
561
562     $include{$sect} .= $content;
563 }
564
565 # Refer to the real documentation.
566 unless ($opt_no_info)
567 {
568     my $info_page = $opt_info || $program;
569
570     $sect = _('SEE ALSO');
571     $include{$sect} ||= '';
572     $include{$sect} .= ".PP\n" if $include{$sect};
573     $include{$sect} .= sprintf _(<<'EOT'), $program, $program, $info_page;
574 The full documentation for
575 .B %s
576 is maintained as a Texinfo manual.  If the
577 .B info
578 and
579 .B %s
580 programs are properly installed at your site, the command
581 .IP
582 .B info %s
583 .PP
584 should give you access to the complete manual.
585 EOT
586 }
587
588 # Output header.
589 print <<EOT;
590 .\\" DO NOT MODIFY THIS FILE!  It was generated by $this_program $this_version.
591 .TH $PROGRAM "$section" "$date" "$source" "$manual"
592 EOT
593
594 # Section ordering.
595 my @pre = (_('NAME'), _('SYNOPSIS'), _('DESCRIPTION'), _('OPTIONS'),
596     _('ENVIRONMENT'), _('FILES'), _('EXAMPLES'));
597
598 my @post = (_('AUTHOR'), _('REPORTING BUGS'), _('COPYRIGHT'), _('SEE ALSO'));
599 my $filter = join '|', @pre, @post;
600
601 # Output content.
602 for my $sect (@pre, (grep ! /^($filter)$/o, @include), @post)
603 {
604     if ($include{$sect})
605     {
606         my $quote = $sect =~ /\W/ ? '"' : '';
607         print enc ".SH $quote$sect$quote\n";
608
609         for ($include{$sect})
610         {
611             # Replace leading dot, apostrophe, backslash and hyphen
612             # tokens.
613             s/\x80/\\&./g;
614             s/\x81/\\&'/g;
615             s/\x82/\\e/g;
616             s/\x83/\\-/g;
617
618             # Convert some latin1 chars to troff equivalents
619             s/\xa0/\\ /g; # non-breaking space
620
621             print enc $_;
622         }
623     }
624 }
625
626 close STDOUT or kark N_("%s: error writing to %s (%s)"), $this_program,
627     $opt_output || 'stdout', $!;
628
629 exit;
630
631 # Call program with given option and return results.
632 sub get_option_value
633 {
634     my ($prog, $opt) = @_;
635     my $stderr = $discard_stderr ? '/dev/null' : '&1';
636     my $value = join '',
637         map { s/ +$//; expand $_ }
638         map { dec $_ }
639         `$prog $opt 2>$stderr`;
640
641     unless ($value)
642     {
643         my $err = N_("%s: can't get `%s' info from %s%s");
644         my $extra = $discard_stderr
645             ? "\n" . N_("Try `--no-discard-stderr' if option outputs to stderr")
646             : '';
647
648         kark $err, $this_program, $opt, $prog, $extra;
649     }
650
651     return $value;
652 }
653
654 # Convert option dashes to \- to stop nroff from hyphenating 'em, and
655 # embolden.  Option arguments get italicised.
656 sub convert_option
657 {
658     local $_ = '\fB' . shift;
659
660     s/-/\x83/g;
661     unless (s/\[=(.*)\]$/\\fR[=\\fI$1\\fR]/)
662     {
663         s/=(.)/\\fR=\\fI$1/;
664         s/ (.)/ \\fI$1/;
665         $_ .= '\fR';
666     }
667
668     $_;
669 }