3 # Generate a short man page from --help and --version output.
4 # Copyright (C) 1997-2018 Free Software Foundation, Inc.
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)
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.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, see <https://www.gnu.org/licenses/>.
19 # Written by Brendan O'Dea <bod@debian.org>
20 # Available from https://ftp.gnu.org/gnu/help2man/
25 use Text
::ParseWords
qw(shellwords);
26 use Text
::Tabs
qw(expand);
27 use POSIX
qw(strftime setlocale LC_ALL);
29 my $this_program = 'help2man';
30 my $this_version = '1.47.4';
36 die "$this_program: no locale support (Locale::gettext required)\n"
37 unless $locale eq 'C';
42 sub enc_user
{ $_[0] }
43 sub kark
{ die +(sprintf shift, @_), "\n" }
49 sub fix_italic_spacing
;
51 my $version_info = enc_user
sprintf _
(<<'EOT'), $this_program, $this_version;
54 Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2009, 2010,
55 2011, 2012, 2013, 2014, 2015 Free Software Foundation, Inc.
56 This is free software; see the source for copying conditions. There is NO
57 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
59 Written by Brendan O'Dea <bod@debian.org>
62 my $help_info = enc_user
sprintf _
(<<'EOT'), $this_program, $this_program;
63 `%s' generates a man page out of `--help' and `--version' output.
65 Usage: %s [OPTION]... EXECUTABLE
67 -n, --name=STRING description for the NAME paragraph
68 -s, --section=SECTION section number for manual page (1, 6, 8)
69 -m, --manual=TEXT name of manual (User Commands, ...)
70 -S, --source=TEXT source of program (FSF, Debian, ...)
71 -L, --locale=STRING select locale (default "C")
72 -i, --include=FILE include material from `FILE'
73 -I, --opt-include=FILE include material from `FILE' if it exists
74 -o, --output=FILE send output to `FILE'
75 -p, --info-page=TEXT name of Texinfo manual
76 -N, --no-info suppress pointer to Texinfo manual
77 -l, --libtool exclude the `lt-' from the program name
78 --help print this help, then exit
79 --version print version number, then exit
81 EXECUTABLE should accept `--help' and `--version' options and produce output on
82 stdout although alternatives may be specified using:
84 -h, --help-option=STRING help option string
85 -v, --version-option=STRING version option string
86 --version-string=STRING version string
87 --no-discard-stderr include stderr when parsing option output
89 Report bugs to <bug-help2man@gnu.org>.
95 my $help_option = '--help';
96 my $version_option = '--version';
97 my $discard_stderr = 1;
98 my ($opt_name, @opt_include, $opt_output, $opt_info, $opt_no_info, $opt_libtool,
102 'n|name=s' => \
$opt_name,
103 's|section=s' => \
$section,
104 'm|manual=s' => \
$manual,
105 'S|source=s' => \
$source,
106 'L|locale=s' => sub { configure_locale
pop },
107 'i|include=s' => sub { push @opt_include, [ pop, 1 ] },
108 'I|opt-include=s' => sub { push @opt_include, [ pop, 0 ] },
109 'o|output=s' => \
$opt_output,
110 'p|info-page=s' => \
$opt_info,
111 'N|no-info' => \
$opt_no_info,
112 'l|libtool' => \
$opt_libtool,
113 'help' => sub { print $help_info; exit },
114 'version' => sub { print $version_info; exit },
115 'h|help-option=s' => \
$help_option,
116 'v|version-option=s' => \
$version_option,
117 'version-string=s' => \
$version_text,
118 'discard-stderr!' => \
$discard_stderr,
122 Getopt
::Long
::config
('bundling');
123 die $help_info unless GetOptions
%opt_def and @ARGV == 1;
128 my %append_match = ();
129 my @sections = (); # retain order of include file or in-line *section*s
131 # Process include file (if given). Format is:
133 # Optional initial text, ignored. May include lines starting with `-'
134 # which are processed as options.
137 # Verbatim text to be included in the named section. By default at
138 # the start, but in the case of `name' and `synopsis' the content
139 # will replace the autogenerated contents.
142 # Verbatim text to be inserted at the start of the named section.
145 # Verbatim text to replace the named section.
148 # Verbatim text to be appended to the end of the named section.
151 # Verbatim text for inclusion below a paragraph matching `pattern'.
156 my ($inc, $required) = @
{shift @opt_include};
158 next unless -f
$inc or $required;
159 kark N_
("%s: can't open `%s' (%s)"), $this_program, $inc, $!
160 unless open INC
, $inc;
167 # Convert input to internal Perl format, so that multibyte
168 # sequences are treated as single characters.
172 if (/^\[([^]]+)\]\s*$/)
178 # Handle explicit [<section], [=section] and [>section]
179 if ($key =~ s/^([<>=])\s*//)
181 if ($1 eq '>') { $hash = \
%append; }
182 elsif ($1 eq '=') { $hash = \
%replace; }
184 # NAME/SYNOPSIS replace by default
185 elsif ($key eq _
('NAME') or $key eq _
('SYNOPSIS'))
194 push @sections, $key;
199 if (m!^/(.*)/([ims]*)\s*$!)
201 my $pat = $2 ?
"(?$2)$1" : $1;
204 eval { $key = qr
($pat) };
207 $@
=~ s/ at .*? line \d.*//;
211 $hash = \
%append_match;
215 # Check for options before the first section--anything else is
216 # silently ignored, allowing the first for comments and
223 local @ARGV = shellwords
$_;
235 kark N_
("%s: no valid information found in `%s'"), $this_program, $inc
239 # Compress trailing blank lines.
240 for my $hash (\
(%include, %replace, %append, %append_match))
242 for (keys %$hash) { $hash->{$_} =~ s/\n+$/\n/ }
245 # Grab help and version info from executable.
246 my $help_text = get_option_value
$ARGV[0], $help_option;
247 $version_text ||= get_option_value
$ARGV[0], $version_option;
249 # By default the generated manual pages will include the current date. This may
250 # however be overriden by setting the environment variable $SOURCE_DATE_EPOCH
251 # to an integer value of the seconds since the UNIX epoch. This is primarily
252 # intended to support reproducible builds (wiki.debian.org/ReproducibleBuilds)
253 # and will additionally ensure that the output date string is UTC.
254 my $epoch_secs = time;
255 if (exists $ENV{SOURCE_DATE_EPOCH
} and $ENV{SOURCE_DATE_EPOCH
} =~ /^(\d+)$/)
261 # Translators: the following message is a strftime(3) format string, which in
262 # the English version expands to the month as a word and the full year. It
263 # is used on the footer of the generated manual pages. If in doubt, you may
264 # just use %x as the value (which should be the full locale-specific date).
265 my $date = enc strftime _
("%B %Y"), localtime $epoch_secs;
266 my $program = program_basename
$ARGV[0];
267 my $package = $program;
272 unlink $opt_output or kark N_
("%s: can't unlink %s (%s)"),
273 $this_program, $opt_output, $! if -e
$opt_output;
275 open STDOUT
, ">$opt_output"
276 or kark N_
("%s: can't create %s (%s)"), $this_program, $opt_output, $!;
279 # The first line of the --version information is assumed to be in one
280 # of the following formats:
283 # <program> <version>
284 # {GNU,Free} <program> <version>
285 # <program> ({GNU,Free} <package>) <version>
286 # <program> - {GNU,Free} <package> <version>
288 # and separated from any copyright/author details by a blank line.
290 ($_, $version_text) = ((split /\n+/, $version_text, 2), '');
292 if (/^(\S+) +\(((?:GNU|Free) +[^)]+)\) +(.*)/ or
293 /^(\S+) +- *((?:GNU|Free) +\S+) +(.*)/)
295 $program = program_basename
$1;
299 elsif (/^((?:GNU|Free) +)?(\S+) +(.*)/)
301 $program = program_basename
$2;
302 $package = $1 ?
"$1$program" : $program;
310 # No info for `info' itself.
311 $opt_no_info = 1 if $program eq 'info';
315 # --name overrides --include contents.
316 $replace{_
('NAME')} = "$program \\- $opt_name\n";
319 # Translators: "NAME", "SYNOPSIS" and other one or two word strings in all
320 # upper case are manual page section headings. The man(1) manual page in your
321 # language, if available should provide the conventional translations.
322 for ($replace{_
('NAME')} || ($include{_
('NAME')} ||= ''))
324 if ($_) # Use first name given as $program
326 $program = $1 if /^([^\s,]+)(?:,?\s*[^\s,\\-]+)*\s+\\?-/;
328 else # Set a default (useless) NAME paragraph.
330 $_ = sprintf _
("%s \\- manual page for %s %s") . "\n", $program,
335 # Man pages traditionally have the page title in caps.
336 my $PROGRAM = uc $program;
338 # Set default page head/footers
339 $source ||= "$program $version";
344 if (/^(1[Mm]|8)/) { $manual = enc _
('System Administration Utilities') }
345 elsif (/^6/) { $manual = enc _
('Games') }
346 else { $manual = enc _
('User Commands') }
350 # Extract usage clause(s) [if any] for SYNOPSIS.
351 # Translators: "Usage" and "or" here are patterns (regular expressions) which
352 # are used to match the usage synopsis in program output. An example from cp
353 # (GNU coreutils) which contains both strings:
354 # Usage: cp [OPTION]... [-T] SOURCE DEST
355 # or: cp [OPTION]... SOURCE... DIRECTORY
356 # or: cp [OPTION]... -t DIRECTORY SOURCE...
357 my $PAT_USAGE = _
('Usage');
358 my $PAT_USAGE_CONT = _
('or');
359 if ($help_text =~ s/^($PAT_USAGE):( +(\S+))(.*)((?:\n(?: {6}\1| *($PAT_USAGE_CONT): +\S).*)*)//om)
366 for (split /\n/) { s/^ *(($PAT_USAGE_CONT): +)?//o; push @syn, $_ }
372 $synopsis .= ".br\n" if $synopsis;
374 s/^lt-// if $opt_libtool;
376 $synopsis .= ".B $1\n";
378 s/(([][]|\.\.+)+)/\\fR$1\\fI/g;
379 s/^/\\fI/ unless s/^\\fR//;
387 $_ = fix_italic_spacing
$_;
391 $include{_
('SYNOPSIS')} .= $synopsis;
394 # Process text, initial section is DESCRIPTION.
395 my $sect = _
('DESCRIPTION');
396 $_ = "$help_text\n\n$version_text";
398 # Normalise paragraph breaks.
403 # Join hyphenated lines.
404 s/([A-Za-z])-\n *([A-Za-z])/$1$2/g;
406 # Temporarily exchange leading dots, apostrophes and backslashes for
412 # Translators: patterns are used to match common program output. In the source
413 # these strings are all of the form of "my $PAT_something = _('...');" and are
414 # regular expressions. If there is more than one commonly used string, you
415 # may separate alternatives with "|". Spaces in these expressions are written
416 # as " +" to indicate that more than one space may be matched. The string
417 # "(?:[\\w-]+ +)?" in the bug reporting pattern is used to indicate an
418 # optional word, so that either "Report bugs" or "Report _program_ bugs" will
420 my $PAT_BUGS = _
('Report +(?:[\w-]+ +)?bugs|Email +bug +reports +to');
421 my $PAT_AUTHOR = _
('Written +by');
422 my $PAT_OPTIONS = _
('Options');
423 my $PAT_ENVIRONMENT = _
('Environment');
424 my $PAT_FILES = _
('Files');
425 my $PAT_EXAMPLES = _
('Examples');
426 my $PAT_FREE_SOFTWARE = _
('This +is +free +software');
428 # Start a new paragraph (if required) for these.
429 s/([^\n])\n($PAT_BUGS|$PAT_AUTHOR) /$1\n\n$2 /og;
431 # Convert iso-8859-1 copyright symbol or (c) to nroff
433 s/^Copyright +(?:\xa9|\([Cc]\))/Copyright \\(co/mg;
437 # Convert some standard paragraph names.
438 if (s/^($PAT_OPTIONS): *\n+//o)
440 $sect = _
('OPTIONS');
443 if (s/^($PAT_ENVIRONMENT): *\n+//o)
445 $sect = _
('ENVIRONMENT');
448 if (s/^($PAT_FILES): *\n+//o)
453 elsif (s/^($PAT_EXAMPLES): *\n+//o)
455 $sect = _
('EXAMPLES');
459 # Custom section indicated by a line containing "*Section Name*".
460 if (s/^\*(\w(.*\w)?)\* *\n+//)
463 $sect =~ tr/*/ /; # also accept *Section*Name*
464 push @sections, $sect;
471 $sect = _
('COPYRIGHT');
474 # Bug reporting section.
475 elsif (/^($PAT_BUGS) /o)
477 $sect = _
('REPORTING BUGS');
481 elsif (/^($PAT_AUTHOR)/o)
486 # Examples, indicated by an indented leading $, % or > are
487 # rendered in a constant width font.
488 if (/^( +)([\$\%>] )\S/)
493 while (s/^$indent\Q$prefix\E(\S.*)\n*//)
495 $include{$sect} .= "$break\n\\f(CW$prefix$1\\fR\n";
504 # Sub-sections have a trailing colon and the second line indented.
505 if (s/^(\S.*:) *\n / /)
507 $matched .= $& if %append_match;
508 $include{$sect} .= qq(.SS
"$1"\n);
514 # Option with description.
515 if (s/^( {1,10}([+-]\S.*?))(?:( +(?!-))|\n( {20,}))(\S.*)\n//)
517 $matched .= $& if %append_match;
518 $indent = length ($4 || "$1$3");
519 $content = ".TP\n\x84$2\n\x84$5\n";
522 # Indent may be different on second line.
523 $indent = length $& if /^ {20,}/;
527 # Option without description.
528 elsif (s/^ {1,10}([+-]\S.*)\n//)
530 $matched .= $& if %append_match;
531 $content = ".HP\n\x84$1\n";
532 $indent = 80; # not continued
535 # Indented paragraph with tag.
536 elsif (s/^( +(\S.*?))(?:( +)|\n( {20,}))(\S.*)\n//)
538 $matched .= $& if %append_match;
539 $indent = length ($4 || "$1$3");
540 $content = ".TP\n\x84$2\n\x84$5\n";
543 # Indented paragraph.
544 elsif (s/^( +)(\S.*)\n//)
546 $matched .= $& if %append_match;
548 $content = ".IP\n\x84$2\n";
551 # Left justified paragraph.
555 $matched .= $& if %append_match;
556 $content = ".PP\n" if $include{$sect};
560 # Append continuations.
561 while ($indent ?
s/^ {$indent}(\S.*)\n// : s/^(\S.*)\n//)
563 $matched .= $& if %append_match;
564 $content .= "\x84$1\n";
567 # Move to next paragraph.
572 # Leading dot and apostrophe protection.
577 # Examples should be verbatim.
578 unless ($sect eq _
('EXAMPLES'))
581 s/(^|[ (])(-[][\w=-]+)/$1 . convert_option $2/mge;
583 # Italicise filenames: /a/b, $VAR/c/d, ~/e/f
585 (^|[ (]) # space/punctuation before
587 (?
:\
$\w
+|~)?
# leading variable, or tilde
588 (?
:/\w
(?
:[\w
.-]*\w
)?
)+ # path components
590 ($|[ ,;.)]) # space/punctuation after
593 $_ = fix_italic_spacing
$_;
596 # Escape remaining hyphens.
599 if ($sect eq _
('COPYRIGHT'))
601 # Insert line breaks before additional copyright messages
602 # and the disclaimer.
603 s/\n(Copyright |$PAT_FREE_SOFTWARE)/\n.br\n$1/og;
605 elsif ($sect eq _
('REPORTING BUGS'))
607 # Handle multi-line bug reporting sections of the form:
609 # Report <program> bugs to <addr>
610 # GNU <package> home page: <url>
612 s/\n([[:upper:]])/\n.br\n$1/g;
616 # Check if matched paragraph contains /pat/.
619 for my $pat (keys %append_match)
621 if ($matched =~ $pat)
623 $content .= ".PP\n" unless $append_match{$pat} =~ /^\./;
624 $content .= $append_match{$pat};
629 $include{$sect} .= $content;
632 # Refer to the real documentation.
633 unless ($opt_no_info)
635 my $info_page = $opt_info || $program;
637 $sect = _
('SEE ALSO');
638 $include{$sect} .= ".PP\n" if $include{$sect};
639 $include{$sect} .= sprintf _
(<<'EOT'), $program, $program, $info_page;
640 The full documentation for
642 is maintained as a Texinfo manual. If the
646 programs are properly installed at your site, the command
650 should give you access to the complete manual.
654 # Append additional text.
655 while (my ($sect, $text) = each %append)
657 $include{$sect} .= $append{$sect};
661 while (my ($sect, $text) = each %replace)
663 $include{$sect} = $replace{$sect};
668 .\\" DO NOT MODIFY THIS FILE! It was generated by $this_program $this_version.
669 .TH $PROGRAM "$section" "$date" "$source" "$manual"
673 my @pre = (_
('NAME'), _
('SYNOPSIS'), _
('DESCRIPTION'), _
('OPTIONS'));
674 my @post = (_
('ENVIRONMENT'), _
('FILES'), _
('EXAMPLES'), _
('AUTHOR'),
675 _
('REPORTING BUGS'), _
('COPYRIGHT'), _
('SEE ALSO'));
676 my %filter = map { $_ => 1 } @pre, @post;
680 for my $sect (@pre, (grep !$filter{$_}, @sections), @post)
682 next if $done{$sect}++; # ignore duplicates
683 next unless $include{$sect};
686 my $quote = $sect =~ /\W/ ?
'"' : '';
687 print enc
".SH $quote$sect$quote\n";
689 for ($include{$sect})
691 # Replace leading dot, apostrophe, backslash and hyphen
698 # Convert some latin1 chars to troff equivalents
699 s/\xa0/\\ /g; # non-breaking space
706 close STDOUT
or kark N_
("%s: error writing to %s (%s)"), $this_program,
707 $opt_output || 'stdout', $!;
711 # Get program basename, and strip libtool "lt-" prefix if required.
716 s/^lt-// if $opt_libtool;
720 # Call program with given option and return results.
723 my ($prog, $opt) = @_;
724 my $stderr = $discard_stderr ?
'/dev/null' : '&1';
726 map { s/ +$//; expand
$_ }
728 `$prog $opt 2>$stderr`;
732 my $err = N_
("%s: can't get `%s' info from %s%s");
733 my $extra = $discard_stderr
734 ?
"\n" . N_
("Try `--no-discard-stderr' if option outputs to stderr")
737 kark
$err, $this_program, $opt, $prog, $extra;
743 # Convert option dashes to \- to stop nroff from hyphenating 'em, and
744 # embolden. Option arguments get italicised.
747 local $_ = '\fB' . shift;
750 unless (s/\[=(.*)\]$/\\fR[=\\fI$1\\fR]/)
760 # Insert spacing escape characters \, and \/ before and after italic text. See
761 # https://www.gnu.org/software/groff/manual/html_node/Ligatures-and-Kerning.html
762 sub fix_italic_spacing
765 s!\\fI(.*?)\\f([BRP])!\\fI\\,$1\\/\\f$2!g;