File-Write-Rotate-0.14/0000755000175000017500000000000012164762056012302 5ustar s1s1File-Write-Rotate-0.14/README0000644000175000017500000002114412164762056013164 0ustar s1s1NAME File::Write::Rotate - Write to files that archive/rotate themselves VERSION version 0.14 SYNOPSIS use File::Write::Rotate; my $fwr = File::Write::Rotate->new( dir => '/var/log', # required prefix => 'myapp', # required #suffix => '.log', # default is '' size => 25*1024*1024, # default is 10MB, unless period is set histories => 12, # default is 10 #buffer_size => 100, # default is none ); # write, will write to /var/log/myapp.log, automatically rotate old log files # to myapp.log.1 when myapp.log reaches 25MB. will keep old log files up to # myapp.log.12. $fwr->write("This is a line\n"); $fwr->write("This is", " another line\n"); # compress old log files $fwr->compress; DESCRIPTION This module can be used to write to file, usually for logging, that can rotate itself. File will be opened in append mode. Locking will be done to avoid conflict when there are multiple writers. Rotation can be done by size (after a certain size is reached), by time (daily/monthly/yearly), or both. I first wrote this module for logging script STDERR output to files (see Tie::Handle::FileWriteRotate). ATTRIBUTES buffer_size => INT Get or set buffer size. If set to a value larger than 0, then when a write() failed, instead of dying, the message will be stored in an internal buffer first. When the number of buffer exceeds this size, then write() will die upon failure. Otherwise, every write() will try to flush the buffer. Can be used for example when a program runs as superuser/root then temporarily drops privilege to a normal user. During this period, logging can fail because the program cannot lock the lock file or write to the logging directory. Before dropping privilege, the program can set buffer_size to some larger-than-zero value to hold the messages emitted during dropping privilege. The next write() as the superuser/root will succeed and flush the buffer to disk (provided there is no other error condition, of course). METHODS $obj = File::Write::Rotate->new(%args) Create new object. Known arguments: * dir => STR (required) Directory to put the files in. * prefix => STR (required) Name of files. The files will be named like the following: "" will only be given if the "period" argument is set. If "period" is set to "yearly", "" will be "YYYY" (4-digit year). If "period" is "monthly", "" will be "YYYY-MM" (4-digit year and 2-digit month). If "period" is "daily", "" will be "YYYY-MM-DD" (4-digit year, 2-digit month, and 2-digit day). "" is either empty string for current file; or .1, .2 and so on for rotated files. .1 is the most recent rotated file, .2 is the next most recent, and so on. An example, with "prefix" set to "myapp": myapp # current file myapp.1 # most recently rotated myapp.2 # the next most recently rotated With "prefix" set to "myapp", "period" set to "monthly", "suffix" set to ".log": myapp.2012-12.log # file name for december 2012 myapp.2013-01.log # file name for january 2013 Like previous, but additionally with "size" also set (which will also rotate each period file if it exceeds specified size): myapp.2012-12.log # file(s) for december 2012 myapp.2012-12.log.1 myapp.2012-12.log.2 myapp.2013-01.log # file(s) for january 2013 All times will use local time, so you probably want to set "TZ" environment variable or equivalent methods to set time zone. * suffix => STR (default: '') Suffix to give to file names, usually file extension like ".log". See "prefix" for more details. If you use a yearly period, setting suffix is advised to avoid ambiguity with rotate suffix (for example, is "myapp.2012" the current file for year 2012 or file with 2012 rotate suffix?) * size => INT (default: 10*1024*1024) Maximum file size, in bytes, before rotation is triggered. The default is 10MB (10*1024*1024) *if* "period" is not set. If "period" is set, no default for "size" is provided, which means files will not be rotated for size (only for period). * period => STR Can be set to either "daily", "monthly", or "yearly". If set, will automatically rotate after period change. See "prefix" for more details. * histories => INT (default: 10) Number of rotated files to keep. After the number of files exceeds this, the oldest one will be deleted. 0 means not to keep any history, 1 means to only keep .1 file, and so on. * buffer_size => INT (default: 0) Set initial value of buffer. See the "buffer_size" attribute for more information. $fwr->write(@args) Write to file. Will automatically rotate file if period changes or file size exceeds specified limit. When rotating, will only keep a specified number of histories and delete the older ones. Uses locking, so multiple writers do not clobber one another. Lock file is named """.lck". Will wait for up to 1 minute to acquire lock, will die if failed to acquire lock. Does not append newline so you'll have to do it yourself. $fwr->compress Compress old rotated files. Currently uses pigz or gzip program to do the compression. Extension given to compressed file is ".gz". Normally, should be done using a separate process so as to avoid blocking the writers. Will not lock writers, but will create """-compress.pid" PID file to prevent multiple compression processes running and to signal the writers to postpone rotation. After compression is finished, will remove the PID file, so rotation can be done again on the next "write()" if necessary. SEE ALSO Log::Dispatch::FileRotate, which inspires this module. Differences between File::Write::Rotate (FWR) and Log::Dispatch::FileRotate (LDFR) are as follows: * FWR is not part of the Log::Dispatch family. This makes FWR more general to use. For using together with Log::Dispatch/Log4perl, I have also written Log::Dispatch::FileWriteRotate which is a direct (although not a perfect drop-in) replacement for Log::Dispatch::FileRotate. * Secondly, FWR does not use Date::Manip. Date::Manip is relatively large (loading Date::Manip 6.37 equals to loading 34 files and ~ 22k lines; while FWR itself is only < 1k lines!) As a consequence of this, FWR does not support DatePattern; instead, FWR replaces it with a simple daily/monthly/yearly period. * And lastly, FWR supports compressing and rotating compressed old files. Using separate processes like the Unix logrotate utility means having to deal with yet another race condition. FWR takes care of that for you (see the compress() method). You also have the option to do log compression in the same script/process if you want, which is convenient. There is no significant overhead difference between FWR and LDFR (FWR is slightly faster than LDFR on my testing). Tie::Handle::FileWriteRotate and Log::Dispatch::FileWriteRotate, which use this module. FAQ Why use autorotating log? Mainly convenience and low maintenance. You no longer need a separate rotator like the Unix logrotate utility (which when accidentally disabled or misconfigured will cause your logs to stop being rotated and grow indefinitely). What is the downside of using FWR (and LDFR)? Mainly performance overhead, as every write() involves locking to make it safe to use with multiple processes. Tested on my Core i5 3.1 GHz desktop, writing log lines in the size of ~ 200 bytes, raw writing to disk (SSD) has the speed of around 3.4mil/s, while using FWR it comes down to around 19.5k/s. However, this is not something you'll notice or need to worry about unless you're logging near that speed. AUTHOR Steven Haryanto COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. File-Write-Rotate-0.14/Build.PL0000644000175000017500000000173512164762056013604 0ustar s1s1 use strict; use warnings; use Module::Build 0.3601; my %module_build_args = ( "build_requires" => { "File::Slurp" => 0, "File::chdir" => 0, "Module::Build" => "0.3601", "Monkey::Patch::Action" => 0, "Test::Exception" => "0.31", "Test::More" => "0.98", "tainting" => "0.01" }, "configure_requires" => { "Module::Build" => "0.3601" }, "dist_abstract" => "Write to files that archive/rotate themselves", "dist_author" => [ "Steven Haryanto " ], "dist_name" => "File-Write-Rotate", "dist_version" => "0.14", "license" => "perl", "module_name" => "File::Write::Rotate", "recommends" => {}, "recursive_test_files" => 1, "requires" => { "File::Which" => 0, "Proc::PID::File" => 0, "SHARYANTO::File::Flock" => "0.49", "Taint::Runtime" => "0.03", "perl" => "5.010001" }, "script_files" => [] ); my $build = Module::Build->new(%module_build_args); $build->create_build_script; File-Write-Rotate-0.14/lib/0000755000175000017500000000000012164762056013050 5ustar s1s1File-Write-Rotate-0.14/lib/File/0000755000175000017500000000000012164762056013727 5ustar s1s1File-Write-Rotate-0.14/lib/File/Write/0000755000175000017500000000000012164762056015021 5ustar s1s1File-Write-Rotate-0.14/lib/File/Write/Rotate.pm0000644000175000017500000004216212164762056016622 0ustar s1s1package File::Write::Rotate; use 5.010001; use strict; use warnings; # we must not use Log::Any, looping if we are used as log output #use Log::Any '$log'; use Taint::Runtime qw(untaint is_tainted); use Time::HiRes 'time'; our $VERSION = '0.14'; # VERSION our $Debug; sub new { my $class = shift; my %args = @_; defined($args{dir}) or die "Please specify dir"; defined($args{prefix}) or die "Please specify prefix"; $args{suffix} //= ""; $args{size} //= 0; if ($args{period}) { $args{period} =~ /daily|day|month|year/i or die "Invalid period, please use daily/monthly/yearly"; } if (!$args{period} && !$args{size}) { $args{size} = 10*1024*1024; } $args{histories} //= 10; $args{_buffer} = []; my $self = bless \%args, $class; $self; } sub buffer_size { my $self = shift; if (@_) { my $old = $self->{buffer_size}; $self->{buffer_size} = $_[0]; return $old; } else { return $self->{buffer_size}; } } # file path, without the rotate suffix sub file_path { my ($self) = @_; # _now is calculated every time we access this method $self->{_now} = time(); my @lt = localtime($self->{_now}); $lt[5] += 1900; $lt[4]++; my $period; if ($self->{period}) { if ($self->{period} =~ /year/i) { $period = sprintf(".%04d", $lt[5]); } elsif ($self->{period} =~ /month/i) { $period = sprintf(".%04d-%02d", $lt[5], $lt[4]); } elsif ($self->{period} =~ /day|daily/i) { $period = sprintf(".%04d-%02d-%02d", $lt[5], $lt[4], $lt[3]); } } else { $period = ""; } join( '', $self->{dir}, '/', $self->{prefix}, $period, $self->{suffix}, ); } sub lock_file_path { my ($self) = @_; join( '', $self->{dir}, '/', $self->{prefix}, '.lck' ); } sub _lock { my ($self) = @_; if ($self->{_lock}) { return $self->{_lock}->_lock; } else { require SHARYANTO::File::Flock; $self->{_lock} = SHARYANTO::File::Flock->lock( $self->lock_file_path, {unlink=>1}); return 1; } } sub _unlock { my ($self) = @_; $self->{_lock}->_unlock if $self->{_lock}; } # will return \@files. each entry is [filename without compress suffix, # rotate_suffix (for sorting), period (for sorting), compress suffix (for # renaming back)] sub _get_files { my ($self) = @_; opendir my($dh), $self->{dir} or do { warn "Can't opendir '$self->{dir}': $!"; return; }; my @files; while (my $e = readdir($dh)) { my $cs = $1 if $e =~ s/(\.gz)\z//; next unless $e =~ /\A\Q$self->{prefix}\E (?:\. (?\d{4}(?:-\d\d(?:-\d\d)?)?) )? \Q$self->{suffix}\E (?:\. (?\d+) )? \z /x; push @files, [$e, $+{rotate_suffix} // 0, $+{period} // "", $cs // ""]; } closedir($dh); [sort {$b->[1] <=> $a->[1] || $a->[2] cmp $b->[2]} @files]; } # rename (increase rotation suffix) and keep only n histories. note: failure in # rotating should not be fatal, we just warn and return. sub _rotate { my ($self) = @_; my $locked = $self->_lock; my $files = $self->_get_files or goto EXIT; # is there a compression process in progress? this is marked by the # existence of -compress.pid PID file. if (-f "$self->{dir}/$self->{prefix}-compress.pid") { warn "Compression is in progress, rotation is postponed"; goto EXIT; } my $i; my $dir = $self->{dir}; for my $f (@$files) { my ($orig, $rs, $period, $cs) = @$f; $i++; #say "D: is_tainted \$dir? ".is_tainted($dir); #say "D: is_tainted \$orig? ".is_tainted($orig); #say "D: is_tainted \$cs? ".is_tainted($cs); # TODO actually, it's more proper to taint near the source (in this # case, _get_files) untaint \$orig; if ($i <= @$files-$self->{histories}) { say "D: Deleting old rotated file $dir/$orig$cs ..." if $Debug; unlink "$dir/$orig$cs" or warn "Can't delete $dir/$orig$cs: $!"; next; } my $new = $orig; if ($rs) { $new =~ s/\.(\d+)\z/"." . ($1+1)/e; } elsif (!$period || delete($self->{_tmp_hack_give_suffix_to_fp})) { $new .= ".1"; } if ($new ne $orig) { say "D: Renaming rotated file $dir/$orig$cs -> $dir/$new$cs ..." if $Debug; rename "$dir/$orig$cs", "$dir/$new$cs" or warn "Can't rename '$dir/$orig$cs' -> '$dir/$new$cs': $!"; } } EXIT: $self->_unlock if $locked; } sub _open { my $self = shift; my $fp = $self->file_path; open $self->{_fh}, ">>", $fp or die "Can't open '$fp': $!"; my $oldfh = select $self->{_fh}; $| = 1; select $oldfh; # set autoflush $self->{_fp} = $fp; } # (re)open file and optionally rotate if necessary sub _rotate_and_open { my ($self) = @_; my $fp = $self->file_path; my ($do_open, $do_rotate) = @_; # stat the current file (not our handle _fp) my @st = stat($fp); # file does not exist yet, create unless (-e _) { $do_open++; goto DOIT; } die "Can't stat '$fp': $!" unless @st; my $finode = $st[1]; # file is not opened yet, open unless ($self->{_fh}) { $self->_open; } # period has changed, rotate if ($self->{_fp} ne $fp) { $do_rotate++; goto DOIT; } # check whether size has been exceeded my $inode; if ($self->{size} > 0) { @st = stat($self->{_fh}); my $size = $st[7]; $inode = $st[1]; if ($size >= $self->{size}) { say "D: Size of $self->{_fp} is $size, exceeds $self->{size}, rotating ..." if $Debug; $do_rotate++; $self->{_tmp_hack_give_suffix_to_fp} = 1; goto DOIT; } } # check whether other process has rename/rotate under us (for example, # 'prefix' has been moved to 'prefix.1'), in which case we need to reopen if ($inode && $finode != $inode) { $do_open++; goto DOIT; } DOIT: $self->_rotate if $do_rotate; $self->_open if $do_rotate || $do_open; # (re)open } sub write { my $self = shift; # the buffering implementation is currently pretty naive. it assume any # die() as a write failure and store the message to buffer. # FYI: if privilege is dropped from superuser, the failure is usually at # locking the lock file (permission denied). my @msg = (map({@$_} @{$self->{_buffer}}), @_); eval { my $locked = $self->_lock; $self->_rotate_and_open; # for testing only $self->{_hook_before_print}->() if $self->{_hook_before_print}; # syntax limitation? can't do print $self->{_fh} ... directly my $fh = $self->{_fh}; print $fh @msg; $self->{_buffer} = []; $self->_unlock if $locked; }; my $err = $@; if ($err) { if (($self->{buffer_size} // 0) > @{$self->{_buffer}}) { # put message to buffer temporarily push @{$self->{_buffer}}, [@_]; } else { # buffer is already full, let's dump the buffered + current message # to the die message anyway. die join( "", "Can't log", (@{$self->{_buffer}} ? " (buffer is full, ". scalar(@{$self->{_buffer}})." message(s))" : ""), ": $err, log message(s)=", @msg ); } } } sub compress { require File::Which; require Proc::PID::File; my ($self) = @_; my $cmd; for (qw/pigz gzip/) { if (File::Which::which($_)) { $cmd = $_; last; } } if (!$cmd) { warn "No compressor program available, compress aborted"; return; } my $locked = $self->_lock; my $files = $self->_get_files or goto EXIT1; my $pid = Proc::PID::File->new( dir => $self->{dir}, name => "$self->{prefix}-compress", verify => 1, ); if ($pid->alive) { warn "Another compression is in progress"; goto EXIT1; } my @tocompress; my $dir = $self->{dir}; for my $f (@$files) { my ($orig, $rs, $period, $cs) = @$f; next unless $rs; next if $cs; push @tocompress, $orig; } EXIT1: $self->_unlock if $locked; if (@tocompress) { system $cmd, "--force", (map {"$self->{dir}/$_"} @tocompress); } } sub DESTROY { my ($self) = @_; $self->_unlock; # Proc::PID::File's DESTROY seem to create an empty PID file, remove it. unlink "$self->{dir}/$self->{prefix}-compress.pid"; } 1; #ABSTRACT: Write to files that archive/rotate themselves __END__ =pod =head1 NAME File::Write::Rotate - Write to files that archive/rotate themselves =head1 VERSION version 0.14 =head1 SYNOPSIS use File::Write::Rotate; my $fwr = File::Write::Rotate->new( dir => '/var/log', # required prefix => 'myapp', # required #suffix => '.log', # default is '' size => 25*1024*1024, # default is 10MB, unless period is set histories => 12, # default is 10 #buffer_size => 100, # default is none ); # write, will write to /var/log/myapp.log, automatically rotate old log files # to myapp.log.1 when myapp.log reaches 25MB. will keep old log files up to # myapp.log.12. $fwr->write("This is a line\n"); $fwr->write("This is", " another line\n"); # compress old log files $fwr->compress; =head1 DESCRIPTION This module can be used to write to file, usually for logging, that can rotate itself. File will be opened in append mode. Locking will be done to avoid conflict when there are multiple writers. Rotation can be done by size (after a certain size is reached), by time (daily/monthly/yearly), or both. I first wrote this module for logging script STDERR output to files (see L). =for Pod::Coverage ^(file_path|lock_file_path|DESTROY)$ =head1 ATTRIBUTES =head2 buffer_size => INT Get or set buffer size. If set to a value larger than 0, then when a write() failed, instead of dying, the message will be stored in an internal buffer first. When the number of buffer exceeds this size, then write() will die upon failure. Otherwise, every write() will try to flush the buffer. Can be used for example when a program runs as superuser/root then temporarily drops privilege to a normal user. During this period, logging can fail because the program cannot lock the lock file or write to the logging directory. Before dropping privilege, the program can set buffer_size to some larger-than-zero value to hold the messages emitted during dropping privilege. The next write() as the superuser/root will succeed and flush the buffer to disk (provided there is no other error condition, of course). =head1 METHODS =head2 $obj = File::Write::Rotate->new(%args) Create new object. Known arguments: =over =item * dir => STR (required) Directory to put the files in. =item * prefix => STR (required) Name of files. The files will be named like the following: C<< >> will only be given if the C argument is set. If C is set to C, C<< >> will be C (4-digit year). If C is C, C<< >> will be C (4-digit year and 2-digit month). If C is C, C<< >> will be C (4-digit year, 2-digit month, and 2-digit day). C<< >> is either empty string for current file; or C<.1>, C<.2> and so on for rotated files. C<.1> is the most recent rotated file, C<.2> is the next most recent, and so on. An example, with C set to C: myapp # current file myapp.1 # most recently rotated myapp.2 # the next most recently rotated With C set to C, C set to C, C set to C<.log>: myapp.2012-12.log # file name for december 2012 myapp.2013-01.log # file name for january 2013 Like previous, but additionally with C also set (which will also rotate each period file if it exceeds specified size): myapp.2012-12.log # file(s) for december 2012 myapp.2012-12.log.1 myapp.2012-12.log.2 myapp.2013-01.log # file(s) for january 2013 All times will use local time, so you probably want to set C environment variable or equivalent methods to set time zone. =item * suffix => STR (default: '') Suffix to give to file names, usually file extension like C<.log>. See C for more details. If you use a yearly period, setting suffix is advised to avoid ambiguity with rotate suffix (for example, is C the current file for year 2012 or file with C<2012> rotate suffix?) =item * size => INT (default: 10*1024*1024) Maximum file size, in bytes, before rotation is triggered. The default is 10MB (10*1024*1024) I C is not set. If C is set, no default for C is provided, which means files will not be rotated for size (only for period). =item * period => STR Can be set to either C, C, or C. If set, will automatically rotate after period change. See C for more details. =item * histories => INT (default: 10) Number of rotated files to keep. After the number of files exceeds this, the oldest one will be deleted. 0 means not to keep any history, 1 means to only keep C<.1> file, and so on. =item * buffer_size => INT (default: 0) Set initial value of buffer. See the C attribute for more information. =back =head2 $fwr->write(@args) Write to file. Will automatically rotate file if period changes or file size exceeds specified limit. When rotating, will only keep a specified number of histories and delete the older ones. Uses locking, so multiple writers do not clobber one another. Lock file is named C<< >>C<.lck>. Will wait for up to 1 minute to acquire lock, will die if failed to acquire lock. Does not append newline so you'll have to do it yourself. =head2 $fwr->compress Compress old rotated files. Currently uses B or B program to do the compression. Extension given to compressed file is C<.gz>. Normally, should be done using a separate process so as to avoid blocking the writers. Will not lock writers, but will create C<< >>C<-compress.pid> PID file to prevent multiple compression processes running and to signal the writers to postpone rotation. After compression is finished, will remove the PID file, so rotation can be done again on the next C if necessary. =head1 SEE ALSO L, which inspires this module. Differences between File::Write::Rotate (FWR) and Log::Dispatch::FileRotate (LDFR) are as follows: =over =item * FWR is not part of the L family. This makes FWR more general to use. For using together with Log::Dispatch/Log4perl, I have also written L which is a direct (although not a perfect drop-in) replacement for Log::Dispatch::FileRotate. =item * Secondly, FWR does not use L. Date::Manip is relatively large (loading Date::Manip 6.37 equals to loading 34 files and ~ 22k lines; while FWR itself is only < 1k lines!) As a consequence of this, FWR does not support DatePattern; instead, FWR replaces it with a simple daily/monthly/yearly period. =item * And lastly, FWR supports compressing and rotating compressed old files. Using separate processes like the Unix B utility means having to deal with yet another race condition. FWR takes care of that for you (see the compress() method). You also have the option to do log compression in the same script/process if you want, which is convenient. =back There is no significant overhead difference between FWR and LDFR (FWR is slightly faster than LDFR on my testing). L and Log::Dispatch::FileWriteRotate, which use this module. =head1 FAQ =head2 Why use autorotating log? Mainly convenience and low maintenance. You no longer need a separate rotator like the Unix B utility (which when accidentally disabled or misconfigured will cause your logs to stop being rotated and grow indefinitely). =head2 What is the downside of using FWR (and LDFR)? Mainly performance overhead, as every write() involves locking to make it safe to use with multiple processes. Tested on my Core i5 3.1 GHz desktop, writing log lines in the size of ~ 200 bytes, raw writing to disk (SSD) has the speed of around 3.4mil/s, while using FWR it comes down to around 19.5k/s. However, this is not something you'll notice or need to worry about unless you're logging near that speed. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut File-Write-Rotate-0.14/MANIFEST.SKIP0000644000175000017500000000000312164762056014171 0ustar s1s1~$ File-Write-Rotate-0.14/Changes0000644000175000017500000000311412164762056013574 0ustar s1s1Revision history for File-Write-Rotate 0.14 2013-07-03 (SHARYANTO) No functional changes. Force fixed SHARYANTO::File::Flock version (0.49). 0.13 2013-04-12 (SHARYANTO) No functional changes. Add FAQ item on why use FWR and the downside. 0.12 2013-04-12 (SHARYANTO) No functional changes. Update module name in POD and expand the explanation on the difference between FWR & LDFR. 0.11 2012-12-28 (SHARYANTO) No functional changes. Tweak error message. 0.10 2012-12-28 (SHARYANTO) [NEW FEATURES] - Add buffering (attribute: buffer_size) to buffer messages during temporary write() failure. 0.09 2012-12-28 (SHARYANTO) Make rotate pass under taint-mode. 0.08 2012-12-28 (SHARYANTO) [BUG FIXES] - Can now rotate on the first write() instead of on the second and subsequent. 0.07 2012-12-27 (SHARYANTO) Avoid using Log::Any, because we are used as backend for Log::Dispatch::FileWriteRotate (thus, a loop). 0.06 2012-12-27 (SHARYANTO) Set autoflush (to pass Log-Any-App09 tests). 0.05 2012-12-26 (SHARYANTO) No functional changes. Mention 'period' argument in POD. 0.04 2012-12-26 (SHARYANTO) - A small fix in DESTROY(). 0.03 2012-12-25 (SHARYANTO) No functional changes. Extract flocking routines to SHARYANTO::File::Flock. 0.02 2012-12-22 (SHARYANTO) No functional changes. Additions/corrections for POD. 0.01 2012-12-21 (SHARYANTO) First release. File-Write-Rotate-0.14/dist.ini0000644000175000017500000000115312164762056013746 0ustar s1s1version = 0.14 name = File-Write-Rotate author = Steven Haryanto license = Perl_5 copyright_holder = Steven Haryanto [MetaResources] homepage = http://metacpan.org/release/File-Write-Rotate repository = http://github.com/sharyanto/perl-File-Write-Rotate [@SHARYANTO] [Prereqs / TestRequires] File::chdir=0 File::Slurp=0 Monkey::Patch::Action=0 tainting=0.01 Test::Exception=0.31 Test::More=0.98 [Prereqs] perl=5.010001 File::Which=0 ;Log::Any=0 Proc::PID::File=0 SHARYANTO::File::Flock=0.49 ; i choose use this since we already use tainting (which uses this) Taint::Runtime=0.03 File-Write-Rotate-0.14/LICENSE0000644000175000017500000004366412164762056013324 0ustar s1s1This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2013 by Steven Haryanto. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Suite 500, Boston, MA 02110-1335 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2013 by Steven Haryanto. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End File-Write-Rotate-0.14/t/0000755000175000017500000000000012164762056012545 5ustar s1s1File-Write-Rotate-0.14/t/00-compile.t0000644000175000017500000000312512164762056014600 0ustar s1s1#!perl use strict; use warnings; use Test::More; use File::Find; use File::Temp qw{ tempdir }; my @modules; find( sub { return if $File::Find::name !~ /\.pm\z/; my $found = $File::Find::name; $found =~ s{^lib/}{}; $found =~ s{[/\\]}{::}g; $found =~ s/\.pm$//; # nothing to skip push @modules, $found; }, 'lib', ); sub _find_scripts { my $dir = shift @_; my @found_scripts = (); find( sub { return unless -f; my $found = $File::Find::name; # nothing to skip open my $FH, '<', $_ or do { note( "Unable to open $found in ( $! ), skipping" ); return; }; my $shebang = <$FH>; return unless $shebang =~ /^#!.*?\bperl\b\s*$/; push @found_scripts, $found; }, $dir, ); return @found_scripts; } my @scripts; do { push @scripts, _find_scripts($_) if -d $_ } for qw{ bin script scripts }; my $plan = scalar(@modules) + scalar(@scripts); $plan ? (plan tests => $plan) : (plan skip_all => "no tests to run"); { # fake home for cpan-testers # no fake requested ## local $ENV{HOME} = tempdir( CLEANUP => 1 ); like( qx{ $^X -Ilib -e "require $_; print '$_ ok'" }, qr/^\s*$_ ok/s, "$_ loaded ok" ) for sort @modules; SKIP: { eval "use Test::Script 1.05; 1;"; skip "Test::Script needed to test script compilation", scalar(@scripts) if $@; foreach my $file ( @scripts ) { my $script = $file; $script =~ s!.*/!!; script_compiles( $file, "$script script compiles" ); } } } File-Write-Rotate-0.14/t/rotate.t0000644000175000017500000000550612164762056014236 0ustar s1s1#!perl use 5.010; use strict; use warnings; use Test::More 0.98; use File::chdir; use File::Path qw(remove_tree); use File::Slurp; use File::Temp qw(tempdir); use File::Write::Rotate; use Taint::Runtime qw(untaint); my $dir = tempdir(CLEANUP=>1); $CWD = $dir; test_rotate( # correctly rename, only keep N histories, doesn't touch other prefixes, # handle compress suffix name => "basic rotate", args => [prefix=>"a", histories=>3], files_before => [qw/a a.1 a.2.gz a.3 b b.1 b.2 b.3 b.4/], before_rotate => sub { write_file("a" , "zero"); write_file("a.1", "one"); write_file("a.2.gz", "two"); write_file("b.1" , "untouched"); }, files_after => [qw/a.1 a.2 a.3.gz b b.1 b.2 b.3 b.4/], after_rotate => sub { is(~~read_file("a.1"), "zero", "a -> a.1"); is(~~read_file("a.2"), "one", "a.2 -> a.2.gz"); is(~~read_file("a.3.gz"), "two", "a.2.gz -> a.3.gz"); is(~~read_file("b.1"), "untouched", "b.1 untouched"); }, ); test_rotate( name => "period, suffix", args => [prefix=>"a", suffix=>".log", histories=>2], files_before => [qw/a.2010-01 a.2011.log a.2012-10.log a.2012-11.log a.2012-12.log/], files_after => [qw/a.2010-01 a.2012-11.log a.2012-12.log/], ); { use tainting; test_rotate( # test rename and unlink works under tainting name => "under tainting", args => [prefix=>"a", histories=>3], files_before => [qw/a a.1 a.2 a.3/], before_rotate => sub { write_file($_, "") for (qw/a a.1 a.2 a.3/); }, files_after => [qw/a.1 a.2 a.3/], after_rotate => sub { }, ); } DONE_TESTING: done_testing; if (Test::More->builder->is_passing) { $CWD = "/"; } else { diag "there are failing tests, not deleting test data dir $dir"; } sub test_rotate { my (%args) = @_; subtest $args{name} => sub { my $fwr = File::Write::Rotate->new( dir => $dir, @{$args{args}} ); my $dh; # remove all files first opendir $dh, "."; while (my $e = readdir($dh)) { next if $e eq '.' || $e eq '..'; untaint \$e; remove_tree($e); } write_file($_, "") for @{$args{files_before}}; $args{before_rotate}->($fwr) if $args{before_rotate}; $fwr->_rotate; undef $fwr; my @files; opendir $dh, "."; while (my $e = readdir($dh)) { next if $e eq '.' || $e eq '..'; push @files, $e; } @files = sort @files; is_deeply(\@files, $args{files_after}, "files_after") or diag explain \@files; $args{after_rotate}->($fwr) if $args{after_rotate}; }; } File-Write-Rotate-0.14/t/write.t0000644000175000017500000001345712164762056014076 0ustar s1s1#!perl use 5.010; use strict; use warnings; use File::chdir; use File::Path qw(remove_tree); use File::Slurp; use File::Temp qw(tempdir); use File::Write::Rotate; use Monkey::Patch::Action qw(patch_package); use Test::Exception; use Test::More 0.98; my $dir = tempdir(CLEANUP=>1); $CWD = $dir; subtest "basic" => sub { delete_all_files(); my $fwr = File::Write::Rotate->new(dir=>$dir, prefix=>"a"); $fwr->write("[1]"); is(~~read_file("a"), "[1]"); $fwr->write("[2]", "[3]"); is(~~read_file("a"), "[1][2][3]"); }; subtest "rotate by size" => sub { delete_all_files(); my $fwr = File::Write::Rotate->new(dir=>$dir, prefix=>"a", size=>3); $fwr->write("[1]"); is(~~read_file("a"), "[1]"); $fwr->write("[2]", "[3]"); is(~~read_file("a"), "[2][3]"); is(~~read_file("a.1"), "[1]"); }; # just testing at some non-negligible size subtest "rotate size, 20k" => sub { delete_all_files(); my $fwr = File::Write::Rotate->new(dir=>$dir, prefix=>"a", size=>20*1000); my $msg = "x" x 100; for (1..200) { $fwr->write($msg) } is( (-s "a") , 20000); ok(!(-e "a.1")); $fwr->write($msg); is( (-s "a") , 100); is( (-s "a.1"), 20000); }; subtest "rotate by period, daily" => sub { delete_all_files(); my $ph; $ph = set_time_to(1356090474); # 2012-12-21 my $fwr = File::Write::Rotate->new(dir=>$dir, prefix=>"a", period=>"daily"); $fwr->write("[1]"); is(~~read_file("a.2012-12-21"), "[1]"); $fwr->write("[2]", "[3]"); is(~~read_file("a.2012-12-21"), "[1][2][3]"); $ph = set_time_to(1356090474 + 86400); # 2012-12-22 $fwr->write("[4]"); is(~~read_file("a.2012-12-22"), "[4]"); }; subtest "rotate by period, monthly" => sub { delete_all_files(); my $ph; $ph = set_time_to(1356090474); # 2012-12-21 my $fwr = File::Write::Rotate->new(dir=>$dir, prefix=>"a", period=>"monthly"); $fwr->write("[1]"); is(~~read_file("a.2012-12"), "[1]"); $fwr->write("[2]", "[3]"); is(~~read_file("a.2012-12"), "[1][2][3]"); $ph = set_time_to(1356090474 + 31*86400); # 2013-01-21 $fwr->write("[4]"); is(~~read_file("a.2013-01"), "[4]"); }; subtest "rotate by period, yearly" => sub { delete_all_files(); my $ph; $ph = set_time_to(1356090474); # 2012-12-21 my $fwr = File::Write::Rotate->new(dir=>$dir, prefix=>"a", period=>"year"); $fwr->write("[1]"); is(~~read_file("a.2012"), "[1]"); $fwr->write("[2]", "[3]"); is(~~read_file("a.2012"), "[1][2][3]"); $ph = set_time_to(1356090474 + 31*86400); # 2013-01-21 $fwr->write("[4]"); is(~~read_file("a.2013"), "[4]"); }; subtest "rotate by period + size, suffix" => sub { delete_all_files(); my $ph; $ph = set_time_to(1356090474); # 2012-12-21 my $fwr = File::Write::Rotate->new(dir=>$dir, prefix=>"a", suffix=>".log", size=>3, period=>"daily"); $fwr->write("[1]"); is(~~read_file("a.2012-12-21.log"), "[1]"); $fwr->write("[2]", "[3]"); is(~~read_file("a.2012-12-21.log"), "[2][3]"); is(~~read_file("a.2012-12-21.log.1"), "[1]"); $fwr->write("[4]"); is(~~read_file("a.2012-12-21.log"), "[4]"); is(~~read_file("a.2012-12-21.log.1"), "[2][3]"); is(~~read_file("a.2012-12-21.log.2"), "[1]"); $ph = set_time_to(1356090474 + 86400); # 2012-12-22 $fwr->write("[5]"); is(~~read_file("a.2012-12-22.log"), "[5]"); }; subtest "two writers, one rotates" => sub { delete_all_files(); my $fwr1 = File::Write::Rotate->new(dir=>$dir, prefix=>"a"); my $fwr2 = File::Write::Rotate->new(dir=>$dir, prefix=>"a", size=>3); $fwr1->write("[1.1]"); is(~~read_file("a"), "[1.1]"); $fwr2->write("[2.1]"); is(~~read_file("a"), "[2.1]"); is(~~read_file("a.1"), "[1.1]"); $fwr1->write("[1.2]"); is(~~read_file("a"), "[2.1][1.2]"); is(~~read_file("a.1"), "[1.1]"); }; # if FWR only rotates after second write(), then there will be cases where the # file won't get rotated at all. subtest "rotate on first write()" => sub { delete_all_files(); write_file("$dir/a", "123"); my $fwr = File::Write::Rotate->new(dir=>$dir, prefix=>"a", size=>3); $fwr->write("[1]"); is(~~read_file("a"), "[1]"); is(~~read_file("a.1"), "123"); }; subtest "buffer (success)" => sub { delete_all_files(); my $fwr = File::Write::Rotate->new(dir=>$dir, prefix=>"a", buffer_size=>2); $fwr->{_hook_before_print} = sub { die }; lives_ok { $fwr->write("[1]") } "first message to buffer"; lives_ok { $fwr->write("[2]") } "second message to buffer"; undef $fwr->{_hook_before_print}; $fwr->write("[3]"); is(~~read_file("a"), "[1][2][3]", "buffered messages gets logged"); $fwr->write("[4]"); is(~~read_file("a"), "[1][2][3][4]", "buffered is emptied"); }; subtest "buffer (failed, full), buffer_size attribute" => sub { delete_all_files(); my $fwr = File::Write::Rotate->new(dir=>$dir, prefix=>"a"); $fwr->buffer_size(2); is($fwr->buffer_size, 2, 'buffer_size()'); local $fwr->{_hook_before_print} = sub { die }; lives_ok { $fwr->write("[1]") } "first message to buffer"; lives_ok { $fwr->write("[2]") } "second message to buffer"; throws_ok { $fwr->write("[3]") } qr/\Q[1][2][3]\E/, "buffer is full"; }; DONE_TESTING: done_testing; if (Test::More->builder->is_passing) { $CWD = "/"; } else { diag "there are failing tests, not deleting test data dir $dir"; } sub delete_all_files { # remove all files first opendir my($dh), "."; while (my $e = readdir($dh)) { next if $e eq '.' || $e eq '..'; remove_tree($e); } } our $Time; sub _time() { $Time } sub set_time_to { $Time = shift; my $ph = patch_package("File::Write::Rotate", 'time', 'replace', \&_time); return $ph; } File-Write-Rotate-0.14/t/release-pod-coverage.t0000644000175000017500000000076512164762056016733 0ustar s1s1#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } use Test::More; eval "use Test::Pod::Coverage 1.08"; plan skip_all => "Test::Pod::Coverage 1.08 required for testing POD coverage" if $@; eval "use Pod::Coverage::TrustPod"; plan skip_all => "Pod::Coverage::TrustPod required for testing POD coverage" if $@; all_pod_coverage_ok({ coverage_class => 'Pod::Coverage::TrustPod' }); File-Write-Rotate-0.14/t/release-pod-syntax.t0000644000175000017500000000045012164762056016455 0ustar s1s1#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } use Test::More; eval "use Test::Pod 1.41"; plan skip_all => "Test::Pod 1.41 required for testing POD" if $@; all_pod_files_ok(); File-Write-Rotate-0.14/t/release-rinci.t0000644000175000017500000000050412164762056015453 0ustar s1s1#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } use Test::More; eval "use Test::Rinci 0.01"; plan skip_all => "Test::Rinci 0.01 required for testing Rinci metadata" if $@; metadata_in_all_modules_ok(); File-Write-Rotate-0.14/MANIFEST0000644000175000017500000000032212164762056013430 0ustar s1s1Build.PL Changes LICENSE MANIFEST MANIFEST.SKIP META.json META.yml README dist.ini lib/File/Write/Rotate.pm t/00-compile.t t/release-pod-coverage.t t/release-pod-syntax.t t/release-rinci.t t/rotate.t t/write.t File-Write-Rotate-0.14/META.json0000644000175000017500000000320612164762056013724 0ustar s1s1{ "abstract" : "Write to files that archive/rotate themselves", "author" : [ "Steven Haryanto " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 4.300028, CPAN::Meta::Converter version 2.120921", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "File-Write-Rotate", "prereqs" : { "build" : { "requires" : { "Module::Build" : "0.3601" } }, "configure" : { "requires" : { "Module::Build" : "0.3601" } }, "develop" : { "requires" : { "Pod::Coverage::TrustPod" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Rinci" : "0.01" } }, "runtime" : { "requires" : { "File::Which" : "0", "Proc::PID::File" : "0", "SHARYANTO::File::Flock" : "0.49", "Taint::Runtime" : "0.03", "perl" : "5.010001" } }, "test" : { "requires" : { "File::Slurp" : "0", "File::chdir" : "0", "Monkey::Patch::Action" : "0", "Test::Exception" : "0.31", "Test::More" : "0.98", "tainting" : "0.01" } } }, "release_status" : "stable", "resources" : { "homepage" : "http://metacpan.org/release/File-Write-Rotate", "repository" : { "url" : "http://github.com/sharyanto/perl-File-Write-Rotate" } }, "version" : "0.14" } File-Write-Rotate-0.14/META.yml0000644000175000017500000000146512164762056013561 0ustar s1s1--- abstract: 'Write to files that archive/rotate themselves' author: - 'Steven Haryanto ' build_requires: File::Slurp: 0 File::chdir: 0 Module::Build: 0.3601 Monkey::Patch::Action: 0 Test::Exception: 0.31 Test::More: 0.98 tainting: 0.01 configure_requires: Module::Build: 0.3601 dynamic_config: 0 generated_by: 'Dist::Zilla version 4.300028, CPAN::Meta::Converter version 2.120921' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 name: File-Write-Rotate requires: File::Which: 0 Proc::PID::File: 0 SHARYANTO::File::Flock: 0.49 Taint::Runtime: 0.03 perl: 5.010001 resources: homepage: http://metacpan.org/release/File-Write-Rotate repository: http://github.com/sharyanto/perl-File-Write-Rotate version: 0.14