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