fu: Close-up of Fu, bringing a scoop of water to her mouth (Default)
fu ([personal profile] fu) wrote in [site community profile] changelog2010-11-30 03:54 pm

[dw-free] regexp cleanup

[commit: http://hg.dwscoalition.org/dw-free/rev/384b3e3c85c0]

http://bugs.dwscoalition.org/show_bug.cgi?id=2792

Efficiency/code cleanup: Refactor out common code into a function. For
efficiency, instead of using $&, use zero-width lookahead to detect where a
backslash is needed and insert it.

Patch by [personal profile] kareila.

Files modified:
  • cgi-bin/LJ/S2.pm
  • htdocs/customize/viewuser.bml
--------------------------------------------------------------------------------
diff -r 25d3da5f57a0 -r 384b3e3c85c0 cgi-bin/LJ/S2.pm
--- a/cgi-bin/LJ/S2.pm	Tue Nov 30 23:09:07 2010 +0800
+++ b/cgi-bin/LJ/S2.pm	Tue Nov 30 23:54:39 2010 +0800
@@ -1260,6 +1260,20 @@ sub alias_overriding_props {
     }
 }
 
+sub convert_prop_val {
+    my ( $prop, $val ) = @_;
+    $prop ||= {};
+    my $type = $prop->{type} || '';
+
+    return int( $val ) if $type eq "int";
+    return $val ? "true" : "false" if $type eq "bool";
+
+    # if not int or bool, treat property as text - use quotes,
+    # use zero-width lookahead to insert a backslash where needed
+    $val =~ s/(?=[\\\$\"])/\\/g;
+    return qq{"$val"};
+}
+
 sub layer_compile_user
 {
     my ($layer, $overrides) = @_;
@@ -1274,16 +1288,7 @@ sub layer_compile_user
 
     foreach my $name (sort keys %$overrides) {
         next if $name =~ /\W/;
-        my $prop = $overrides->{$name}->[0];
-        my $val = $overrides->{$name}->[1];
-        if ($prop->{'type'} eq "int") {
-            $val = int($val);
-        } elsif ($prop->{'type'} eq "bool") {
-            $val = $val ? "true" : "false";
-        } else {
-            $val =~ s/[\\\$\"]/\\$&/g;
-            $val = "\"$val\"";
-        }
+        my $val = convert_prop_val( @{ $overrides->{$name} } );
         $s2 .= "set $name = $val;\n";
     }
 
diff -r 25d3da5f57a0 -r 384b3e3c85c0 htdocs/customize/viewuser.bml
--- a/htdocs/customize/viewuser.bml	Tue Nov 30 23:09:07 2010 +0800
+++ b/htdocs/customize/viewuser.bml	Tue Nov 30 23:54:39 2010 +0800
@@ -146,14 +146,7 @@ _c?>
         next if $GET{'as'} eq "" && ! $had_override;
         next if $GET{'as'} eq "theme" && $type ne "Color";
 
-        if ($prop->{'type'} eq "int") {
-            $val = int($val);
-        } elsif ($prop->{'type'} eq "bool") {
-            $val = $val ? "true" : "false";
-        } else {
-            $val =~ s/[\\\$\"]/\\$&/g;
-            $val = "\"$val\"";
-        }
+        $val = LJ::S2::convert_prop_val( $prop, $val );
         $body .= "set $name = $val;\n";
     }
     $body .= "</textarea>";
--------------------------------------------------------------------------------