35e6b02f44f60e1926cb1cb402c8b76a26af51ac
[dbsrgits/DBIx-Class.git] / t / 00describe_environment.t
1 ###
2 ### This version is rather 5.8-centric, because DBIC itself is 5.8
3 ### It certainly can be rewritten to degrade well on 5.6
4 ###
5
6 # Very important to grab the snapshot early, as we will be reporting
7 # the INC indices from the POV of whoever ran the script, *NOT* from
8 # the POV of the internals
9 my @initial_INC;
10 BEGIN {
11   @initial_INC = @INC;
12 }
13
14 BEGIN {
15   unshift @INC, 't/lib';
16
17   if ( "$]" < 5.010) {
18
19     # Pre-5.10 perls pollute %INC on unsuccesfull module
20     # require, making it appear as if the module is already
21     # loaded on subsequent require()s
22     # Can't seem to find the exact RT/perldelta entry
23     #
24     # The reason we can't just use a sane, clean loader, is because
25     # if a Module require()s another module the %INC will still
26     # get filled with crap and we are back to square one. A global
27     # fix is really the only way for this test, as we try to load
28     # each available module separately, and have no control (nor
29     # knowledge) over their common dependencies.
30     #
31     # we want to do this here, in the very beginning, before even
32     # warnings/strict are loaded
33
34     require DBICTest::Util::OverrideRequire;
35
36     DBICTest::Util::OverrideRequire::override_global_require( sub {
37       my $res = eval { $_[0]->() };
38       if ($@ ne '') {
39         delete $INC{$_[1]};
40         die $@;
41       }
42       return $res;
43     } );
44   }
45 }
46
47 use strict;
48 use warnings;
49
50 use Test::More 'no_plan';
51 use Config;
52 use File::Find 'find';
53 use Digest::MD5 ();
54 use Cwd 'abs_path';
55 use File::Spec;
56 use List::Util 'max';
57 use ExtUtils::MakeMaker;
58
59 use DBICTest::RunMode;
60 use DBICTest::Util 'visit_namespaces';
61 use DBIx::Class::Optional::Dependencies;
62
63 my $known_paths = {
64   SA => {
65     config_key => 'sitearch',
66   },
67   SL => {
68     config_key => 'sitelib',
69   },
70   SS => {
71     config_key => 'sitelib_stem',
72     match_order => 1,
73   },
74   SP => {
75     config_key => 'siteprefix',
76     match_order => 2,
77   },
78   VA => {
79     config_key => 'vendorarch',
80   },
81   VL => {
82     config_key => 'vendorlib',
83   },
84   VS => {
85     config_key => 'vendorlib_stem',
86     match_order => 3,
87   },
88   VP => {
89     config_key => 'vendorprefix',
90     match_order => 4,
91   },
92   PA => {
93     config_key => 'archlib',
94   },
95   PL => {
96     config_key => 'privlib',
97   },
98   PP => {
99     config_key => 'prefix',
100     match_order => 5,
101   },
102   BLA => {
103     rel_path => './blib/arch',
104     skip_unversioned_modules => 1,
105   },
106   BLL => {
107     rel_path => './blib/lib',
108     skip_unversioned_modules => 1,
109   },
110   INC => {
111     rel_path => './inc',
112   },
113   LIB => {
114     rel_path => './lib',
115     skip_unversioned_modules => 1,
116   },
117   T => {
118     rel_path => './t',
119     skip_unversioned_modules => 1,
120   },
121   XT => {
122     rel_path => './xt',
123     skip_unversioned_modules => 1,
124   },
125   CWD => {
126     rel_path => '.',
127   },
128   HOME => {
129     rel_path => '~',
130     abs_unix_path => abs_unix_path (
131       eval { require File::HomeDir and File::HomeDir->my_home }
132         ||
133       $ENV{USERPROFILE}
134         ||
135       $ENV{HOME}
136         ||
137       glob('~')
138     ),
139   },
140 };
141
142 for my $k (keys %$known_paths) {
143   my $v = $known_paths->{$k};
144
145   # never use home as a found-in-dir marker - it is too broad
146   # HOME is only used by the shortener
147   $v->{marker} = $k unless $k eq 'HOME';
148
149   unless ( $v->{abs_unix_path} ) {
150     if ( $v->{rel_path} ) {
151       $v->{abs_unix_path} = abs_unix_path( $v->{rel_path} );
152     }
153     elsif ( $Config{ $v->{config_key} || '' } ) {
154       $v->{abs_unix_path} = abs_unix_path (
155         $Config{"$v->{config_key}exp"} || $Config{$v->{config_key}}
156       );
157     }
158   }
159
160   delete $known_paths->{$k} unless $v->{abs_unix_path} and -d $v->{abs_unix_path};
161 }
162 my $seen_markers = {};
163
164 # first run through lib/ and *try* to load anything we can find
165 # within our own project
166 find({
167   wanted => sub {
168     -f $_ or return;
169
170     # can't just `require $fn`, as we need %INC to be
171     # populated properly
172     my ($mod) = $_ =~ /^ lib [\/\\] (.+) \.pm $/x
173       or return;
174
175     try_module_require(join ('::', File::Spec->splitdir($mod)) )
176   },
177   no_chdir => 1,
178 }, 'lib' );
179
180
181
182 # now run through OptDeps and attempt loading everything else
183 #
184 # some things needs to be sorted before other things
185 # positive - load first
186 # negative - load last
187 my $load_weights = {
188   # Make sure oracle is tried last - some clients (e.g. 10.2) have symbol
189   # clashes with libssl, and will segfault everything coming after them
190   "DBD::Oracle" => -999,
191 };
192
193 my @known_modules = sort
194   { ($load_weights->{$b}||0) <=> ($load_weights->{$a}||0) }
195   keys %{
196     DBIx::Class::Optional::Dependencies->req_list_for([
197       grep
198         # some DBDs are notoriously problematic to load
199         # hence only show stuff based on test_rdbms which will
200         # take into account necessary ENVs
201         { $_ !~ /^ (?: rdbms | dist )_ /x }
202         keys %{DBIx::Class::Optional::Dependencies->req_group_list}
203     ])
204   }
205 ;
206
207 try_module_require($_) for @known_modules;
208
209 my $has_versionpm = eval { require version };
210
211
212 # At this point we've loaded everything we ever could, but some modules
213 # (understandably) crapped out. For an even more thorough report, note
214 # everthing present in @INC we excplicitly know about (via OptDeps)
215 # *even though* it didn't load
216 my $known_failed_loads;
217
218 for my $mod (@known_modules) {
219   my $inc_key = module_notional_filename($mod);
220   next if defined $INC{$inc_key};
221
222   if (defined( my $idx = module_found_at_inc_index( $mod, \@INC ) ) ) {
223     $known_failed_loads->{$mod} = abs_unix_path( "$INC[$idx]/$inc_key" );
224   }
225
226 }
227
228 my $perl = 'perl';
229
230 # This is a cool idea, but the line is too long even with shortening :(
231 #
232 #for my $i ( 1 .. $Config{config_argc} ) {
233 #  my $conf_arg = $Config{"config_arg$i"};
234 #  $conf_arg =~ s!
235 #    \= (.+)
236 #  !
237 #    '=' . shorten_fn($1)
238 #  !ex;
239 #
240 #  $perl .= " $conf_arg";
241 #}
242
243 my $interesting_modules = {
244   # pseudo module
245   $perl => {
246     version => $],
247     abs_unix_path => abs_unix_path($^X),
248   }
249 };
250
251
252 # drill through the *ENTIRE* symtable and build a map of interesting modules
253 visit_namespaces( action => sub {
254   no strict 'refs';
255   my $pkg = shift;
256
257   # keep going, but nothing to see here
258   return 1 if $pkg eq 'main';
259
260   # private - not interested, including no further descent
261   return 0 if $pkg =~ / (?: ^ | :: ) _ /x;
262
263   my $inc_key = module_notional_filename($pkg);
264
265   my $abs_unix_path = (
266     $INC{$inc_key}
267       and
268     -f $INC{$inc_key}
269       and
270     -r $INC{$inc_key}
271       and
272     abs_unix_path($INC{$inc_key})
273   );
274
275   # handle versions first (not interested in synthetic classes)
276   if (
277     defined ${"${pkg}::VERSION"}
278       and
279     ${"${pkg}::VERSION"} !~ /\Qset by base.pm/
280   ) {
281
282     # make sure a version can be extracted, be noisy when it doesn't work
283     # do this even if we are throwing away the result below in lieu of EUMM
284     my $mod_ver = eval { $pkg->VERSION };
285
286     if (my $err = $@) {
287       $err =~ s/^/  /mg;
288       say_err (
289         "Calling `$pkg->VERSION` resulted in an exception, which should never "
290       . "happen - please file a bug with the distribution containing $pkg. "
291       . "Complete exception text below:\n\n$err"
292       );
293     }
294     elsif( ! defined $mod_ver or ! length $mod_ver ) {
295       my $ret = defined $mod_ver
296         ? "the empty string ''"
297         : "'undef'"
298       ;
299
300       say_err (
301         "Calling `$pkg->VERSION` returned $ret, even though \$${pkg}::VERSION "
302       . "is defined, which should never happen - please file a bug with the "
303       . "distribution containing $pkg."
304       );
305
306       undef $mod_ver;
307     }
308
309     if (
310       $abs_unix_path
311         and
312       defined ( my $eumm_ver = eval { MM->parse_version( $abs_unix_path ) } )
313     ) {
314
315       # can only run the check reliably if v.pm is there
316       if (
317         $has_versionpm
318           and
319         defined $mod_ver
320           and
321         $eumm_ver ne $mod_ver
322           and
323         (
324           ( eval { version->parse( do { (my $v = $eumm_ver) =~ s/_//g; $v } ) } || 0 )
325             !=
326           ( eval { version->parse( do { (my $v = $mod_ver) =~ s/_//g; $v } ) } || 0 )
327         )
328       ) {
329         say_err (
330           "Mismatch of versions '$mod_ver' and '$eumm_ver', obtained respectively "
331         . "via `$pkg->VERSION` and parsing the version out of @{[ shorten_fn( $abs_unix_path ) ]} "
332         . "with ExtUtils::MakeMaker\@@{[ ExtUtils::MakeMaker->VERSION ]}. "
333         . "This should never happen - please check whether this is still present "
334         . "in the latest version, and then file a bug with the distribution "
335         . "containing $pkg."
336         );
337       }
338
339       $interesting_modules->{$pkg}{version} = $eumm_ver;
340     }
341     elsif( defined $mod_ver ) {
342
343       $interesting_modules->{$pkg}{version} = $mod_ver;
344     }
345   }
346   elsif ( $known_failed_loads->{$pkg} ) {
347     $abs_unix_path = $known_failed_loads->{$pkg};
348     $interesting_modules->{$pkg}{version} = '!! LOAD FAIL !!';
349   }
350
351   if ($abs_unix_path) {
352     my ($marker, $initial_inc_idx);
353
354     my $current_inc_idx = module_found_at_inc_index($pkg, \@INC);
355     my $p = subpath_of_known_path( $abs_unix_path );
356
357     if (
358       defined $current_inc_idx
359         and
360       $p->{marker}
361         and
362       abs_unix_path($INC[$current_inc_idx]) eq $p->{abs_unix_path}
363     ) {
364       $marker = $p->{marker};
365     }
366     elsif (defined ( $initial_inc_idx = module_found_at_inc_index($pkg, \@initial_INC) ) ) {
367       $marker = "\$INC[$initial_inc_idx]";
368     }
369
370     # we are only interested if there was a declared version already above
371     # OR if the module came from somewhere other than skip_unversioned_modules
372     if (
373       $marker
374         and
375       (
376         $interesting_modules->{$pkg}
377           or
378         !$p->{skip_unversioned_modules}
379       )
380     ) {
381       $interesting_modules->{$pkg}{source_marker} = $marker;
382       $seen_markers->{$marker} = 1;
383     }
384
385     # at this point only fill in the path (md5 calc) IFF it is interesting
386     # in any respect
387     $interesting_modules->{$pkg}{abs_unix_path} = $abs_unix_path
388       if $interesting_modules->{$pkg};
389   }
390
391   1;
392 });
393
394 # compress identical versions sourced from ./blib, ./lib, ./t and ./xt
395 # as close to the root of a namespace as we can
396 purge_identically_versioned_submodules_with_markers([ map {
397   ( $_->{skip_unversioned_modules} && $_->{marker} ) || ()
398 } values %$known_paths ]);
399
400 ok 1, (scalar keys %$interesting_modules) . " distinctly versioned modules found";
401
402 # do not announce anything under ci - we are watching for STDERR silence
403 exit 0 if DBICTest::RunMode->is_ci;
404
405
406 # diag the result out
407 my $max_ver_len = max map
408   { length "$_" }
409   ( 'xxx.yyyzzz_bbb', map { $_->{version} || '' } values %$interesting_modules )
410 ;
411 my $max_marker_len = max map { length $_ } ( '$INC[999]', keys %$seen_markers );
412
413 my $discl = <<'EOD';
414
415 List of loadable modules within both the core and *OPTIONAL* dependency chains
416 present on this system (modules sourced from ./blib, ./lib, ./t, and ./xt
417 with versions identical to their parent namespace were omitted for brevity)
418
419     *** Note that *MANY* of these modules will *NEVER* be loaded ***
420             *** during normal operation of DBIx::Class ***
421 EOD
422
423 # pre-assemble everything and print it in one shot
424 # makes it less likely for parallel test execution to insert bogus lines
425 my $final_out = "\n$discl\n";
426
427 $final_out .= "\@INC at startup (does not reflect manipulation at runtime):\n";
428
429 my $in_inc_skip;
430 for (0.. $#initial_INC) {
431
432   my $shortname = shorten_fn( $initial_INC[$_] );
433
434   # when *to* print a line of INC
435   if (
436     ! $ENV{AUTOMATED_TESTING}
437       or
438     @initial_INC < 11
439       or
440     $seen_markers->{"\$INC[$_]"}
441       or
442     ! -e $shortname
443       or
444     ! File::Spec->file_name_is_absolute($shortname)
445   ) {
446     $in_inc_skip = 0;
447     $final_out .= sprintf ( "% 3s: %s\n",
448       $_,
449       $shortname
450     );
451   }
452   elsif(! $in_inc_skip++) {
453     $final_out .= "  ...\n";
454   }
455 }
456
457 $final_out .= "\n";
458
459 if (my @seen_known_paths = grep { $known_paths->{$_} } keys %$seen_markers) {
460
461   $final_out .= join "\n", 'Sourcing markers:', (map
462     {
463       sprintf "%*s: %s",
464         $max_marker_len => $_->{marker},
465         ($_->{config_key} ? "\$Config{$_->{config_key}}" : "$_->{rel_path}/" )
466     }
467     sort
468       {
469         !!$b->{config_key} cmp !!$a->{config_key}
470           or
471         ( $a->{marker}||'') cmp ($b->{marker}||'')
472       }
473       @{$known_paths}{@seen_known_paths}
474   ), '', '';
475
476 }
477
478 $final_out .= "=============================\n";
479
480 $final_out .= join "\n", (map
481   { sprintf (
482     "%*s  %*s  %*s%s",
483     $max_marker_len => $interesting_modules->{$_}{source_marker} || '',
484     $max_ver_len => ( defined $interesting_modules->{$_}{version}
485       ? $interesting_modules->{$_}{version}
486       : ''
487     ),
488     -78 => $_,
489     ($interesting_modules->{$_}{abs_unix_path}
490       ? "  [ MD5: @{[ get_md5( $interesting_modules->{$_}{abs_unix_path} ) ]} ]"
491       : "! -f \$INC{'@{[ module_notional_filename($_) ]}'}"
492     ),
493   ) }
494   sort { lc($a) cmp lc($b) } keys %$interesting_modules
495 ), '';
496
497 $final_out .= "=============================\n$discl\n\n";
498
499 diag $final_out;
500
501 exit 0;
502
503
504
505 sub say_err { print STDERR "\n", @_, "\n\n" };
506
507 # do !!!NOT!!! use Module::Runtime's require_module - it breaks CORE::require
508 sub try_module_require {
509   # trap deprecation warnings and whatnot
510   local $SIG{__WARN__} = sub {};
511   local $@;
512   eval "require $_[0]";
513 }
514
515 sub abs_unix_path {
516   return '' unless (
517     defined $_[0]
518       and
519     ( -e $_[0] or File::Spec->file_name_is_absolute($_[0]) )
520   );
521
522   # File::Spec's rel2abs does not resolve symlinks
523   # we *need* to look at the filesystem to be sure
524   my $abs_fn = abs_path($_[0]);
525
526   if ( $^O eq 'MSWin32' and $abs_fn ) {
527
528     # sometimes we can get a short/longname mix, normalize everything to longnames
529     $abs_fn = Win32::GetLongPathName($abs_fn);
530
531     # Fixup (native) slashes in Config not matching (unixy) slashes in INC
532     $abs_fn =~ s|\\|/|g;
533   }
534
535   $abs_fn;
536 }
537
538 sub shorten_fn {
539   my $fn = shift;
540
541   my $abs_fn = abs_unix_path($fn);
542
543   if (my $p = subpath_of_known_path( $fn ) ) {
544     $abs_fn =~ s| (?<! / ) $|/|x
545       if -d $abs_fn;
546
547     if ($p->{rel_path}) {
548       $abs_fn =~ s!\Q$p->{abs_unix_path}!$p->{rel_path}!
549         and return $abs_fn;
550     }
551     elsif ($p->{config_key}) {
552       $abs_fn =~ s!\Q$p->{abs_unix_path}!<<$p->{marker}>>!
553         and
554       $seen_markers->{$p->{marker}} = 1
555         and
556       return $abs_fn;
557     }
558   }
559
560   # we got so far - not a known path
561   # return the unixified version it if was absolute, leave as-is otherwise
562   my $rv = ( $abs_fn and File::Spec->file_name_is_absolute( $fn ) )
563     ? $abs_fn
564     : $fn
565   ;
566
567   $rv = "( ! -e ) $rv" unless -e $rv;
568
569   return $rv;
570 }
571
572 sub subpath_of_known_path {
573   my $abs_fn = abs_unix_path( $_[0] )
574     or return '';
575
576   for my $p (
577     sort {
578       length( $b->{abs_unix_path} ) <=> length( $a->{abs_unix_path} )
579         or
580       ( $a->{match_order} || 0 ) <=> ( $b->{match_order} || 0 )
581     }
582     values %$known_paths
583   ) {
584     # run through the matcher twice - first always append a /
585     # then try without
586     # important to avoid false positives
587     for my $suff ( '/', '' ) {
588       return { %$p } if 0 == index( $abs_fn, "$p->{abs_unix_path}$suff" );
589     }
590   }
591 }
592
593 sub module_found_at_inc_index {
594   my ($mod, $inc_dirs) = @_;
595
596   return undef unless @$inc_dirs;
597
598   my $fn = module_notional_filename($mod);
599
600   for my $i ( 0 .. $#$inc_dirs ) {
601
602     # searching from here on out won't mean anything
603     # FIXME - there is actually a way to interrogate this safely, but
604     # that's a fight for another day
605     return undef if length ref $inc_dirs->[$i];
606
607     if (
608       -d $inc_dirs->[$i]
609         and
610       -f "$inc_dirs->[$i]/$fn"
611         and
612       -r "$inc_dirs->[$i]/$fn"
613     ) {
614       return $i;
615     }
616   }
617
618   return undef;
619 }
620
621 sub purge_identically_versioned_submodules_with_markers {
622   my $markers = shift;
623
624   return unless @$markers;
625
626   for my $mod ( sort { length($b) <=> length($a) } keys %$interesting_modules ) {
627
628     next unless defined $interesting_modules->{$mod}{version};
629
630     my $marker = $interesting_modules->{$mod}{source_marker}
631       or next;
632
633     next unless grep { $marker eq $_ } @$markers;
634
635     my $parent = $mod;
636
637     while ( $parent =~ s/ :: (?: . (?! :: ) )+ $ //x ) {
638       $interesting_modules->{$parent}
639         and
640       ($interesting_modules->{$parent}{version}||'') eq $interesting_modules->{$mod}{version}
641         and
642       ($interesting_modules->{$parent}{source_marker}||'') eq $interesting_modules->{$mod}{source_marker}
643         and
644     delete $interesting_modules->{$mod}
645         and
646       last
647     }
648   }
649 }
650
651 sub module_notional_filename {
652   (my $fn = $_[0] . '.pm') =~ s|::|/|g;
653   $fn;
654 }
655
656 sub get_md5 {
657   # we already checked for -r/-f, just bail if can't open
658   open my $fh, '<:raw', $_[0] or return '';
659   Digest::MD5->new->addfile($fh)->hexdigest;
660 }