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