1# $OpenBSD: LaLoFile.pm,v 1.4 2014/03/19 02:16:22 afresh1 Exp $ 2 3# Copyright (c) 2007-2010 Steven Mestdagh <steven@openbsd.org> 4# Copyright (c) 2012 Marc Espie <espie@openbsd.org> 5# 6# Permission to use, copy, modify, and distribute this software for any 7# purpose with or without fee is hereby granted, provided that the above 8# copyright notice and this permission notice appear in all copies. 9# 10# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 18use strict; 19use warnings; 20use feature qw(say switch state); 21 22package LT::LaLoFile; 23use LT::Trace; 24 25my %file_cache; # which files have been parsed 26my $cache_by_fullname = {}; 27my $cache_by_inode = {}; 28 29# allows special treatment for some keywords 30sub set 31{ 32 my ($self, $k, $v) = @_; 33 34 $self->{$k} = $v; 35} 36 37sub stringize 38{ 39 my ($self, $k) = @_; 40 if (defined $self->{$k}) { 41 return $self->{$k}; 42 } 43 return ''; 44} 45 46sub read 47{ 48 my ($class, $filename) = @_; 49 my $info = $class->new; 50 open(my $fh, '<', $filename) or die "Cannot read $filename: $!\n"; 51 while (my $line = <$fh>) { 52 chomp($line); 53 next if $line =~ /^\#/; 54 next if $line =~ /^\s*$/; 55 if ($line =~ m/^(\S+)\=\'(.*)\'$/) { 56 $info->set($1, $2); 57 } elsif ($line =~ m/^(\S+)\=(\S+)$/) { 58 $info->set($1, $2); 59 } 60 } 61 return $info; 62} 63 64sub parse 65{ 66 my ($class, $filename) = @_; 67 68 tprint {"parsing $filename"}; 69 70 if (defined $cache_by_fullname->{$filename}) { 71 tsay {" (cached)"}; 72 return $cache_by_fullname->{$filename}; 73 } 74 my $key = join("/", (stat $filename)[0,1]); 75 if (defined $cache_by_inode->{$key}) { 76 tsay {" (cached)"}; 77 return $cache_by_inode->{$key}; 78 } 79 tsay {""}; 80 return $cache_by_inode->{$key} = $cache_by_fullname->{$filename} = 81 $class->read($filename); 82} 83 84sub new 85{ 86 my $class = shift; 87 bless {}, $class; 88} 89 901; 91