File Coverage

lib/Ubic/AtomicFile.pm
Criterion Covered Total %
statement 23 23 100.0
branch 7 14 50.0
condition n/a
subroutine 5 5 100.0
pod 1 1 100.0
total 36 43 83.7


line stmt bran cond sub pod time code
1             package Ubic::AtomicFile;
2             $Ubic::AtomicFile::VERSION = '1.58_01'; # TRIAL
3 39     39   192 use strict;
  39         64  
  39         1214  
4 39     39   189 use warnings;
  39         45  
  39         1092  
5              
6             # ABSTRACT: atomic file operations
7              
8              
9 39     39   351 use IO::Handle;
  39         66  
  39         1746  
10 39     39   204 use Params::Validate qw(:all);
  39         150  
  39         15708  
11              
12             sub store($$;$) {
13 27     27 1 1087 my ($data, $file, @options) = @_;
14              
15 27         391 my $options = validate(@options, {
16             sync => { default => 1 },
17             });
18              
19 27         120 my $new_file = "$file.new";
20              
21 27 50       2257 open my $fh, '>', $new_file or die "Can't open '$new_file' for writing: $!";
22 27 50       46 print {$fh} $data or die "Can't print to '$new_file': $!";
  27         270  
23 27 50       1416 $fh->flush or die "Can't flush '$new_file': $!";
24              
25 27 50       117 if ($options->{sync}) {
26             # Here is a link which says why we should do sync too if we don't want to lose data:
27             # https://bugs.launchpad.net/ubuntu/+source/linux/+bug/317781/comments/54
28             #
29             # For some types of atomic files this is important, for others (pidfiles, temp files) it can be too big performance hit.
30             # Every part of ubic code decides for itself.
31 27 50       128544781 $fh->sync or die "Can't sync '$new_file': $!";
32             }
33              
34 27 50       944 close $fh or die "Can't close '$new_file': $!";
35 27 50       3548 rename $new_file => $file or die "Can't rename '$new_file' to '$file': $!";
36             }
37              
38             1;
39              
40             __END__