Config-Cfe
view release on metacpan or search on metacpan
# &lock($file);
if ($exist_flag && !-e $file) {
&new_file($file);
$par->{'mode'} = 0666 & umask;
$par->{'uid'} = $>;
$par->{'gid'} = $);
&verbose('read_file', sprintf("mode=0%o, uid=%d, gid=%d",
$par->{'mode'}, $par->{'uid'}, $par->{'gid'}));
return;
}
&get_filemode($file);
$par->{'file_name'} = $file;
$par->{'edit'} = $par->{'cur_line'} = 0;
my $lines = $par->{'lines'} = [];
unless (-e $file) {
&verbose("read_file", "$file does not exist");
return;
}
open(FILE, $file) || croak "open $file:$!";
while(<FILE>) {
chop;
push(@$lines, $_);
croak "too many lines" if @$lines >= $par->{'max_lines'};
}
close(FILE);
&verbose("read_file", "$file, ".(@$lines*1)." lines");
}
=head1 write_file [\%par]
Write the current file if it has been changed.
Control of the file can be done thru the hash parameter B<par>.
The old file will be renamed to B<.>I<filename>B<.cfe>.
Will not rename the final file (I<filename.new>) to I<filename>
if debug is active.
Accepted keys for B<par>:
key name default
--------------------------------------
mode filemode 0666 & umask.
uid numeric userid 0
gid numeric groupid 0
=cut
sub write_file {
my (%tpar) = @_;
my ($tmp, $fsize, $file);
return unless $par->{'edit'};
$tpar{'mode'} = $par->{'mode'} unless $tpar{'mode'};
$tpar{'uid'} = $par->{'uid'} unless $tpar{'uid'};
$tpar{'gid'} = $par->{'gid'} unless $tpar{'gid'};
croak "No filename!" unless $file = $par->{'file_name'};
($tmp = $file) =~ s/$/.new/;
open(FILEO, ">$tmp") || croak "can't create $tmp:$!";
chmod $tpar{'mode'}, $tmp;
chown $tpar{'uid'}, $tpar{'gid'}, $tmp;
for my $line (@{$par->{'lines'}}) {
print FILEO "$line\n";
$fsize += length($line)+1;
}
close(FILEO);
&abort_file("incorrect filesize, abort") if -s $tmp != $fsize;
unless ($debug) {
rename($file, ".$file.cfe");
rename($tmp, $file) || &abort_file("rename $tmp to $file:$!");
}
$par->{'lines'} = [];
&verbose('write_file', "wrote $file, ".
(@{$par->{'lines'}}*1)." lines, $fsize bytes");
# &unlock($file);
&reset_par;
}
=head1 abort_file
Quit editing the current file.
=cut
sub abort_file {
my ($txt) = @_;
my ($tmp, $fsize, $file);
croak "No filename!" unless $file = $par->{'file_name'};
($tmp = $file) =~ s/$/.new/;
unlink($tmp) || croak "unlink $tmp:$!";
croak $txt if $txt;
# &unlock($file);
&reset_par;
}
=head1 append_file filename
Appends B<filename> at the current line.
=cut
sub append_file {
my ($file) = @_;
my (@tmp);
&verbose("append_file", "**** $file");
open(FILE, $file) || croak "open $file:$!";
while(<FILE>) {
chop;
push(@tmp, $_);
&verbose("append_file", $_);
croak "too many lines"
if @{$par->{'lines'}} >= $par->{'max_lines'};
}
close(FILE);
&append(@tmp);
}
=head1 list_lines [from_line [to_line]]
( run in 0.630 second using v1.01-cache-2.11-cpan-f56aa216473 )