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.60';
3 36     36   110 use strict;
  36         29  
  36         765  
4 36     36   114 use warnings;
  36         25  
  36         641  
5              
6             # ABSTRACT: atomic file operations
7              
8              
9 36     36   107 use IO::Handle;
  36         41  
  36         1009  
10 36     36   116 use Params::Validate qw(:all);
  36         37  
  36         9216  
11              
12             sub store($$;$) {
13 24     24 1 663 my ($data, $file, @options) = @_;
14              
15 24         268 my $options = validate(@options, {
16             sync => { default => 1 },
17             });
18              
19 24         93 my $new_file = "$file.new";
20              
21 24 50       1583 open my $fh, '>', $new_file or die "Can't open '$new_file' for writing: $!";
22 24 50       39 print {$fh} $data or die "Can't print to '$new_file': $!";
  24         169  
23 24 50       838 $fh->flush or die "Can't flush '$new_file': $!";
24              
25 24 50       77 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 24 50       2093899 $fh->sync or die "Can't sync '$new_file': $!";
32             }
33              
34 24 50       719 close $fh or die "Can't close '$new_file': $!";
35 24 50       2534 rename $new_file => $file or die "Can't rename '$new_file' to '$file': $!";
36             }
37              
38             1;
39              
40             __END__