Start anew
[msysgit.git] / lib / perl5 / 5.6.1 / Pod / Find.pm
blob18913eea1800eb5fd85cf89369a0223a870b59f9
1 #############################################################################
2 # Pod/Find.pm -- finds files containing POD documentation
4 # Author: Marek Rouchal <marek@saftsack.fs.uni-bayreuth.de>
5 #
6 # Copyright (C) 1999-2000 by Marek Rouchal (and borrowing code
7 # from Nick Ing-Simmon's PodToHtml). All rights reserved.
8 # This file is part of "PodParser". Pod::Find is free software;
9 # you can redistribute it and/or modify it under the same terms
10 # as Perl itself.
11 #############################################################################
13 package Pod::Find;
15 use vars qw($VERSION);
16 $VERSION = 0.21; ## Current version of this package
17 require 5.005; ## requires this Perl version or later
18 use Carp;
20 #############################################################################
22 =head1 NAME
24 Pod::Find - find POD documents in directory trees
26 =head1 SYNOPSIS
28 use Pod::Find qw(pod_find simplify_name);
29 my %pods = pod_find({ -verbose => 1, -inc => 1 });
30 foreach(keys %pods) {
31 print "found library POD `$pods{$_}' in $_\n";
34 print "podname=",simplify_name('a/b/c/mymodule.pod'),"\n";
36 $location = pod_where( { -inc => 1 }, "Pod::Find" );
38 =head1 DESCRIPTION
40 B<Pod::Find> provides a set of functions to locate POD files. Note that
41 no function is exported by default to avoid pollution of your namespace,
42 so be sure to specify them in the B<use> statement if you need them:
44 use Pod::Find qw(pod_find);
46 =cut
48 use strict;
49 #use diagnostics;
50 use Exporter;
51 use File::Spec;
52 use File::Find;
53 use Cwd;
55 use vars qw(@ISA @EXPORT_OK $VERSION);
56 @ISA = qw(Exporter);
57 @EXPORT_OK = qw(&pod_find &simplify_name &pod_where &contains_pod);
59 # package global variables
60 my $SIMPLIFY_RX;
62 =head2 C<pod_find( { %opts } , @directories )>
64 The function B<pod_find> searches for POD documents in a given set of
65 files and/or directories. It returns a hash with the file names as keys
66 and the POD name as value. The POD name is derived from the file name
67 and its position in the directory tree.
69 E.g. when searching in F<$HOME/perl5lib>, the file
70 F<$HOME/perl5lib/MyModule.pm> would get the POD name I<MyModule>,
71 whereas F<$HOME/perl5lib/Myclass/Subclass.pm> would be
72 I<Myclass::Subclass>. The name information can be used for POD
73 translators.
75 Only text files containing at least one valid POD command are found.
77 A warning is printed if more than one POD file with the same POD name
78 is found, e.g. F<CPAN.pm> in different directories. This usually
79 indicates duplicate occurrences of modules in the I<@INC> search path.
81 B<OPTIONS> The first argument for B<pod_find> may be a hash reference
82 with options. The rest are either directories that are searched
83 recursively or files. The POD names of files are the plain basenames
84 with any Perl-like extension (.pm, .pl, .pod) stripped.
86 =over 4
88 =item C<-verbose =E<gt> 1>
90 Print progress information while scanning.
92 =item C<-perl =E<gt> 1>
94 Apply Perl-specific heuristics to find the correct PODs. This includes
95 stripping Perl-like extensions, omitting subdirectories that are numeric
96 but do I<not> match the current Perl interpreter's version id, suppressing
97 F<site_perl> as a module hierarchy name etc.
99 =item C<-script =E<gt> 1>
101 Search for PODs in the current Perl interpreter's installation
102 B<scriptdir>. This is taken from the local L<Config|Config> module.
104 =item C<-inc =E<gt> 1>
106 Search for PODs in the current Perl interpreter's I<@INC> paths. This
107 automatically considers paths specified in the C<PERL5LIB> environment
108 as this is prepended to I<@INC> by the Perl interpreter itself.
110 =back
112 =cut
114 # return a hash of the POD files found
115 # first argument may be a hashref (options),
116 # rest is a list of directories to search recursively
117 sub pod_find
119 my %opts;
120 if(ref $_[0]) {
121 %opts = %{shift()};
124 $opts{-verbose} ||= 0;
125 $opts{-perl} ||= 0;
127 my (@search) = @_;
129 if($opts{-script}) {
130 require Config;
131 push(@search, $Config::Config{scriptdir})
132 if -d $Config::Config{scriptdir};
133 $opts{-perl} = 1;
136 if($opts{-inc}) {
137 if ($^O eq 'MacOS') {
138 # tolerate '.', './some_dir' and '(../)+some_dir' on Mac OS
139 my @new_INC = @INC;
140 for (@new_INC) {
141 if ( $_ eq '.' ) {
142 $_ = ':';
143 } elsif ( $_ =~ s|^((?:\.\./)+)|':' x (length($1)/3)|e ) {
144 $_ = ':'. $_;
145 } else {
146 $_ =~ s|^\./|:|;
149 push(@search, grep($_ ne File::Spec->curdir, @new_INC));
150 } else {
151 push(@search, grep($_ ne File::Spec->curdir, @INC));
154 $opts{-perl} = 1;
157 if($opts{-perl}) {
158 require Config;
159 # this code simplifies the POD name for Perl modules:
160 # * remove "site_perl"
161 # * remove e.g. "i586-linux" (from 'archname')
162 # * remove e.g. 5.00503
163 # * remove pod/ if followed by *.pod (e.g. in pod/perlfunc.pod)
165 # Mac OS:
166 # * remove ":?site_perl:"
167 # * remove :?pod: if followed by *.pod (e.g. in :pod:perlfunc.pod)
169 if ($^O eq 'MacOS') {
170 $SIMPLIFY_RX =
171 qq!^(?i:\:?site_perl\:|\:?pod\:(?=.*?\\.pod\\z))*!;
172 } else {
173 $SIMPLIFY_RX =
174 qq!^(?i:site(_perl)?/|\Q$Config::Config{archname}\E/|\\d+\\.\\d+([_.]?\\d+)?/|pod/(?=.*?\\.pod\\z))*!;
178 my %dirs_visited;
179 my %pods;
180 my %names;
181 my $pwd = cwd();
183 foreach my $try (@search) {
184 unless(File::Spec->file_name_is_absolute($try)) {
185 # make path absolute
186 $try = File::Spec->catfile($pwd,$try);
188 # simplify path
189 # on VMS canonpath will vmsify:[the.path], but File::Find::find
190 # wants /unixy/paths
191 $try = File::Spec->canonpath($try) if ($^O ne 'VMS');
192 my $name;
193 if(-f $try) {
194 if($name = _check_and_extract_name($try, $opts{-verbose})) {
195 _check_for_duplicates($try, $name, \%names, \%pods);
197 next;
199 my $root_rx = $^O eq 'MacOS' ? qq!^\Q$try\E! : qq!^\Q$try\E/!;
200 File::Find::find( sub {
201 my $item = $File::Find::name;
202 if(-d) {
203 if($dirs_visited{$item}) {
204 warn "Directory '$item' already seen, skipping.\n"
205 if($opts{-verbose});
206 $File::Find::prune = 1;
207 return;
209 else {
210 $dirs_visited{$item} = 1;
212 if($opts{-perl} && /^(\d+\.[\d_]+)\z/s && eval "$1" != $]) {
213 $File::Find::prune = 1;
214 warn "Perl $] version mismatch on $_, skipping.\n"
215 if($opts{-verbose});
217 return;
219 if($name = _check_and_extract_name($item, $opts{-verbose}, $root_rx)) {
220 _check_for_duplicates($item, $name, \%names, \%pods);
222 }, $try); # end of File::Find::find
224 chdir $pwd;
225 %pods;
228 sub _check_for_duplicates {
229 my ($file, $name, $names_ref, $pods_ref) = @_;
230 if($$names_ref{$name}) {
231 warn "Duplicate POD found (shadowing?): $name ($file)\n";
232 warn " Already seen in ",
233 join(' ', grep($$pods_ref{$_} eq $name, keys %$pods_ref)),"\n";
235 else {
236 $$names_ref{$name} = 1;
238 $$pods_ref{$file} = $name;
241 sub _check_and_extract_name {
242 my ($file, $verbose, $root_rx) = @_;
244 # check extension or executable flag
245 # this involves testing the .bat extension on Win32!
246 unless(-f $file && -T _ && ($file =~ /\.(pod|pm|plx?)\z/i || -x _ )) {
247 return undef;
250 return undef unless contains_pod($file,$verbose);
252 # strip non-significant path components
253 # TODO what happens on e.g. Win32?
254 my $name = $file;
255 if(defined $root_rx) {
256 $name =~ s!$root_rx!!s;
257 $name =~ s!$SIMPLIFY_RX!!os if(defined $SIMPLIFY_RX);
259 else {
260 if ($^O eq 'MacOS') {
261 $name =~ s/^.*://s;
262 } else {
263 $name =~ s:^.*/::s;
266 _simplify($name);
267 $name =~ s!/+!::!g; #/
268 if ($^O eq 'MacOS') {
269 $name =~ s!:+!::!g; # : -> ::
270 } else {
271 $name =~ s!/+!::!g; # / -> ::
273 $name;
276 =head2 C<simplify_name( $str )>
278 The function B<simplify_name> is equivalent to B<basename>, but also
279 strips Perl-like extensions (.pm, .pl, .pod) and extensions like
280 F<.bat>, F<.cmd> on Win32 and OS/2, or F<.com> on VMS, respectively.
282 =cut
284 # basic simplification of the POD name:
285 # basename & strip extension
286 sub simplify_name {
287 my ($str) = @_;
288 # remove all path components
289 if ($^O eq 'MacOS') {
290 $str =~ s/^.*://s;
291 } else {
292 $str =~ s:^.*/::s;
294 _simplify($str);
295 $str;
298 # internal sub only
299 sub _simplify {
300 # strip Perl's own extensions
301 $_[0] =~ s/\.(pod|pm|plx?)\z//i;
302 # strip meaningless extensions on Win32 and OS/2
303 $_[0] =~ s/\.(bat|exe|cmd)\z//i if($^O =~ /mswin|os2/i);
304 # strip meaningless extensions on VMS
305 $_[0] =~ s/\.(com)\z//i if($^O eq 'VMS');
308 # contribution from Tim Jenness <t.jenness@jach.hawaii.edu>
310 =head2 C<pod_where( { %opts }, $pod )>
312 Returns the location of a pod document given a search directory
313 and a module (e.g. C<File::Find>) or script (e.g. C<perldoc>) name.
315 Options:
317 =over 4
319 =item C<-inc =E<gt> 1>
321 Search @INC for the pod and also the C<scriptdir> defined in the
322 L<Config|Config> module.
324 =item C<-dirs =E<gt> [ $dir1, $dir2, ... ]>
326 Reference to an array of search directories. These are searched in order
327 before looking in C<@INC> (if B<-inc>). Current directory is used if
328 none are specified.
330 =item C<-verbose =E<gt> 1>
332 List directories as they are searched
334 =back
336 Returns the full path of the first occurence to the file.
337 Package names (eg 'A::B') are automatically converted to directory
338 names in the selected directory. (eg on unix 'A::B' is converted to
339 'A/B'). Additionally, '.pm', '.pl' and '.pod' are appended to the
340 search automatically if required.
342 A subdirectory F<pod/> is also checked if it exists in any of the given
343 search directories. This ensures that e.g. L<perlfunc|perlfunc> is
344 found.
346 It is assumed that if a module name is supplied, that that name
347 matches the file name. Pods are not opened to check for the 'NAME'
348 entry.
350 A check is made to make sure that the file that is found does
351 contain some pod documentation.
353 =cut
355 sub pod_where {
357 # default options
358 my %options = (
359 '-inc' => 0,
360 '-verbose' => 0,
361 '-dirs' => [ File::Spec->curdir ],
364 # Check for an options hash as first argument
365 if (defined $_[0] && ref($_[0]) eq 'HASH') {
366 my $opt = shift;
368 # Merge default options with supplied options
369 %options = (%options, %$opt);
372 # Check usage
373 carp 'Usage: pod_where({options}, $pod)' unless (scalar(@_));
375 # Read argument
376 my $pod = shift;
378 # Split on :: and then join the name together using File::Spec
379 my @parts = split (/::/, $pod);
381 # Get full directory list
382 my @search_dirs = @{ $options{'-dirs'} };
384 if ($options{'-inc'}) {
386 require Config;
388 # Add @INC
389 if ($^O eq 'MacOS' && $options{'-inc'}) {
390 # tolerate '.', './some_dir' and '(../)+some_dir' on Mac OS
391 my @new_INC = @INC;
392 for (@new_INC) {
393 if ( $_ eq '.' ) {
394 $_ = ':';
395 } elsif ( $_ =~ s|^((?:\.\./)+)|':' x (length($1)/3)|e ) {
396 $_ = ':'. $_;
397 } else {
398 $_ =~ s|^\./|:|;
401 push (@search_dirs, @new_INC);
402 } elsif ($options{'-inc'}) {
403 push (@search_dirs, @INC);
405 push (@search_dirs, @INC) if $options{'-inc'};
407 # Add location of pod documentation for perl man pages (eg perlfunc)
408 # This is a pod directory in the private install tree
409 #my $perlpoddir = File::Spec->catdir($Config::Config{'installprivlib'},
410 # 'pod');
411 #push (@search_dirs, $perlpoddir)
412 # if -d $perlpoddir;
414 # Add location of binaries such as pod2text
415 push (@search_dirs, $Config::Config{'scriptdir'})
416 if -d $Config::Config{'scriptdir'};
419 # Loop over directories
420 Dir: foreach my $dir ( @search_dirs ) {
422 # Don't bother if can't find the directory
423 if (-d $dir) {
424 warn "Looking in directory $dir\n"
425 if $options{'-verbose'};
427 # Now concatenate this directory with the pod we are searching for
428 my $fullname = File::Spec->catfile($dir, @parts);
429 warn "Filename is now $fullname\n"
430 if $options{'-verbose'};
432 # Loop over possible extensions
433 foreach my $ext ('', '.pod', '.pm', '.pl') {
434 my $fullext = $fullname . $ext;
435 if (-f $fullext &&
436 contains_pod($fullext, $options{'-verbose'}) ) {
437 warn "FOUND: $fullext\n" if $options{'-verbose'};
438 return $fullext;
441 } else {
442 warn "Directory $dir does not exist\n"
443 if $options{'-verbose'};
444 next Dir;
446 if(-d File::Spec->catdir($dir,'pod')) {
447 $dir = File::Spec->catdir($dir,'pod');
448 redo Dir;
451 # No match;
452 return undef;
455 =head2 C<contains_pod( $file , $verbose )>
457 Returns true if the supplied filename (not POD module) contains some pod
458 information.
460 =cut
462 sub contains_pod {
463 my $file = shift;
464 my $verbose = 0;
465 $verbose = shift if @_;
467 # check for one line of POD
468 unless(open(POD,"<$file")) {
469 warn "Error: $file is unreadable: $!\n";
470 return undef;
473 local $/ = undef;
474 my $pod = <POD>;
475 close(POD) || die "Error closing $file: $!\n";
476 unless($pod =~ /\n=(head\d|pod|over|item)\b/s) {
477 warn "No POD in $file, skipping.\n"
478 if($verbose);
479 return 0;
482 return 1;
485 =head1 AUTHOR
487 Marek Rouchal E<lt>marek@saftsack.fs.uni-bayreuth.deE<gt>,
488 heavily borrowing code from Nick Ing-Simmons' PodToHtml.
490 Tim Jenness E<lt>t.jenness@jach.hawaii.eduE<gt> provided
491 C<pod_where> and C<contains_pod>.
493 =head1 SEE ALSO
495 L<Pod::Parser>, L<Pod::Checker>, L<perldoc>
497 =cut