From a307212cb8dcd1faf1f0a706930cf4e555f3b633 Mon Sep 17 00:00:00 2001 From: "Kyle J. McKay" Date: Thu, 4 Jul 2013 19:38:26 -0700 Subject: [PATCH] Util.pm: new filedb_atomic_grep function The filedb_atomic_grep function works similarly to the perl grep function in that an array of the non-empty values returned by the subroutine is the final result. --- Girocco/Util.pm | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/Girocco/Util.pm b/Girocco/Util.pm index 838c573..bada935 100644 --- a/Girocco/Util.pm +++ b/Girocco/Util.pm @@ -8,9 +8,9 @@ use Girocco::Config; BEGIN { use base qw(Exporter); our @EXPORT = qw(scrypt jailed_file - lock_file unlock_file - filedb_atomic_append filedb_atomic_edit - valid_email valid_email_multi + lock_file unlock_file + filedb_atomic_append filedb_atomic_edit filedb_atomic_grep + valid_email valid_email_multi valid_repo_url valid_web_url); } @@ -51,9 +51,13 @@ sub lock_file { } sub unlock_file { - my ($path) = @_; + my ($path, $noreplace) = @_; - rename "$path.lock", $path or die "$path unlock failed: $!"; + if (!$noreplace) { + rename "$path.lock", $path or die "$path unlock failed: $!"; + } else { + unlink "$path.lock" or die "$path unlock failed: $!"; + } } sub filedb_atomic_append { @@ -97,6 +101,25 @@ sub filedb_atomic_edit { unlock_file($file); } +sub filedb_atomic_grep { + my ($file, $fn) = @_; + my @results = (); + + open my $src, $file or die "$file open for reading failed: $!"; + my $dst = lock_file($file); + + while (<$src>) { + my $result = $fn->($_); + push(@results, $result) if $result; + } + + close $dst or die "$file(l) close failed: $!"; + close $src; + + unlock_file($file, 1); + return @results; +} + sub valid_email { $_ = $_[0]; /^[a-zA-Z0-9+._-]+@[a-zA-Z0-9.-]+$/; -- 2.11.4.GIT