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