| 1 | package Ubic::AtomicFile; | ||||||||||
| 2 | 172 | $Ubic::AtomicFile::VERSION = '1.59'; | |||||||||
| 3 | 172 | ▶ | use strict; | ||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||
| 4 | 172 | ▶ | use warnings; | ||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||
| 5 | |||||||||||
| 6 | # ABSTRACT: atomic file operations | ||||||||||
| 7 | |||||||||||
| 8 | |||||||||||
| 9 | 172 | ▶ | use IO::Handle; | ||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||
| 10 | 172 | ▶ | use Params::Validate qw(:all); | ||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||
| 11 | |||||||||||
| 12 | sub store($$;$) { | ||||||||||
| 13 | 82 | ▶ | my ($data, $file, @options) = @_; | ||||||||
|
Subroutine
store: called CC=8 SCAR=22.4
Pod
documented
| |||||||||||
| 14 | |||||||||||
| 15 | 82 | my $options = validate(@options, { | |||||||||
| 16 | sync => { default => 1 }, | ||||||||||
| 17 | }); | ||||||||||
| 18 | |||||||||||
| 19 | 82 | my $new_file = "$file.new"; | |||||||||
| 20 | |||||||||||
| 21 | 82 | ▶ | open my $fh, '>', $new_file or die "Can't open '$new_file' for writing: $!"; | ||||||||
|
Branch: 1 branch
| |||||||||||
| 22 | 82 | ▶ | print {$fh} $data or die "Can't print to '$new_file': $!"; | ||||||||
|
Branch: 1 branch
| |||||||||||
| 23 | 82 | ▶ | $fh->flush or die "Can't flush '$new_file': $!"; | ||||||||
|
Branch: 1 branch
| |||||||||||
| 24 | |||||||||||
| 25 | 82 | ▶ | if ($options->{sync}) { | ||||||||
|
Branch: 1 branch
| |||||||||||
| 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 | 82 | ▶ | $fh->sync or die "Can't sync '$new_file': $!"; | ||||||||
|
Branch: 1 branch
| |||||||||||
| 32 | } | ||||||||||
| 33 | |||||||||||
| 34 | 82 | ▶ | close $fh or die "Can't close '$new_file': $!"; | ||||||||
|
Branch: 1 branch
| |||||||||||
| 35 | 82 | ▶ | rename $new_file => $file or die "Can't rename '$new_file' to '$file': $!"; | ||||||||
|
Branch: 1 branch
| |||||||||||
| 36 | } | ||||||||||
| 37 | |||||||||||
| 38 | 172 | 1; | |||||||||
| 39 | |||||||||||
| 40 | __END__ | ||||||||||