Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 9597cfe818
Fetching contributors…

Cannot retrieve contributors at this time

file 689 lines (623 sloc) 19.85 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
#!/usr/bin/env perl
#
# Copyright (C) 2011 Rocky Bernstein <rockb@cpan.org>
#
#
=head1 NAME Linecache

DB::LineCache - package to read and cache lines of a Perl program.

=head1 SYNOPSIS

The LineCache package allows one to get any line from any file,
caching lines of the file on first access to the file. Although the
file may be any file, the common use is when the file is a Perl
script since parsing of the file is done to figure out where the
statement boundaries are.

The routines here may be is useful when a small random sets of lines
are read from a single file, in particular in a debugger to show
source lines.

use 'DB::LineCache'
lines = DB::LineCache::getlines('/tmp/myperl.pl')
# The following lines have same effect as the above.
$: << '/tmp'
Dir.chdir('/tmp') {lines = DB::LineCache::getlines('myperl.pl')

line = DB::LineCache::getline('/tmp/myperl.pl', 6)
# Note lines[6] == line (if /tmp/myperl.pl has 6 lines)

DB::LineCache::clear_file_cache
DB::LineCache::update_cache # Check for modifications of all cached files.

=cut

use Digest::SHA1;

use version; $VERSION = '0.1.0';

# A package to read and cache lines of a Perl program.
package DB::LineCache;
use English;
use strict; use warnings;
no warnings 'once';
no warnings 'redefine';

use Cwd 'abs_path';
use File::Basename;
use File::Spec;
use File::stat;

use lib '../../..';
## FIXME:: Make conditional
use Devel::Trepan::DB::Colors;
my $perl_formatter = Devel::Trepan::DB::Colors::setup();

## struct(stat => '$', lines => '%', path => '$', sha1 => '$');

# The file cache. The key is a name as would be given by Perl for
# __FILE__. The value is a LineCacheInfo object.

my %file_cache;
my %script_cache;

# Maps a string filename (a String) to a key in %file_cache (a
# String).
#
# One important use of %file2file_remap is mapping the a full path
# of a file into the name stored in %file_cache or given by Perl's
# __FILE__. Applications such as those that get input from users,
# may want canonicalize a file name before looking it up. This map
# gives a way to do that.
#
# Another related use is when a template system is used. Here we'll
# probably want to remap not only the file name but also line
# ranges. Will probably use this for that, but I'm not sure.

my %file2file_remap;
my %file2file_remap_lines;
my %script2file;

sub remove_script_temps()
{
    for my $filename (values %script2file) {
unlink($filename) if -f $filename;
    }
}

END { remove_script_temps };

  
# Clear the file cache entirely.
sub clear_file_cache(;$)
{
    if (scalar @_ == 1) {
my $filename = shift;
if ($file_cache{$filename}) {
delete $file_cache{$filename};
}
    } else {
%file_cache = {};
%file2file_remap = {};
%file2file_remap_lines = {};
    }
}

# Remove syntax-formatted lines in the cache. Use this when you change
# the Syntax::Highlight::Perl colors and want to redo how files may
# have previously been syntax marked.
sub clear_file_format_cache()
{
    while (my ($fname, $cache_info) = each %file_cache) {
while (my($format, $lines) = each %{$cache_info->{lines_href}}) {
next if 'plain' eq $format;
my $ref = $file_cache{$fname};
$ref->{lines_href}->{$format} = undef;
}
    }
}

# Clear the script cache entirely.
sub clear_script_cache() {
    %script_cache = {};
}

# Return an array of cached file names
sub cached_files() {
    keys %file_cache;
}

# Discard cache entries that are out of date. If +filename+ is +undef+
# all entries in the file cache +@@file_cache+ are checked.
# If we don't have stat information about a file, which can happen
# if the file was read from $__SCRIPT_LINES but no corresponding file
# is found, it will be kept. Return a list of invalidated filenames.
# undef is returned if a filename was given but not found cached.
sub checkcache(;$$)
{
    my ($filename, $opts) = @_;
    $opts //= {};

    my $use_perl_d_file = $opts->{use_perl_d_file};

    my @filenames;
    if (defined $filename) {
@filenames = keys %file_cache;
    } elsif (exists $file_cache{$filename}) {
@filenames = ($filename);
    } else {
return undef;
    }

    my @result = ();
    for my $filename (@filenames) {
next unless exists $file_cache{$filename};
my $path = $file_cache{$filename}{path};
if (-f $path) {
my $cache_info = $file_cache{$filename}{stat};
my $stat = File::stat::stat($path);
if ($cache_info) {
if ($stat &&
($cache_info->{size} != $stat->size or
$cache_info->{mtime} != $stat->mtime)) {
push @result, $filename;
update_cache($filename, $opts);
}
}
        } else {
push @result, $filename;
update_cache($filename, $opts);
        }
    }
    return @result;
}

# Cache script if it's not already cached.
sub cache_script($;$)
{
    my ($script, $opts) = @_;
    $opts //= {};
    update_script_cache($script, $opts) unless
(exists $script_cache{$script});
    $script;
}

# Cache file name or script object if it's not already cached.
# Return the expanded filename for it in the cache if a filename,
# or the script, or undef if we can't find the file.
sub cache($;$)
{
    my ($file_or_script, $reload_on_change) = @_;
    cache_file($file_or_script, $reload_on_change)
}

# Cache filename if it's not already cached.
# Return the expanded filename for it in the cache
# or undef if we can't find the file.
sub cache_file($;$$)
{
    my ($filename, $reload_on_change, $opts) = @_;
    $opts //={};
    if (exists $file_cache{$filename}) {
checkcache($filename) if $reload_on_change;
    } else {
$opts->{use_perl_d_file} //= 1;
update_cache($filename, $opts);
    }
    if (exists $file_cache{$filename}) {
$file_cache{$filename}{path};
    } else {
return undef;
    }
}

# Return true if file_or_script is cached.
sub is_cached($)
{
    my $file_or_script = shift;
    return undef unless defined $file_or_script;
    exists $file_cache{map_file($file_or_script)};
}

sub is_cached_script($)
{
    my $filename = shift;
    my $name = map_file($filename);
    scalar @{"_<$name"};
}
      
sub is_empty($)
{
    my $filename = shift;
    $filename=map_file($filename);
    my $ref = $file_cache{$filename};
    $ref->{lines_href}{plain};
}

# Get line +line_number+ from file named +filename+. Return undef if
# there was a problem. If a file named filename is not found, the
# function will look for it in the $: array.
#
# Examples:
#
# lines = LineCache::getline('/tmp/myfile.rb')
# # Same as above
# $: << '/tmp'
# lines = LineCache.getlines('myfile.rb')
#
sub getline($$;$)
{
    my ($file_or_script, $line_number, $opts) = @_;
    $opts //= {};
    my $reload_on_change = $opts->{reload_on_change};
    my $filename = map_file($file_or_script);
    ($filename, $line_number) = map_file_line($filename, $line_number);
    ## print "+++FILENAME $filename\n";
    my $lines = getlines($filename, $opts);
    if (@$lines && $line_number > 0 && $line_number <= scalar @$lines) {
my $line = $lines->[$line_number-1];
chomp $line if defined $line;
        return $line;
    } else {
        return undef;
    }
}

# Read lines of +filename+ and cache the results. However +filename+ was
# previously cached use the results from the cache. Return undef
# if we can't get lines
sub getlines($;$);
sub getlines($;$)
{
    my ($filename, $opts) = @_;
    $opts //= {use_perl_d_file => 1};
    my ($reload_on_change, $use_perl_d_file) =
        ($opts->{reload_on_change}, $opts->{use_perl_d_file});
    checkcache($filename) if $reload_on_change;
    my $format = $opts->{output} || 'plain';
    if (exists $file_cache{$filename}) {
my $lines_href = $file_cache{$filename}{lines_href};
my $lines_aref = $lines_href->{$format};
if ($opts->{output} && !defined $lines_aref) {
my @formatted_lines = ();
my $lines_aref = $lines_href->{plain};
for my $line (@$lines_aref) {
push @formatted_lines, highlight_string($line);
## print $formatted_text;
}
$lines_href->{$format} = \@formatted_lines;
return \@formatted_lines;
} else {
return $lines_aref;
}
    } elsif (exists $script_cache{$filename}) {
### FIXME: combine with above...
print "+++IS IN SCRIPT CACHE\n";
my $lines_href = $script_cache{$filename}{lines_href};
my $lines_aref = $lines_href->{$format};
if ($opts->{output} && !defined $lines_aref) {
my @formatted_lines = ();
my $lines_aref = $lines_href->{plain};
for my $line (@$lines_aref) {
push @formatted_lines, highlight_string($line);
## print $formatted_text;
}
$lines_href->{$format} = \@formatted_lines;
return \@formatted_lines;
} else {
return $lines_aref;
}
    } else {
$opts->{use_perl_d_file} = 1;
update_cache($filename, $opts);
if (exists $file_cache{$filename}) {
return getlines($filename, $opts);
} else {
return undef;
}
    }
}

sub highlight_string($)
{
    my ($string) = shift;
    $string = $perl_formatter->format_string($string);
    chomp $string;
    $string;
  }

 # Return full filename path for filename
sub path($)
{
    my $filename = shift;
    $filename = map_file($filename);
    return undef unless exists $file_cache{$filename};
    $file_cache{$filename}->path();
}

sub remap_file($$)
{
    my ($from_file, $to_file) = @_;
    $file2file_remap{$from_file} = $to_file;
    cache_file($to_file);
}

sub remap_file_lines($$$$)
{
    my ($from_file, $to_file, $range_ref, $start) = @_;
    my @range = @$range_ref;
    $to_file = $from_file unless $to_file;
    my $ary_ref = ${$file2file_remap_lines{$to_file}} //= [];
    # FIXME: need to check for overwriting ranges: whether
    # they intersect or one encompasses another.
    push @$ary_ref, [$from_file, @range, $start];
}
  
# Return SHA1 of filename.
sub DB::LineCache::sha1($)
{
    my $filename = shift;
    $filename = map_file($filename);
    return undef unless exists $file_cache{$filename};
    my $sha1 = $file_cache{$filename}{sha1};
    return $sha1->hexdigest if exists $file_cache{$filename}{sha1};
    $sha1 = Digest::SHA1->new;
    my $line_ary = $file_cache{$filename}{lines_href}{plain};
    for my $line (@$line_ary) {
next unless defined $line;
$sha1->add($line);
    }
    $file_cache{$filename}{sha1} = $sha1;
    $sha1->hexdigest;
  }
      
# Return the number of lines in filename
sub size($)
{
    my $file_or_script = shift;
    cache($file_or_script);
    $file_or_script = map_file($file_or_script);
    return undef unless exists $file_cache{$file_or_script};
    my $lines_href = $file_cache{$file_or_script}{lines_href};
    return undef unless defined $lines_href;
    scalar @{$lines_href->{plain}};
}

# Return File.stat in the cache for filename.
sub DB::LineCache::stat($)
{
    my $filename = shift;
    return undef unless exists $file_cache{$filename};
    $file_cache{$filename}{stat};
}

# Return an Array of breakpoints in filename.
# The list will contain an entry for each distinct line event call
# so it is possible (and possibly useful) for a line number appear more
# than once.
sub trace_line_numbers($;$)
{
    my ($filename, $reload_on_change) = @_;
    my $fullname = cache($filename, $reload_on_change);
    return undef unless $fullname;
    my $trace_nums_ary = $file_cache{$filename}{trace_nums};
    return @$trace_nums_ary if $trace_nums_ary;
    my $lines_ary = $file_cache{$filename}{lines_href}{plain};
    my @lines = @$lines_ary;
    my @result = ();
    for (my $i=1; $i <= $#lines; $i++) {
next unless defined $lines[$i];
no warnings 'numeric';
push @result, $i unless $lines[$i] == 0;
use warnings 'numeric'
    }
    $file_cache{$filename}{trace_nums} = \@result;
    return @result;
  }
    
sub map_file($)
{
    my $file = shift;
    return undef unless defined($file);
    $file2file_remap{$file} ? $file2file_remap{$file} : $file
  }

use File::Temp qw(tempfile);
sub map_script($$)
{
    my ($script, $string) = @_;
    if (exists $script2file{$script}) {
$script2file{$script};
    } else {
# my $sha1 = Digest::SHA1->new();
# $sha1->add($string);
my ($fh, $tempfile) = tempfile('XXXX', SUFFIX=>'.pl',
TMPDIR => 1);
print $fh $string;
$fh->close();
$script2file{$script} = $tempfile;
# cache_file($tempfile);
# $file_cache{$tempfile}{sha1} = $sha1;
$tempfile;
    }
}

sub map_file_line($$)
{
    my ($file, $line) = @_;
    if (exists $file2file_remap_lines{$file}) {
my $triplet_ref = $file2file_remap_lines{$file};
for my $triplet (@$triplet_ref) {
my ($from_file, $range_ref, $start) = @$triplet;
my @range = @$range_ref;
if ( $range[0] >= $line && $range[-1] <= $line) {
my $from_file = $from_file || $file;
return [$from_file, $start+$line-$range[0]];
}
}
    }
    return ($file, $line);
}

sub filename_is_eval($)
{
    my $filename = shift;
    return ($filename =~ /^\(eval \d+\)/);
}

# UPDATE a cache entry. If something is wrong, return undef. Return
# 1 if the cache was updated and false if not.
sub update_script_cache($$)
{
    my ($script, $opts) = @_;
    return 0 unless filename_is_eval($script);
    my $string = $opts->{string};
    my $lines_href = {};
    unless (defined($string)) {
if ($script eq $DB::filename) {
# Should be the same as the else case,
# but just in case...
$lines_href->{plain} = \@DB::lines;
$string = join("\n", @DB::lines);
} else {
$lines_href->{plain} = \@{"_<$script"};
$string = join("\n", @{"_<$script"});
}
    }
    $lines_href->{$opts->{output}} = highlight_string($string) if
$opts->{output};

    my $entry = {
lines_href => $lines_href,
    };
    $script_cache{$script} = $entry;
    return 1;
  }

sub read_file($)
{
    my $path = shift;
    if (-r $path) {
open(FH, '<', $path);
seek FH, 0, 0;
my @lines = <FH>;
close FH;
return @lines;
    } else {
return undef;
    }
}

# Update a cache entry. If something's wrong, return undef. Return 1
# if the cache was updated and false if not. If use_perl_d_file is 1,
# use that as the source for the lines of the file
sub update_cache($;$)
{
    my ($filename, $opts) = @_;
    my $read_file = 0;
    $opts //={};
    my $use_perl_d_file = $opts->{use_perl_d_file} //= 1;

    return undef unless $filename;

    delete $file_cache{$filename};

    my $path = abs_path($filename) || $filename;
    my $lines_href;
    if ($use_perl_d_file) {
my @list = ($filename);
if (filename_is_eval($filename)) {
cache_script($filename);
## FIXME: create a temporary file in script2file;
}
push @list, $file2file_remap{$path} if exists $file2file_remap{$path};
for my $name (@list) {
my $stat;
no strict; # Avoid string as ARRAY ref error message
if (scalar @{"main::_<$name"}) {
$stat = File::stat::stat($path);
}
my $raw_lines = \@{"main::_<$name"};

# Perl sometimes doesn't seem to save all file data, such
# as those intended for POD or possibly those after
# __END__. But we want these, so we'll have to read the
# file the old-fashioned way and check lines. Variable
# $incomplete records if there was a mismatch.
my $incomplete = 0;
if (-r $path) {
my @lines_check = read_file($path);
my @lines = @$raw_lines;
for (my $i=1; $i<=$#lines; $i++) {
if (defined $raw_lines->[$i]) {
$incomplete = 1 if $raw_lines->[$i] ne $lines[$i];
} else {
$raw_lines->[$i] = $lines_check[$i-1]
}
}
}
use strict;
$lines_href = {};
$lines_href->{plain} = $raw_lines;
if ($opts->{output} && defined($raw_lines)) {
# Some lines in $raw_lines may be undefined
no strict; no warnings;
local $WARNING=0;
my $highlight_lines = highlight_string(join('', @$raw_lines));
my @highlight_lines = split(/\n/, $highlight_lines);
$lines_href->{$opts->{output}} = \@highlight_lines;
use strict; use warnings;
}
my $entry = {
stat => $stat,
lines_href => $lines_href,
path => $path,
incomplete => $incomplete
};
$read_file = 1;
        }
    }
      
    my $stat = undef;
    if (-f $path ) {
$stat = File::stat::stat($path);
    } elsif (!$read_file) {
if (basename($filename) eq $filename) {
# try looking through the search path.
for my $dirname (@INC) {
$path = File::Spec::catfile->($dirname, $filename);
if ( -f $path) {
$stat = File::stat::stat($path);
last;
}
}
}
return 0 unless defined $stat;
    }
    if ( -r $path ) {
my @lines = read_file($path);
$lines_href = {plain => \@lines};
if ($opts->{output}) {
my $highlight_lines = highlight_string(join('', @lines));
my @highlight_lines = split(/\n/, $highlight_lines);
$lines_href->{$opts->{output}} = \@highlight_lines;
}
    }
    my $entry = {
stat => $stat,
lines_href => $lines_href,
path => $path,
incomplete => 0
};
    $file_cache{$filename} = $entry;
    $file2file_remap{$path} = $filename;
    return 1;
}

# example usage
unless (caller) {
    BEGIN {
use English;
$PERLDB |= 0x400;
    }; # Turn on saving @{_<$filename};
    my $file=__FILE__;
    my $fullfile = abs_path($file);
    no strict;
    print scalar(@{"main::_<$file"}), "\n";
    use strict;
    
    my $lines = DB::LineCache::getlines(__FILE__);
    printf "%s has %d lines\n", __FILE__, scalar @$lines;
    my $full_file = abs_path(__FILE__);
    $lines = DB::LineCache::getlines(__FILE__);
    printf "%s still has %d lines\n", __FILE__, scalar @$lines;
    $lines = DB::LineCache::getlines(__FILE__);
    printf "%s also has %d lines\n", $full_file, scalar @$lines;
    my $line_number = __LINE__;
    my $line = DB::LineCache::getline(__FILE__, $line_number);
    printf "The %d line is:\n%s\n", $line_number, $line ;
    DB::LineCache::remap_file('another_name', __FILE__);
    print DB::LineCache::getline('another_name', __LINE__), "\n";
    
    printf "Files cached: %s\n", join(', ', DB::LineCache::cached_files);
    DB::LineCache::update_cache(__FILE__);
    ## DB::LineCache::checkcache(__FILE__);
    printf "I said %s has %d lines!\n", __FILE__, DB::LineCache::size(__FILE__);
    printf "SHA1 of %s is:\n%s\n", __FILE__, DB::LineCache::sha1(__FILE__);
    # print "#{__FILE__} trace line numbers:\n" +

    my $stat = DB::LineCache::stat(__FILE__);
    printf("stat info size: %d, ctime %s, mode %o\n",
$stat->size, $stat->ctime, $stat->mode);

    my $lines_aref = DB::LineCache::getlines(__FILE__, {output=>'term'});
    print join("\n", @$lines_aref), "\n" if defined $lines_aref;

    print("trace nums: ", join(', ',
DB::LineCache::trace_line_numbers(__FILE__)),
"\n");
    $lines_aref = DB::LineCache::getlines(__FILE__, {output=>'term'});
    print("trace nums again: ", join(', ',
DB::LineCache::trace_line_numbers(__FILE__)),
"\n");
    eval "printf \"filename_is_eval: %s, %s\n\", __FILE__,
filename_is_eval(__FILE__);";
    $DB::filename = 'bogus';
    eval "update_script_cache(__FILE__, {});
print '+++', is_cached_script(__FILE__), \"\\n\"";
    $DB::filename = '(eval 4)';
    my $filename = map_script($DB::filename, "\$x=1;\n\$y=2;\n\$z=3;\n");
    print "mapped eval is $filename\n";
    
    # print("#{__FILE__} is %scached." %
    # yes_no(LineCache::cached?(__FILE__)))
    # print "Full path: #{DB::LineCache::path(__FILE__)}"
    # LineCache::checkcache # Check all files in the cache
    # LineCache::clear_file_cache
    # print("#{__FILE__} is now %scached." %
    # yes_no(LineCache::cached?(__FILE__)))
    # digest = SCRIPT_LINES__.select{|k,v| k =~ /digest.rb$/}
    # print digest.first[0] if digest
    # line = LineCache::getline(__FILE__, 7)
    # print "The 7th line is\n#{line}"
    # LineCache::remap_file_lines(__FILE__, 'test2', (10..20), 6)
    # print LineCache::getline('test2', 10)
    # print "Remapped 10th line of test2 is\n#{line}"
}

1;
Something went wrong with that request. Please try again.