fileset: array search
authorMischa POSLAWSKY <perl@shiar.org>
Fri, 20 Nov 2009 00:40:14 +0000 (01:40 +0100)
committerMischa POSLAWSKY <perl@shiar.org>
Wed, 2 Dec 2009 15:09:59 +0000 (16:09 +0100)
lib/File/Rewrite.pm
t/10-fileset.t

index 784542d9f47074854c9789811429148a98f20087..2b05ded11175fc09025378089fa0fb67e8f64d6e 100644 (file)
@@ -10,15 +10,20 @@ our @EXPORT_OK = qw(fileset);
 
 sub fileset {
        my ($filename, $replace, $search) = @_;
-       $search = $replace if not defined $search;
        my $tmpname = "$filename.$$.tmp";
        my $changes = 0;
 
+       $search = $replace if not defined $search;
+
+       # generate a single regex to emulate smart match
+       $search = [$search] unless ref $search eq 'ARRAY';
+       $search = join('|', map { ref $_ ? $_ : "^\Q$_\E\$" } @$search);
+
        open my $src,  '<', $filename;
        open my $dest, '>', $tmpname;
        while (readline $src) {
                chomp;
-               if ($_ =~ (ref $search ? $search : qr/^\Q$search\E$/)) {
+               if ($_ =~ /$search/s) {
                        if (ref $replace eq 'ARRAY') {
                                if (@$replace and $_ eq $replace->[0]) {
                                        shift @$replace;
index db1575e9e51daf277ed0404fe7c16ac32a730ae0..fca87b70ec16343af7d91853b4065852644ddefc 100644 (file)
@@ -3,7 +3,7 @@
 use strict;
 use warnings;
 
-use Test::More tests => 16;
+use Test::More tests => 20;
 use Test::NoWarnings;
 
 use autodie;
@@ -59,7 +59,13 @@ testfileset('keep first',     "foo$/bar$/foo$/", ['foo'],       1, "foo$/bar$/")
 
 testfileset('add new array',  ".$/",        [['foo','.'], ''],  2, ".$/foo$/.$/");
 testfileset('replace by array', "$/foo$/.$/", [['foo',''], ''], 3, "foo$/.$/foo$/$/");
-testfileset('partial add',    "foo$/$/",   [['foo','.'], 'foo'], 1, "foo$/$/.$/");
+testfileset('partial add',    "foo$/$/",    [['foo','.'], 'foo'], 1, "foo$/$/.$/");
 
-is(remove_tree($target), 14, 'no unexpected files');
+my $SAMPLE2 = "$/foo$/and$/bar$/.$/";
+testfileset('keep pair',      $SAMPLE2, [['foo','bar']], 0, "$/foo$/and$/bar$/.$/");
+testfileset('keep order',     $SAMPLE2, [['bar','foo']], 2, "$/and$/bar$/.$/foo$/");
+testfileset('replace pair',   $SAMPLE2, [['fooo','barr'], ['bar','foo']], 4, "$/and$/.$/fooo$/barr$/");
+testfileset('mixed arrays',   $SAMPLE2, [['bar','foo','.'],['ignore',qr/a/]], 3, "$/foo$/bar$/.$/foo$/.$/");
+
+is(remove_tree($target), 18, 'no unexpected files');