Pod/FindPods.pm untested

filter: Statementstmt 0.0% 0 / 312 Branchbran 0.0% 0 / 146 Conditioncond 0.0% 0 / 67 MC/DCmcdc 0.0% 0 / 40 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 608 CC 73 SCAR 59.9
CC
73
Cov
0%
pod_find
1122.0
function_pod
132.0
guess_architectures
56.0
CRAP 399.5
1 # -*- perl -*-
2  
3 #
4 # Author: Slaven Rezic
5 #
6 # Copyright (C) 2001,2003,2004,2005,2007,2009,2012 Slaven Rezic. All rights reserved.
7 # This package is free software; you can redistribute it and/or modify
8 # it under the same terms as Perl itself.
9 #
10 # Mail: slaven@rezic.de
11 # WWW: http://www.rezic.de/eserte/
12 #
13  
14 package Tk::Pod::FindPods;
15  
16 =head1 NAME
17  
18 Tk::Pod::FindPods - find Pods installed on the current system
19  
20  
21 =head1 SYNOPSIS
22  
23 use Tk::Pod::FindPods;
24  
25 my $o = Tk::Pod::FindPods->new;
26 $pods = $o->pod_find(-categorized => 1, -usecache => 1);
27  
28 =head1 DESCRIPTION
29  
30 =cut
31  
32 use base 'Exporter';
33 use strict;
34 use vars qw($VERSION @EXPORT_OK $init_done %arch $arch_re);
35  
36 @EXPORT_OK = qw/%pods $has_cache pod_find/;
37  
38 $VERSION = '5.16';
39  
40 BEGIN { # Make a DEBUG constant very first thing...
41 if(defined &DEBUG) {
42 } elsif(($ENV{'TKPODDEBUG'} || '') =~ m/^(\d+)/) { # untaint
43 my $debug = $1;
44 *DEBUG = sub () { $debug };
45 } else {
46 *DEBUG = sub () {0};
47 }
48 }
49  
50 use File::Find;
51 use File::Spec;
52 use File::Basename;
53 use Config;
54  
55 sub new {
56 my($class) = @_;
57 my $self = bless {}, $class;
58 $self->init;
59 $self;
60 }
61  
62 sub init {
63 return if $init_done;
64 %arch = guess_architectures();
65 $arch_re = "(" . join("|", map { quotemeta $_ } ("mach", keys %arch)) . ")";
66 $init_done++;
67 }
68  
69 =head2 pod_find
70  
71 The B<pod_find> method scans the current system for available Pod
72 documentation. The keys of the returned hash reference are the names
73 of the modules or Pods (C<::> substituted by C</> --- this makes it
74 easier for Tk::Pod::Tree, as the separator may only be of one
75 character). The values are the corresponding filenames.
76  
77 If C<-categorized> is specified, then the returned hash has an extra
78 level with four categories: B<perl> (for core language documentation),
79 B<pragma> (for pragma documentation like L<var|var> or
80 L<strict|strict>), B<mod> (core or CPAN modules), and B<script> (perl
81 scripts with embedded Pod documentation). Otherwise, C<-category> may
82 be set to force the Pods into a category.
83  
84 By default, C<@INC> is scanned for Pods. This can be overwritten by
85 the C<-directories> option (specify as an array reference).
86  
87 If C<-usecache> is specified, then the list of Pods is cached (see
88 L<cache directory|/Cache directory>). C<-usecache> is disabled if
89 C<-categorized> is not set or C<-directories> is set.
90  
91 =cut
92  
93 sub pod_find {
94 my $self = shift;
95 my(@args) = @_;
96 my %args;
97 if (ref $args[0] eq 'HASH') {
98 %args = %{ $args[0] };
99 } else {
100 %args = @args;
101 }
102  
103 $self->{has_cache} = 0;
104  
105 if ($args{-usecache}) {
106 if (!$args{-categorized} || $args{-directories}) {
107 DEBUG and warn "Disabling -usecache";
108 } else {
109 my $perllocal_site = File::Spec->catfile($Config{'installsitearch'},'perllocal.pod');
110 my $perllocal_lib = File::Spec->catfile($Config{'installarchlib'},'perllocal.pod');
111 my $cache_file = _cache_file();
112 VALIDATE_CACHE: {
113 if (!-r $cache_file) {
114 DEBUG and warn "Cache file $cache_file does not exist or is not readable\n";
115 last VALIDATE_CACHE;
116 }
117 if (-e $perllocal_site && -M $perllocal_site < -M $cache_file) {
118 DEBUG and warn "$perllocal_site is more recent than cache file $cache_file\n";
119 last VALIDATE_CACHE;
120 }
121 if (-e $perllocal_lib && -M $perllocal_lib < -M $cache_file) {
122 DEBUG and warn "$perllocal_lib is more recent than cache file $cache_file\n";
123 last VALIDATE_CACHE;
124 }
125  
126 $self->LoadCache;
127 if ($self->{pods}) {
128 $self->{has_cache} = 1;
129 return $self->{pods};
130 }
131 }
132 }
133 }
134  
135 my(@dirs, @script_dirs);
136 if ($args{-directories}) {
137 @dirs = @{ $args{-directories} };
138 @script_dirs = ();
139 } else {
140 @dirs = sort { length($b) <=> length($a) } grep { $_ ne '.' } @INC; # ignore current directory
141 @script_dirs = ($Config{'scriptdir'});
142 }
143  
144 my %seen_dir = ();
145 my $curr_dir;
146 undef $curr_dir;
147 my %pods = ();
148  
149 if ($args{-category}) {
150 $pods{$args{-category}} = {};
151 }
152  
153 my $duplicate_warning_header_seen = 0;
154  
155 # Assume $_ and $File::Find::name are set
156 my $ignore_directory = sub {
157 return 1 if m{^(RCS|CVS|\.svn|\.git|blib)$};
158 };
159  
160 my $wanted = sub {
161 if (-d) {
162 if ($ignore_directory->()) {
163 $File::Find::prune = 1;
164 return;
165 } elsif ($seen_dir{$File::Find::name}) {
166 $File::Find::prune = 1;
167 return;
168 } else {
169 $seen_dir{$File::Find::name}++;
170 }
171 }
172  
173 if (-f && /\.(pod|pm)$/) {
174 my $curr_dir_rx = quotemeta $curr_dir;
175 (my $name = $File::Find::name) =~ s|^$curr_dir_rx/?||;
176 $name = simplify_name($name);
177  
178 my $hash;
179 if ($args{-categorized}) {
180 my $type = type($name);
181 $hash = $pods{$type} || do { $pods{$type} = {} };
182 } elsif ($args{-category}) {
183 $hash = $pods{$args{-category}};
184 } else {
185 $hash = \%pods;
186 }
187  
188 if (exists $hash->{$name}) {
189 if ($hash->{$name} =~ /\.pod$/ && $File::Find::name =~ /\.pm$/) {
190 return;
191 }
192 my($ext1) = $hash->{$name} =~ /\.(.*)$/;
193 my($ext2) = $File::Find::name =~ /\.(.*)$/;
194 if ($ext1 eq $ext2) {
195 (my $modname = $name) =~ s{/}{::}g;
196 if (!$duplicate_warning_header_seen) {
197 $duplicate_warning_header_seen = 1;
198 warn "*** Pod(s) with same name at different locations found: ***\n";
199 }
200 (my $hash_name_without_scheme = $hash->{$name}) =~ s{^file:}{};
201 warn " $modname:\n $hash_name_without_scheme\n $File::Find::name\n";
202 return;
203 }
204 }
205 $hash->{$name} = "file:" . $File::Find::name;
206 }
207 };
208  
209 my $wanted_scripts = sub {
210 if (-d) {
211 if ($ignore_directory->()) {
212 $File::Find::prune = 1;
213 return;
214 } elsif ($seen_dir{$File::Find::name}) {
215 $File::Find::prune = 1;
216 return;
217 } else {
218 $seen_dir{$File::Find::name}++;
219 }
220 }
221  
222 if (-T && open(SCRIPT, $_)) {
223 my $has_pod = 0;
224 {
225 local $_;
226 while(<SCRIPT>) {
227 if (/^=(head\d+|pod)/) {
228 $has_pod = 1;
229 last;
230 }
231 }
232 }
233 close SCRIPT;
234 if ($has_pod) {
235 my $name = $_;
236  
237 my $hash;
238 if ($args{-categorized}) {
239 my $type = 'script';
240 $hash = $pods{$type} || do { $pods{$type} = {} };
241 } elsif ($args{-category}) {
242 $hash = $pods{$args{-category}};
243 } else {
244 $hash = \%pods;
245 }
246  
247 if (exists $hash->{$name}) {
248 return;
249 }
250 $hash->{$name} = "file:" . $File::Find::name;
251 }
252 }
253 };
254  
255 my %opts;
256 if ($^O ne "MSWin32") {
257 $opts{follow} = 1;
258 $opts{follow_skip} = 2;
259 }
260  
261 foreach my $inc (reverse @dirs) {
262 next unless -d $inc;
263 $curr_dir = $inc;
264 find({ %opts, wanted => $wanted }, $inc);
265 }
266  
267 foreach my $inc (reverse @script_dirs) {
268 find({ %opts, wanted => $wanted_scripts }, $inc);
269 }
270  
271 if ($duplicate_warning_header_seen) {
272 warn "*** This was the list of Pod(s) with same name at different locations. ***\n";
273 }
274  
275 $self->{pods} = \%pods;
276 $self->{pods};
277 }
278  
279 sub simplify_name {
280 my $f = shift;
281 $f =~ s|^\d+\.\d+\.\d+/?||; # strip perl version
282 $f =~ s|^$arch_re/|| if defined $arch_re; # strip machine
283 $f =~ s/\.(pod|pm)$//;
284 $f =~ s|^pod/||;
285 # Workaround for case insensitive systems --- the pod directory contains
286 # general pod documentation as well as Pod::* documentation:
287 if ($^O =~ /^cygwin/) {
288 $f =~ s|^pods/||; # "pod" is "pods" on cygwin
289 } elsif ($^O =~ /^darwin/) {
290 $f =~ s|^pods/||; # ... and on MacOSX
291 } elsif ($^O eq 'MSWin32') {
292 # oldstyle:
293 $f =~ s|^pod/perl|perl|i;
294 $f =~ s|^pod/Win32|Win32|i;
295 # newstyle:
296 $f =~ s|^pods/||;
297 }
298 $f;
299 }
300  
301 sub type {
302 local $_ = shift;
303 if (/^(?:perl|activeperl)/) { return "perl" }
304 elsif (/^a2p$/) { return "script" }
305 elsif (/^[a-z]/ && !/^(mod_perl|lwpcook|lwptut|cgi_to_mod_perl|libapreq)/)
306 { return "pragma" }
307 else { return "mod" }
308 }
309  
310 # It's not possible to just use $Config{archname} --- it is necessary
311 # to get the names of all the installated archnames. This may be
312 # something like i386-freebsd vs. i386-freebsd-64int.
313 sub guess_architectures {
314 my %arch;
315 my @configs;
316 foreach my $inc (@INC) {
317 next unless -d $inc;
318 if (!opendir(DIR, $inc)) {
319 warn "Can't opendir $inc: $!";
320 next;
321 }
322 while(defined(my $base = readdir DIR)) {
323 # Skip . and .., and some obviously wrong directories
324 # containing a Config.pm file. This is not strictly necessary,
325 # but so we avoid to scan the file itself.
326 next if $base =~ /^(\.|\.\.|CPANPLUS|Encode|Prima|Tk|PDL|Template|Net|App)$/;
327 next if !-d File::Spec->catdir($inc, $base);
328 my $cfgpm = File::Spec->catfile($inc, $base, "Config.pm");
329 if (-r $cfgpm) {
330 push @configs, $cfgpm;
331 }
332 }
333 closedir DIR;
334 }
335  
336 # Scan the Config.pm file to see if it's really a perl Config.pm
337 # file.
338 foreach my $config (@configs) {
339 my($arch) = $config =~ m|[\\/]([^/\\]+)[\\/]Config.pm|;
340 if (open(CFG, $config)) {
341 while(<CFG>) {
342 /archname.*$arch/ && do {
343 $arch{$arch}++;
344 last;
345 };
346 }
347 close CFG;
348 } else {
349 warn "cannot open $config: $!";
350 }
351 }
352 %arch;
353 }
354  
355 sub module_location {
356 my $mod = shift;
357 my($type, $path) = $mod =~ /^([^:]+):(.*)/;
358 if ($type eq 'cpan') {
359 'cpan';
360 } elsif (is_site_module($path)) {
361 'site';
362 } elsif (is_vendor_module($path)) {
363 'vendor';
364 } else {
365 'core';
366 }
367 }
368  
369 sub is_site_module {
370 my $path = shift;
371 if ($^O eq 'MSWin32') {
372 return $path =~ m|[/\\]site[/\\]lib[/\\]|;
373 }
374 $path =~ /^(
375 \Q$Config{'installsitelib'}\E
376 |
377 \Q$Config{'installsitearch'}\E
378 )/x;
379 }
380  
381 sub is_vendor_module {
382 my $path = shift;
383 return 0 if (!defined $Config{'installvendorlib'} ||
384 $Config{'installvendorlib'} eq '' ||
385 !defined $Config{'installvendorarch'} ||
386 $Config{'installvendorarch'} eq ''
387 );
388 $path =~ /^(
389 \Q$Config{'installvendorlib'}\E
390 |
391 \Q$Config{'installvendorarch'}\E
392 )/x;
393 }
394  
395 sub _cache_file {
396 (my $ver = $]) =~ s/[^a-z0-9]/_/gi;
397 (my $os = $Config{'archname'}) =~ s/[^a-z0-9]/_/gi;
398 my $uid = $<;
399  
400 my $cache_file_pattern = $ENV{TKPODCACHE};
401 if (!defined $cache_file_pattern) {
402 my $cache_root;
403 if ($^O =~ m{^(darwin|MSWin32)} && eval { require File::HomeDir; 1 }) {
404 $cache_root = File::Spec->catfile(File::HomeDir->my_data, ".tkpod_cache");
405 } elsif ($ENV{HOME} && -d $ENV{HOME}) {
406 $cache_root = "$ENV{HOME}/.tkpod_cache";
407 } else {
408 $cache_root = File::Spec->can('tmpdir') ? File::Spec->tmpdir : $ENV{TMPDIR}||"/tmp";
409 }
410 $cache_file_pattern = File::Spec->catfile
411 ($cache_root,
412 join('_', 'pods',"%v","%o","%u")
413 );
414 }
415 $cache_file_pattern =~ s/%v/$ver/g;
416 $cache_file_pattern =~ s/%o/$os/g;
417 $cache_file_pattern =~ s/%u/$uid/g;
418 $cache_file_pattern;
419 }
420  
421 sub pods { shift->{pods} }
422 sub has_cache { shift->{has_cache} }
423  
424 # Parts stolen from Pod::Perldoc::search_perlfunc
425 # Return pod text for given function
426 sub function_pod {
427 my($self, $func) = @_;
428  
429 my $pod = "";
430  
431 my $perlfunc = $self->{pods}{perl}{perlfunc};
432 $perlfunc =~ s{^file:}{};
433 open(PFUNC, "< $perlfunc") or die "Can't open $perlfunc: $!";
434  
435 # Functions like -r, -e, etc. are listed under `-X'.
436 my $search_re = ($func =~ /^-[rwxoRWXOeszfdlpSbctugkTBMAC]$/)
437 ? '(?:I<)?-X' : quotemeta($func) ;
438  
439 # Skip introduction
440 local $_;
441 while (<PFUNC>) {
442 last if /^=head2 Alphabetical Listing of Perl Functions/;
443 }
444  
445 # Look for our function
446 my $found = 0;
447 my $inlist = 0;
448 while (<PFUNC>) { # "The Mothership Connection is here!"
449 if ( m/^=item\s+$search_re\W/ ) {
450 $found = 1;
451 }
452 elsif (/^=item/) {
453 last if $found > 1 and not $inlist;
454 }
455 next unless $found;
456 if (/^=over/) {
457 ++$inlist;
458 }
459 elsif (/^=back/) {
460 --$inlist;
461 }
462 $pod .= $_;
463 ++$found if /^\w/; # found descriptive text
464 }
465 if ($pod eq "") {
466 warn sprintf "No documentation for perl function `%s' found\n", $func;
467 } else {
468 # Fix pod so no warnings are given:
469 $pod = "=over\n\n$pod\n\n=back\n";
470 }
471 close PFUNC or die "Can't open $perlfunc: $!";
472  
473 return $pod;
474 }
475  
476 =head2 WriteCache
477  
478 Write the Pod cache. The cache is written to the L<cache
479 directory|/Cache directory>. The file name is constructed from the
480 perl version, operation system and user id.
481  
482 =cut
483  
484 sub WriteCache {
485 my $self = shift;
486  
487 require Data::Dumper;
488  
489 my $cache_dir = dirname _cache_file();
490 if (!-d $cache_dir) {
491 mkdir $cache_dir, 0777
492 or do {
493 warn "Can't create cache directory $cache_dir: $!";
494 return;
495 };
496 }
497 if (!open(CACHE, ">" . _cache_file())) {
498 warn "Can't write to cache file " . _cache_file() . ": $!";
499 return;
500 }
501  
502 my $dd = Data::Dumper->new([$self->{pods}], ['pods']);
503 $dd->Indent(0);
504 print CACHE $dd->Dump;
505 close CACHE;
506 }
507  
508 =head2 LoadCache()
509  
510 Load the Pod cache, if possible.
511  
512 =cut
513  
514 sub LoadCache {
515 my $self = shift;
516 my $cache_file = _cache_file();
517 if (-r $cache_file) {
518 return if $< != (stat($cache_file))[4];
519 require Safe;
520 my $c = Safe->new('Tk::Pod::FindPods::SAFE');
521 $c->rdo($cache_file);
522 if (keys %$Tk::Pod::FindPods::SAFE::pods) {
523 $self->{pods} = { %$Tk::Pod::FindPods::SAFE::pods };
524 return $self->{pods};
525 }
526 }
527 return {};
528 }
529  
530 return 1 if caller;
531  
532 package main;
533  
534 require Data::Dumper;
535 print Data::Dumper->Dumpxs([Tk::Pod::FindPods->new->pod_find(-categorized => 0, -usecache => 0)],[]);
536  
537 __END__