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