3e4dd4bb7261907ffc36b1c34d8067f07c871656
[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 vars qw($CURRENT_SCRIPT);
9 use namespace::autoclean;
10
11 with 'MooseX::Getopt';
12
13 has 'rcfile' => (
14   is => 'ro', isa => 'Str',
15   default => sub { 'repl.rc' },
16 );
17
18 has 'profile' => (
19   is       => 'ro',
20   isa      => 'Str',
21   default  => sub { $ENV{DEVEL_REPL_PROFILE} || 'Default' },
22 );
23
24 has '_repl' => (
25   is => 'ro', isa => 'Devel::REPL',
26   default => sub { Devel::REPL->new() }
27 );
28
29 sub BUILD {
30   my ($self) = @_;
31   $self->load_profile($self->profile);
32   $self->load_rcfile($self->rcfile);
33 }
34
35 sub load_profile {
36   my ($self, $profile) = @_;
37   $profile = "Devel::REPL::Profile::${profile}" unless $profile =~ /::/;
38   use_module $profile;
39   confess "Profile class ${profile} doesn't do 'Devel::REPL::Profile'"
40     unless $profile->does('Devel::REPL::Profile');
41   $profile->new->apply_profile($self->_repl);
42 }
43
44 sub load_rcfile {
45   my ($self, $rc_file) = @_;
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
52   $self->apply_script($rc_file);
53 }
54
55 sub apply_script {
56   my ($self, $script, $warn_on_unreadable) = @_;
57
58   if (!-e $script) {
59     warn "File '$script' does not exist" if $warn_on_unreadable;
60     return;
61   }
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 $@;
73 }
74
75 sub eval_script {
76   my ($self, $data) = @_;
77   local $CURRENT_SCRIPT = $self;
78   $self->_repl->eval($data);
79 }
80
81 sub run {
82   my ($self) = @_;
83   $self->_repl->run;
84 }
85
86 sub import {
87   my ($class, @opts) = @_;
88   return unless (@opts == 1 && $opts[0] eq 'run');
89   $class->new_with_options->run;
90 }
91
92 sub 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
99 1;