App-Rad
view release on metacpan or search on metacpan
lib/App/Rad/Include.pm view on Meta::CPAN
package App::Rad::Include;
use Carp qw/carp croak/;
use strict;
use warnings;
our $VERSION = '0.01';
sub load {
my ($self, $c) = @_;
$c->register('include', \&include, 'include one-liner as a command');
}
# translates one-liner into
# a complete, readable code
sub _get_oneliner_code {
return _sanitize( _deparse($_[0]) );
}
#TODO: option to do it saving a backup file
# (behavior probably set via 'setup')
# inserts the string received
# (hopefully code) inside the
# user's program file as a 'sub'
sub _insert_code_in_file {
my ($command_name, $code_text) = @_;
my $sub =<<"EOSUB";
sub $command_name {
$code_text
}
EOSUB
# tidy up the code, if Perl::Tidy is available
eval "use Perl::Tidy ()";
if (! $@) {
my $new_code = '';
Perl::Tidy::perltidy( argv => '', source => \$sub, destination => \$new_code );
$sub = $new_code;
}
#TODO: flock
# eval {
# use 'Fcntl qw(:flock)';
# }
# if ($@) {
# carp 'Could not load file locking module';
# }
#TODO: I really should be using PPI
#if the user has it installed...
#or at least a decent parser
open my $fh, '+<', $0
or croak "error updating file $0: $!\n";
# flock($fh, LOCK_EX) or carp "could not lock file $0: $!\n";
my @file = <$fh>;
_insert_code_into_array(\@file, $sub);
# TODO: only change the file if
# it's eval'd without errors
seek ($fh, 0, 0) or croak "error seeking file $0: $!\n";
print $fh @file or croak "error writing to file $0: $!\n";
truncate($fh, tell($fh)) or croak "error truncating file $0: $!\n";
close $fh;
}
sub _insert_code_into_array {
my ($file_array_ref, $sub) = @_;
my $changed = 0;
$sub = "\n\n" . $sub . "\n\n";
my $line_id = 0;
while ( $file_array_ref->[$line_id] ) {
# this is a very rudimentary parser. It assumes a simple
( run in 0.697 second using v1.01-cache-2.11-cpan-df04353d9ac )