1# $OpenBSD: LaLoFile.pm,v 1.5 2023/07/06 08:29:26 espie 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 v5.36; 19 20package LT::LaLoFile; 21use LT::Trace; 22 23my %file_cache; # which files have been parsed 24my $cache_by_fullname = {}; 25my $cache_by_inode = {}; 26 27# allows special treatment for some keywords 28sub set($self, $k, $v) 29{ 30 $self->{$k} = $v; 31} 32 33sub stringize($self, $k) 34{ 35 if (defined $self->{$k}) { 36 return $self->{$k}; 37 } 38 return ''; 39} 40 41sub read($class, $filename) 42{ 43 my $info = $class->new; 44 open(my $fh, '<', $filename) or die "Cannot read $filename: $!\n"; 45 while (my $line = <$fh>) { 46 chomp($line); 47 next if $line =~ /^\#/; 48 next if $line =~ /^\s*$/; 49 if ($line =~ m/^(\S+)\=\'(.*)\'$/) { 50 $info->set($1, $2); 51 } elsif ($line =~ m/^(\S+)\=(\S+)$/) { 52 $info->set($1, $2); 53 } 54 } 55 return $info; 56} 57 58sub parse($class, $filename) 59{ 60 tprint {"parsing $filename"}; 61 62 if (defined $cache_by_fullname->{$filename}) { 63 tsay {" (cached)"}; 64 return $cache_by_fullname->{$filename}; 65 } 66 my $key = join("/", (stat $filename)[0,1]); 67 if (defined $cache_by_inode->{$key}) { 68 tsay {" (cached)"}; 69 return $cache_by_inode->{$key}; 70 } 71 tsay {""}; 72 return $cache_by_inode->{$key} = $cache_by_fullname->{$filename} = 73 $class->read($filename); 74} 75 76sub new($class) 77{ 78 bless {}, $class; 79} 80 811; 82