Allow base.pm to be used with packages that don't exist on dist
[scpubgit/Object-Remote.git] / lib / Object / Remote / ModuleLoader.pm
1 package Object::Remote::ModuleLoader;
2
3 BEGIN {
4   package Object::Remote::ModuleLoader::Hook;
5   use Moo;
6   use Object::Remote::Logging qw( :log :dlog );
7   has sender => (is => 'ro', required => 1);
8
9   # unqualified INC forced into package main
10   sub Object::Remote::ModuleLoader::Hook::INC {
11     my ($self, $module) = @_;
12     log_debug { "Loading $module via " . ref($self) };
13     my $ret = eval {
14       if (my $code = $self->sender->source_for($module)) {
15         open my $fh, '<', \$code;
16         Dlog_trace { "Module sender successfully sent code for '$module': $code" } $code;
17         return $fh;
18       }
19       log_trace { "Module sender did not return code for '$module'" };
20       return;
21     };
22     if ($@) {
23       log_trace { "Module sender blew up - $@" };
24       if ($@ =~ /Can't locate/) {
25         my @caller = caller(0);
26         if ($caller[0] eq 'base') {
27           $@ =~ s/(in \@INC.)/$1 at $caller[1] line $caller[2]/;
28         }
29         # Fudge the error messge to make it work with
30         # Module::Runtime use_package_optimistically
31         # Module::Runtime wants - /\ACan't locate \Q$fn\E .+ at \Q@{[__FILE__]}\E line/
32         # We could probably measure and hard-code this but that could easily
33         # be a forwards compatibility disaster, so do a quick search of caller
34         # with a reasonable range; we're already into a woefully inefficient
35         # situation here so a little defensiveness won't make things much worse
36         foreach my $i (4..20) {
37           my ($package, $file, $line) = caller($i);
38           last unless $package;
39           if ($package eq 'Module::Runtime') {
40             # we want to fill in the error message with the 
41             # module runtime module call info.
42             $@ =~ s/(in \@INC.)/$1 at $file line $line/;
43             last;
44           }
45         }
46       }
47       die $@;
48     }
49     return $ret;
50   }
51 }
52
53 use Moo;
54
55 use Object::Remote::Logging qw( :log );
56
57 has module_sender => (is => 'ro', required => 1);
58
59 has inc_hook => (is => 'lazy');
60
61 sub _build_inc_hook {
62   my ($self) = @_;
63   log_debug { "Constructing module builder hook" };
64   my $hook = Object::Remote::ModuleLoader::Hook->new(sender => $self->module_sender);
65   log_trace { "Done constructing module builder hook" };
66   return $hook;
67 }
68
69 sub BUILD { shift->enable }
70
71 sub enable {
72   log_debug { "enabling module loader hook" };
73   push @INC, shift->inc_hook;
74   return;
75 }
76
77 sub disable {
78   my ($self) = @_;
79   log_debug { "disabling module loader hook" };
80   my $hook = $self->inc_hook;
81   @INC = grep $_ ne $hook, @INC;
82   return;
83 }
84
85 sub DEMOLISH { $_[0]->disable unless $_[1] }
86
87 1;