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.59';
3 37     37   136 use strict;
  37         50  
  37         804  
4 37     37   116 use warnings;
  37         46  
  37         671  
5              
6             # ABSTRACT: atomic file operations
7              
8              
9 37     37   122 use IO::Handle;
  37         42  
  37         1126  
10 37     37   116 use Params::Validate qw(:all);
  37         54  
  37         10103  
11              
12             sub store($$;$) {
13 24     24 1 698 my ($data, $file, @options) = @_;
14              
15 24         269 my $options = validate(@options, {
16             sync => { default => 1 },
17             });
18              
19 24         93 my $new_file = "$file.new";
20              
21 24 50       1626 open my $fh, '>', $new_file or die "Can't open '$new_file' for writing: $!";
22 24 50       38 print {$fh} $data or die "Can't print to '$new_file': $!";
  24         188  
23 24 50       928 $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       992088 $fh->sync or die "Can't sync '$new_file': $!";
32             }
33              
34 24 50       728 close $fh or die "Can't close '$new_file': $!";
35 24 50       2876 rename $new_file => $file or die "Can't rename '$new_file' to '$file': $!";
36             }
37              
38             1;
39              
40             __END__