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