Commit | Line | Data |
59aedffc |
1 | package Devel::REPL::Script; |
2 | |
3 | use Moose; |
4 | use Devel::REPL; |
5 | use File::HomeDir; |
6 | use File::Spec; |
4d33251a |
7 | use vars qw($CURRENT_SCRIPT); |
59aedffc |
8 | use namespace::clean -except => [ qw(meta) ]; |
9 | |
10 | with 'MooseX::Getopt'; |
11 | |
12 | has 'rcfile' => ( |
13 | is => 'ro', isa => 'Str', required => 1, default => sub { 'repl.rc' }, |
14 | ); |
15 | |
4d33251a |
16 | has 'profile' => ( |
17 | is => 'ro', isa => 'Str', required => 1, default => sub { 'Default' }, |
18 | ); |
19 | |
fa626608 |
20 | has 'e' => ( |
21 | is => 'ro', isa => 'ArrayRef', default => sub { [] }, |
22 | ); |
23 | |
59aedffc |
24 | has '_repl' => ( |
25 | is => 'ro', isa => 'Devel::REPL', required => 1, |
26 | default => sub { Devel::REPL->new() } |
27 | ); |
28 | |
29 | sub BUILD { |
30 | my ($self) = @_; |
4d33251a |
31 | $self->load_profile($self->profile); |
32 | $self->load_rcfile($self->rcfile); |
fa626608 |
33 | $self->load_scripts($self->e); |
59aedffc |
34 | } |
35 | |
4d33251a |
36 | sub load_profile { |
37 | my ($self, $profile) = @_; |
38 | $profile = "Devel::REPL::Profile::${profile}" unless $profile =~ /::/; |
39 | Class::MOP::load_class($profile); |
3bcf4eb8 |
40 | confess "Profile class ${profile} doesn't do 'Devel::REPL::Profile'" |
41 | unless $profile->does('Devel::REPL::Profile'); |
4d33251a |
42 | $profile->new->apply_profile($self->_repl); |
43 | } |
59aedffc |
44 | |
4d33251a |
45 | sub load_rcfile { |
46 | my ($self, $rc_file) = @_; |
59aedffc |
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 | if (-r $rc_file) { |
54 | open RCFILE, '<', $rc_file || die "Couldn't open ${rc_file}: $!"; |
55 | my $rc_data; |
56 | { local $/; $rc_data = <RCFILE>; } |
57 | close RCFILE; # Don't care if this fails |
58 | $self->eval_rcdata($rc_data); |
59 | warn "Error executing rc file ${rc_file}: $@\n" if $@; |
60 | } |
61 | } |
62 | |
fa626608 |
63 | sub load_scripts { |
64 | my ($self, $scripts) = @_; |
65 | |
66 | for (@$scripts) { |
67 | do $_; |
68 | } |
69 | } |
70 | |
59aedffc |
71 | sub eval_rcdata { |
4d33251a |
72 | my ($self, $data) = @_; |
73 | local $CURRENT_SCRIPT = $self; |
74 | $self->_repl->eval($data); |
59aedffc |
75 | } |
76 | |
77 | sub run { |
78 | my ($self) = @_; |
79 | $self->_repl->run; |
80 | } |
81 | |
82 | sub import { |
83 | my ($class, @opts) = @_; |
84 | return unless (@opts == 1 && $opts[0] eq 'run'); |
85 | $class->new_with_options->run; |
86 | } |
87 | |
4d33251a |
88 | sub 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 |
95 | 1; |