Remove soon-to-be-deprecated use of Class::MOP::load_class
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Script.pm
CommitLineData
59aedffc 1package Devel::REPL::Script;
2
3use Moose;
4use Devel::REPL;
5use File::HomeDir;
6use File::Spec;
8456006f 7use Module::Runtime 'use_module';
4d33251a 8use vars qw($CURRENT_SCRIPT);
aa8b7647 9use namespace::autoclean;
59aedffc 10
11with 'MooseX::Getopt';
12
13has 'rcfile' => (
b595a818 14 is => 'ro', isa => 'Str',
15 default => sub { 'repl.rc' },
59aedffc 16);
17
4d33251a 18has 'profile' => (
cdbe3d31 19 is => 'ro',
20 isa => 'Str',
cdbe3d31 21 default => sub { $ENV{DEVEL_REPL_PROFILE} || 'Default' },
4d33251a 22);
23
59aedffc 24has '_repl' => (
b595a818 25 is => 'ro', isa => 'Devel::REPL',
59aedffc 26 default => sub { Devel::REPL->new() }
27);
28
29sub BUILD {
30 my ($self) = @_;
4d33251a 31 $self->load_profile($self->profile);
32 $self->load_rcfile($self->rcfile);
59aedffc 33}
34
4d33251a 35sub load_profile {
36 my ($self, $profile) = @_;
37 $profile = "Devel::REPL::Profile::${profile}" unless $profile =~ /::/;
8456006f 38 use_module $profile;
3bcf4eb8 39 confess "Profile class ${profile} doesn't do 'Devel::REPL::Profile'"
40 unless $profile->does('Devel::REPL::Profile');
4d33251a 41 $profile->new->apply_profile($self->_repl);
42}
59aedffc 43
4d33251a 44sub load_rcfile {
45 my ($self, $rc_file) = @_;
59aedffc 46
47 # plain name => ~/.re.pl/${rc_file}
48 if ($rc_file !~ m!/!) {
49 $rc_file = File::Spec->catfile(File::HomeDir->my_home, '.re.pl', $rc_file);
50 }
51
cb3b891f 52 $self->apply_script($rc_file);
59aedffc 53}
54
cb3b891f 55sub apply_script {
56 my ($self, $script, $warn_on_unreadable) = @_;
fa626608 57
cb3b891f 58 if (!-e $script) {
59 warn "File '$script' does not exist" if $warn_on_unreadable;
60 return;
fa626608 61 }
cb3b891f 62 elsif (!-r _) {
63 warn "File '$script' is unreadable" if $warn_on_unreadable;
64 return;
65 }
66
67 open RCFILE, '<', $script or die "Couldn't open ${script}: $!";
68 my $rc_data;
69 { local $/; $rc_data = <RCFILE>; }
70 close RCFILE; # Don't care if this fails
71 $self->eval_script($rc_data);
72 warn "Error executing script ${script}: $@\n" if $@;
fa626608 73}
74
cb3b891f 75sub eval_script {
4d33251a 76 my ($self, $data) = @_;
77 local $CURRENT_SCRIPT = $self;
78 $self->_repl->eval($data);
59aedffc 79}
80
81sub run {
82 my ($self) = @_;
83 $self->_repl->run;
84}
85
86sub import {
87 my ($class, @opts) = @_;
88 return unless (@opts == 1 && $opts[0] eq 'run');
89 $class->new_with_options->run;
90}
91
4d33251a 92sub current {
93 confess "->current should only be called as class method" if ref($_[0]);
94 confess "No current instance (valid only during rc parse)"
95 unless $CURRENT_SCRIPT;
96 return $CURRENT_SCRIPT;
97}
98
59aedffc 991;