This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Weed out some smaller changes.
[perl5.git] / lib / Pod / Usage.pm
CommitLineData
360aca43
GS
1#############################################################################
2# Pod/Usage.pm -- print usage messages for the running script.
3#
66aff6dd 4# Copyright (C) 1996-2000 by Bradford Appleton. All rights reserved.
360aca43
GS
5# This file is part of "PodParser". PodParser is free software;
6# you can redistribute it and/or modify it under the same terms
7# as Perl itself.
8#############################################################################
9
10package Pod::Usage;
11
12use vars qw($VERSION);
92e3d63a 13$VERSION = 1.13; ## Current version of this package
828c4421 14require 5.005; ## requires this Perl version or later
360aca43
GS
15
16=head1 NAME
17
18Pod::Usage, pod2usage() - print a usage message from embedded pod documentation
19
20=head1 SYNOPSIS
21
22 use Pod::Usage
23
24 my $message_text = "This text precedes the usage message.";
25 my $exit_status = 2; ## The exit status to use
26 my $verbose_level = 0; ## The verbose level to use
27 my $filehandle = \*STDERR; ## The filehandle to write to
28
29 pod2usage($message_text);
30
31 pod2usage($exit_status);
32
33 pod2usage( { -message => $message_text ,
34 -exitval => $exit_status ,
35 -verbose => $verbose_level,
36 -output => $filehandle } );
37
38 pod2usage( -msg => $message_text ,
39 -exitval => $exit_status ,
40 -verbose => $verbose_level,
41 -output => $filehandle );
42
43=head1 ARGUMENTS
44
45B<pod2usage> should be given either a single argument, or a list of
46arguments corresponding to an associative array (a "hash"). When a single
47argument is given, it should correspond to exactly one of the following:
48
92e3d63a 49=over 4
360aca43
GS
50
51=item *
52
53A string containing the text of a message to print I<before> printing
54the usage message
55
56=item *
57
58A numeric value corresponding to the desired exit status
59
60=item *
61
62A reference to a hash
63
64=back
65
66If more than one argument is given then the entire argument list is
67assumed to be a hash. If a hash is supplied (either as a reference or
68as a list) it should contain one or more elements with the following
69keys:
70
92e3d63a 71=over 4
360aca43
GS
72
73=item C<-message>
74
75=item C<-msg>
76
77The text of a message to print immediately prior to printing the
78program's usage message.
79
80=item C<-exitval>
81
82The desired exit status to pass to the B<exit()> function.
83
84=item C<-verbose>
85
86The desired level of "verboseness" to use when printing the usage
87message. If the corresponding value is 0, then only the "SYNOPSIS"
88section of the pod documentation is printed. If the corresponding value
89is 1, then the "SYNOPSIS" section, along with any section entitled
90"OPTIONS", "ARGUMENTS", or "OPTIONS AND ARGUMENTS" is printed. If the
91corresponding value is 2 or more then the entire manpage is printed.
92
93=item C<-output>
94
95A reference to a filehandle, or the pathname of a file to which the
96usage message should be written. The default is C<\*STDERR> unless the
97exit value is less than 2 (in which case the default is C<\*STDOUT>).
98
99=item C<-input>
100
101A reference to a filehandle, or the pathname of a file from which the
102invoking script's pod documentation should be read. It defaults to the
103file indicated by C<$0> (C<$PROGRAM_NAME> for users of F<English.pm>).
104
105=item C<-pathlist>
106
107A list of directory paths. If the input file does not exist, then it
108will be searched for in the given directory list (in the order the
109directories appear in the list). It defaults to the list of directories
110implied by C<$ENV{PATH}>. The list may be specified either by a reference
111to an array, or by a string of directory paths which use the same path
112separator as C<$ENV{PATH}> on your system (e.g., C<:> for Unix, C<;> for
113MSWin32 and DOS).
114
115=back
116
117=head1 DESCRIPTION
118
119B<pod2usage> will print a usage message for the invoking script (using
120its embedded pod documentation) and then exit the script with the
121desired exit status. The usage message printed may have any one of three
122levels of "verboseness": If the verbose level is 0, then only a synopsis
123is printed. If the verbose level is 1, then the synopsis is printed
124along with a description (if present) of the command line options and
125arguments. If the verbose level is 2, then the entire manual page is
126printed.
127
128Unless they are explicitly specified, the default values for the exit
129status, verbose level, and output stream to use are determined as
130follows:
131
92e3d63a 132=over 4
360aca43
GS
133
134=item *
135
136If neither the exit status nor the verbose level is specified, then the
137default is to use an exit status of 2 with a verbose level of 0.
138
139=item *
140
141If an exit status I<is> specified but the verbose level is I<not>, then the
142verbose level will default to 1 if the exit status is less than 2 and
143will default to 0 otherwise.
144
145=item *
146
147If an exit status is I<not> specified but verbose level I<is> given, then
148the exit status will default to 2 if the verbose level is 0 and will
149default to 1 otherwise.
150
151=item *
152
153If the exit status used is less than 2, then output is printed on
154C<STDOUT>. Otherwise output is printed on C<STDERR>.
155
156=back
157
158Although the above may seem a bit confusing at first, it generally does
159"the right thing" in most situations. This determination of the default
160values to use is based upon the following typical Unix conventions:
161
92e3d63a 162=over 4
360aca43
GS
163
164=item *
165
166An exit status of 0 implies "success". For example, B<diff(1)> exits
167with a status of 0 if the two files have the same contents.
168
169=item *
170
171An exit status of 1 implies possibly abnormal, but non-defective, program
172termination. For example, B<grep(1)> exits with a status of 1 if
173it did I<not> find a matching line for the given regular expression.
174
175=item *
176
177An exit status of 2 or more implies a fatal error. For example, B<ls(1)>
178exits with a status of 2 if you specify an illegal (unknown) option on
179the command line.
180
181=item *
182
183Usage messages issued as a result of bad command-line syntax should go
184to C<STDERR>. However, usage messages issued due to an explicit request
185to print usage (like specifying B<-help> on the command line) should go
186to C<STDOUT>, just in case the user wants to pipe the output to a pager
187(such as B<more(1)>).
188
189=item *
190
191If program usage has been explicitly requested by the user, it is often
192desireable to exit with a status of 1 (as opposed to 0) after issuing
193the user-requested usage message. It is also desireable to give a
194more verbose description of program usage in this case.
195
196=back
197
198B<pod2usage> doesn't force the above conventions upon you, but it will
199use them by default if you don't expressly tell it to do otherwise. The
200ability of B<pod2usage()> to accept a single number or a string makes it
201convenient to use as an innocent looking error message handling function:
202
203 use Pod::Usage;
204 use Getopt::Long;
205
206 ## Parse options
207 GetOptions("help", "man", "flag1") || pod2usage(2);
208 pod2usage(1) if ($opt_help);
209 pod2usage(-verbose => 2) if ($opt_man);
210
211 ## Check for too many filenames
212 pod2usage("$0: Too many files given.\n") if (@ARGV > 1);
213
92e3d63a 214Some user's however may feel that the above "economy of expression" is
360aca43
GS
215not particularly readable nor consistent and may instead choose to do
216something more like the following:
217
218 use Pod::Usage;
219 use Getopt::Long;
220
221 ## Parse options
222 GetOptions("help", "man", "flag1") || pod2usage(-verbose => 0);
223 pod2usage(-verbose => 1) if ($opt_help);
224 pod2usage(-verbose => 2) if ($opt_man);
225
226 ## Check for too many filenames
227 pod2usage(-verbose => 2, -message => "$0: Too many files given.\n")
228 if (@ARGV > 1);
229
230As with all things in Perl, I<there's more than one way to do it>, and
231B<pod2usage()> adheres to this philosophy. If you are interested in
232seeing a number of different ways to invoke B<pod2usage> (although by no
233means exhaustive), please refer to L<"EXAMPLES">.
234
235=head1 EXAMPLES
236
237Each of the following invocations of C<pod2usage()> will print just the
238"SYNOPSIS" section to C<STDERR> and will exit with a status of 2:
239
240 pod2usage();
241
242 pod2usage(2);
243
244 pod2usage(-verbose => 0);
245
246 pod2usage(-exitval => 2);
247
248 pod2usage({-exitval => 2, -output => \*STDERR});
249
250 pod2usage({-verbose => 0, -output => \*STDERR});
251
252 pod2usage(-exitval => 2, -verbose => 0);
253
254 pod2usage(-exitval => 2, -verbose => 0, -output => \*STDERR);
255
256Each of the following invocations of C<pod2usage()> will print a message
257of "Syntax error." (followed by a newline) to C<STDERR>, immediately
258followed by just the "SYNOPSIS" section (also printed to C<STDERR>) and
259will exit with a status of 2:
260
261 pod2usage("Syntax error.");
262
263 pod2usage(-message => "Syntax error.", -verbose => 0);
264
265 pod2usage(-msg => "Syntax error.", -exitval => 2);
266
267 pod2usage({-msg => "Syntax error.", -exitval => 2, -output => \*STDERR});
268
269 pod2usage({-msg => "Syntax error.", -verbose => 0, -output => \*STDERR});
270
271 pod2usage(-msg => "Syntax error.", -exitval => 2, -verbose => 0);
272
273 pod2usage(-message => "Syntax error.",
274 -exitval => 2,
275 -verbose => 0,
276 -output => \*STDERR);
277
278Each of the following invocations of C<pod2usage()> will print the
279"SYNOPSIS" section and any "OPTIONS" and/or "ARGUMENTS" sections to
280C<STDOUT> and will exit with a status of 1:
281
282 pod2usage(1);
283
284 pod2usage(-verbose => 1);
285
286 pod2usage(-exitval => 1);
287
288 pod2usage({-exitval => 1, -output => \*STDOUT});
289
290 pod2usage({-verbose => 1, -output => \*STDOUT});
291
292 pod2usage(-exitval => 1, -verbose => 1);
293
294 pod2usage(-exitval => 1, -verbose => 1, -output => \*STDOUT});
295
296Each of the following invocations of C<pod2usage()> will print the
297entire manual page to C<STDOUT> and will exit with a status of 1:
298
299 pod2usage(-verbose => 2);
300
301 pod2usage({-verbose => 2, -output => \*STDOUT});
302
303 pod2usage(-exitval => 1, -verbose => 2);
304
305 pod2usage({-exitval => 1, -verbose => 2, -output => \*STDOUT});
306
307=head2 Recommended Use
308
309Most scripts should print some type of usage message to C<STDERR> when a
310command line syntax error is detected. They should also provide an
311option (usually C<-H> or C<-help>) to print a (possibly more verbose)
312usage message to C<STDOUT>. Some scripts may even wish to go so far as to
313provide a means of printing their complete documentation to C<STDOUT>
f48e6a7e
GS
314(perhaps by allowing a C<-man> option). The following complete example
315uses B<Pod::Usage> in combination with B<Getopt::Long> to do all of these
360aca43
GS
316things:
317
318 use Getopt::Long;
319 use Pod::Usage;
320
f48e6a7e
GS
321 my $man = 0;
322 my $help = 0;
360aca43
GS
323 ## Parse options and print usage if there is a syntax error,
324 ## or if usage was explicitly requested.
f48e6a7e
GS
325 GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
326 pod2usage(1) if $help;
327 pod2usage(-verbose => 2) if $man;
360aca43
GS
328
329 ## If no arguments were given, then allow STDIN to be used only
330 ## if it's not connected to a terminal (otherwise print usage)
331 pod2usage("$0: No files given.") if ((@ARGV == 0) && (-t STDIN));
f48e6a7e
GS
332 __END__
333
334 =head1 NAME
335
336 sample - Using GetOpt::Long and Pod::Usage
337
338 =head1 SYNOPSIS
339
340 sample [options] [file ...]
341
342 Options:
343 -help brief help message
344 -man full documentation
345
346 =head1 OPTIONS
347
348 =over 8
349
350 =item B<-help>
351
352 Print a brief help message and exits.
353
354 =item B<-man>
355
356 Prints the manual page and exits.
357
358 =back
359
360 =head1 DESCRIPTION
361
362 B<This program> will read the given input file(s) and do something
363 useful with the contents thereof.
364
365 =cut
360aca43
GS
366
367=head1 CAVEATS
368
369By default, B<pod2usage()> will use C<$0> as the path to the pod input
370file. Unfortunately, not all systems on which Perl runs will set C<$0>
371properly (although if C<$0> isn't found, B<pod2usage()> will search
372C<$ENV{PATH}> or else the list specified by the C<-pathlist> option).
373If this is the case for your system, you may need to explicitly specify
374the path to the pod docs for the invoking script using something
375similar to the following:
376
377 pod2usage(-exitval => 2, -input => "/path/to/your/pod/docs");
378
379=head1 AUTHOR
380
381Brad Appleton E<lt>bradapp@enteract.comE<gt>
382
383Based on code for B<Pod::Text::pod2text()> written by
384Tom Christiansen E<lt>tchrist@mox.perl.comE<gt>
385
386=head1 ACKNOWLEDGEMENTS
387
388Steven McDougall E<lt>swmcd@world.std.comE<gt> for his help and patience
389with re-writing this manpage.
390
391=cut
392
393#############################################################################
394
395use strict;
396#use diagnostics;
397use Carp;
398use Exporter;
360aca43
GS
399use File::Spec;
400
401use vars qw(@ISA @EXPORT);
360aca43 402@EXPORT = qw(&pod2usage);
664bb207
GS
403BEGIN {
404 if ( $] >= 5.005_58 ) {
405 require Pod::Text;
406 @ISA = qw( Pod::Text );
407 }
408 else {
409 require Pod::PlainText;
410 @ISA = qw( Pod::PlainText );
411 }
412}
413
360aca43
GS
414
415##---------------------------------------------------------------------------
416
417##---------------------------------
418## Function definitions begin here
419##---------------------------------
420
421sub pod2usage {
422 local($_) = shift || "";
423 my %opts;
424 ## Collect arguments
425 if (@_ > 0) {
426 ## Too many arguments - assume that this is a hash and
427 ## the user forgot to pass a reference to it.
428 %opts = ($_, @_);
429 }
430 elsif (ref $_) {
431 ## User passed a ref to a hash
432 %opts = %{$_} if (ref($_) eq 'HASH');
433 }
e9fdc7d2 434 elsif (/^[-+]?\d+$/) {
360aca43
GS
435 ## User passed in the exit value to use
436 $opts{"-exitval"} = $_;
437 }
438 else {
439 ## User passed in a message to print before issuing usage.
440 $_ and $opts{"-message"} = $_;
441 }
442
443 ## Need this for backward compatibility since we formerly used
444 ## options that were all uppercase words rather than ones that
445 ## looked like Unix command-line options.
446 ## to be uppercase keywords)
447 %opts = map {
448 my $val = $opts{$_};
449 s/^(?=\w)/-/;
450 /^-msg/i and $_ = '-message';
451 /^-exit/i and $_ = '-exitval';
452 lc($_) => $val;
453 } (keys %opts);
454
455 ## Now determine default -exitval and -verbose values to use
456 if ((! defined $opts{"-exitval"}) && (! defined $opts{"-verbose"})) {
457 $opts{"-exitval"} = 2;
458 $opts{"-verbose"} = 0;
459 }
460 elsif (! defined $opts{"-exitval"}) {
461 $opts{"-exitval"} = ($opts{"-verbose"} > 0) ? 1 : 2;
462 }
463 elsif (! defined $opts{"-verbose"}) {
464 $opts{"-verbose"} = ($opts{"-exitval"} < 2);
465 }
466
467 ## Default the output file
468 $opts{"-output"} = ($opts{"-exitval"} < 2) ? \*STDOUT : \*STDERR
469 unless (defined $opts{"-output"});
470 ## Default the input file
471 $opts{"-input"} = $0 unless (defined $opts{"-input"});
472
473 ## Look up input file in path if it doesnt exist.
474 unless ((ref $opts{"-input"}) || (-e $opts{"-input"})) {
475 my ($dirname, $basename) = ('', $opts{"-input"});
476 my $pathsep = ($^O =~ /^(?:dos|os2|MSWin32)$/) ? ";"
477 : (($^O eq 'MacOS') ? ',' : ":");
478 my $pathspec = $opts{"-pathlist"} || $ENV{PATH} || $ENV{PERL5LIB};
479
480 my @paths = (ref $pathspec) ? @$pathspec : split($pathsep, $pathspec);
481 for $dirname (@paths) {
482 $_ = File::Spec->catfile($dirname, $basename) if length;
483 last if (-e $_) && ($opts{"-input"} = $_);
484 }
485 }
486
487 ## Now create a pod reader and constrain it to the desired sections.
488 my $parser = new Pod::Usage(USAGE_OPTIONS => \%opts);
489 if ($opts{"-verbose"} == 0) {
490 $parser->select("SYNOPSIS");
491 }
492 elsif ($opts{"-verbose"} == 1) {
493 my $opt_re = '(?i)' .
494 '(?:OPTIONS|ARGUMENTS)' .
495 '(?:\s*(?:AND|\/)\s*(?:OPTIONS|ARGUMENTS))?';
496 $parser->select( 'SYNOPSIS', $opt_re, "DESCRIPTION/$opt_re" );
497 }
498
499 ## Now translate the pod document and then exit with the desired status
500 $parser->parse_from_file($opts{"-input"}, $opts{"-output"});
501 exit($opts{"-exitval"});
502}
503
504##---------------------------------------------------------------------------
505
506##-------------------------------
507## Method definitions begin here
508##-------------------------------
509
510sub new {
511 my $this = shift;
512 my $class = ref($this) || $this;
513 my %params = @_;
514 my $self = {%params};
515 bless $self, $class;
516 $self->initialize();
517 return $self;
518}
519
520sub begin_pod {
521 my $self = shift;
522 $self->SUPER::begin_pod(); ## Have to call superclass
523 my $msg = $self->{USAGE_OPTIONS}->{-message} or return 1;
524 my $out_fh = $self->output_handle();
525 print $out_fh "$msg\n";
526}
527
528sub preprocess_paragraph {
529 my $self = shift;
530 local $_ = shift;
531 my $line = shift;
532 ## See if this is a heading and we arent printing the entire manpage.
e9fdc7d2 533 if (($self->{USAGE_OPTIONS}->{-verbose} < 2) && /^=head/) {
360aca43 534 ## Change the title of the SYNOPSIS section to USAGE
e9fdc7d2 535 s/^=head1\s+SYNOPSIS\s*$/=head1 USAGE/;
360aca43
GS
536 ## Try to do some lowercasing instead of all-caps in headings
537 s{([A-Z])([A-Z]+)}{((length($2) > 2) ? $1 : lc($1)) . lc($2)}ge;
538 ## Use a colon to end all headings
e9fdc7d2 539 s/\s*$/:/ unless (/:\s*$/);
360aca43
GS
540 $_ .= "\n";
541 }
542 return $self->SUPER::preprocess_paragraph($_);
543}
544