package Regexp::Wildcards;

use strict;
use warnings;

use Carp qw/croak/;
use Text::Balanced qw/extract_bracketed/;

=head1 NAME

Regexp::Wildcards - Converts wildcard expressions to Perl regular expressions.

=head1 VERSION

Version 0.08

=cut

our $VERSION = '0.08';

=head1 SYNOPSIS

    use Regexp::Wildcards;

    my $rw = Regexp::Wildcards->new(type => 'unix');

    my $re;
    $re = $rw->convert('a{b?,c}*');          # Do it Unix shell style.
    $re = $rw->convert('a?,b*',   'win32');  # Do it Windows shell style.
    $re = $rw->convert('*{x,y}?', 'jokers'); # Process the jokers and escape the rest.
    $re = $rw->convert('%a_c%',    'sql');   # Turn SQL wildcards into regexps.

    $rw = Regexp::Wildcards->new(
     do      => [ qw/jokers brackets/ ], # Do jokers and brackets.
     capture => [ qw/any greedy/ ],      # Capture *'s greedily.
    );

    $rw->do(add => 'groups');            # Don't escape groups.
    $rw->capture(rem => [ qw/greedy/ ]); # Actually we want non-greedy matches.
    $re = $rw->convert('*a{,(b)?}?c*');  # '(.*?)a(?:|(b).).c(.*?)'
    $rw->capture();                      # No more captures.

=head1 DESCRIPTION

In many situations, users may want to specify patterns to match but don't need the full power of regexps. Wildcards make one of those sets of simplified rules. This module converts wildcard expressions to Perl regular expressions, so that you can use them for matching.

It handles the C<*> and C<?> shell jokers, as well as Unix bracketed alternatives C<{,}>, but also C<%> and C<_> SQL wildcards. It can also keep original C<(...)> groups. Backspace (C<\>) is used as an escape character.

Typesets that mimic the behaviour of Windows and Unix shells are also provided.

=head1 METHODS

=cut

sub _check_self {
 croak 'First argument isn\'t a valid ' . __PACKAGE__ . ' object'
  unless ref $_[0] and $_[0]->isa(__PACKAGE__);
}

my %types = (
 jokers   => [ qw/jokers/ ],
 sql      => [ qw/sql/ ],
 commas   => [ qw/commas/ ],
 brackets => [ qw/brackets/ ],
 unix     => [ qw/jokers brackets/ ],
 win32    => [ qw/jokers commas/ ],
);
$types{$_} = $types{win32} for qw/dos os2 MSWin32 cygwin/;

my %escapes = (
 jokers   => '?*',
 sql      => '%_',
 commas   => ',',
 brackets => '{},',
 groups   => '()',
);

my %captures = (
 single   => sub { $_[1] ? '(.)' : '.' },
 any      => sub { $_[1] ? ($_[0]->{greedy} ? '(.*)'
                                            : '(.*?)')
                         : '.*' },
 brackets => sub { $_[1] ? '(' : '(?:'; },
 greedy   => undef
);

sub _validate {
 my $self  = shift;
 _check_self $self;
 my $valid = shift;
 my $old   = shift;
 $old = { } unless defined $old;
 my $c;
 if (@_ <= 1) {
  $c = { set => $_[0] };
 } elsif (@_ % 2) {
  croak 'Arguments must be passed as an unique scalar or as key => value pairs';
 } else {
  my %args = @_;
  $c = { map { (exists $args{$_}) ? ($_ => $args{$_}) : () } qw/set add rem/ };
 }
 for (qw/set add rem/) {
  my $v = $c->{$_};
  next unless defined $v;
  my $cb = {
   ''      => sub { +{ ($_[0] => 1) x (exists $valid->{$_[0]}) } },
   'ARRAY' => sub { +{ map { ($_ => 1) x (exists $valid->{$_}) } @{$_[0]} } },
   'HASH'  => sub { +{ map { ($_ => $_[0]->{$_}) x (exists $valid->{$_}) }
                        keys %{$_[0]} } }
  }->{ ref $v };
  croak 'Wrong option set' unless $cb;
  $c->{$_} = $cb->($v);
 }
 my $config = (exists $c->{set}) ? $c->{set} : $old;
 $config->{$_} = $c->{add}->{$_} for grep $c->{add}->{$_},
                                                keys %{$c->{add} || {}};
 delete $config->{$_} for grep $c->{rem}->{$_}, keys %{$c->{rem} || {}};
 $config;
}

sub _do {
 my $self = shift;
 my $config;
 $config->{do} = $self->_validate(\%escapes, $self->{do}, @_);
 $config->{escape} = '';
 $config->{escape} .= $escapes{$_} for keys %{$config->{do}};
 $config->{escape} = quotemeta $config->{escape};
 $config;
}

sub do {
 my $self = shift;
 _check_self $self;
 my $config = $self->_do(@_);
 $self->{$_} = $config->{$_} for keys %$config;
 $self;
}

sub _capture {
 my $self = shift;
 my $config;
 $config->{capture} = $self->_validate(\%captures, $self->{capture}, @_);
 $config->{greedy}  = delete $config->{capture}->{greedy};
 for (keys %captures) {
  $config->{'c_' . $_} = $captures{$_}->($config, $config->{capture}->{$_})
                                               if $captures{$_}; # Skip 'greedy'
 }
 $config;
}

sub capture {
 my $self = shift;
 _check_self $self;
 my $config = $self->_capture(@_);
 $self->{$_} = $config->{$_} for keys %$config;
 $self;
}

sub _type {
 my ($self, $type) = @_;
 $type = 'unix'      unless defined $type;
 croak 'Wrong type'  unless exists $types{$type};
 my $config = $self->_do($types{$type});
 $config->{type} = $type;
 $config;
}

sub type {
 my $self = shift;
 _check_self $self;
 my $config = $self->_type(@_);
 $self->{$_} = $config->{$_} for keys %$config;
 $self;
}

sub new {
 my $class = shift;
 $class = ref($class) || $class || __PACKAGE__;
 croak 'Optional arguments must be passed as key => value pairs' if @_ % 2;
 my %args = @_;
 my $self = { };
 bless $self, $class;
 if (defined $args{do}) {
  $self->do($args{do});
 } else {
  $self->type($args{type});
 }
 $self->capture($args{capture});
}

=head2 C<< new [ do => $what | type => $type ], capture => $captures >>

Constructs a new L<Regexp::Wildcard> object.

C<do> lists all features that should be enabled when converting wildcards to regexps. Refer to L</do> for details on what can be passed in C<$what>.

The C<type> specifies a predefined set of C<do> features to use. 


C<$type> can be any of C<'jokers'>, C<'sql'>, C<'commas'>, C<'brackets'>, C<'win32'> or C<'unix'>. An unknown value defaults to C<'unix'>, except for C<'dos'>, C<'os2'>, C<'MSWin32'> and C<'cygwin'> that default to C<'win32'>. With this set of options, you can pass C<$^O> as the C<$type> so that you get the corresponding shell behaviour.

=over 4

=item C<>

For the C<$capture> syntax, refer to the L</capture> method.

=head3 C<type>

=head3 C<capture>

=over 4

=head2 C<$CaptureSingle>

When this variable is true, each occurence of unescaped I<"exactly one"> wildcards (i.e. C<?> jokers or C<_> for SQL wildcards) are made capturing in the resulting regexp (they are be replaced by C<(.)>). Otherwise, they are just replaced by C<.>. Default is the latter.

    For jokers :
    'a???b\\??' is translated to 'a(.)(.)(.)b\\?(.)' if $CaptureSingle is true
                                 'a...b\\?.'         otherwise (default)

    For SQL wildcards :
    'a___b\\__' is translated to 'a(.)(.)(.)b\\_(.)' if $CaptureSingle is true
                                 'a...b\\_.'         otherwise (default)


=item C<any>

By default this variable is false, and successions of unescaped I<"any"> wildcards (i.e. C<*> jokers or C<%> for SQL wildcards) are replaced by B<one> single C<.*>. When it evalutes to true, those sequences of I<"any"> wildcards are made into B<one> capture, which is greedy (C<(.*)>) for C<$CaptureAny E<gt> 0> and otherwise non-greedy (C<(.*?)>).

    For jokers :
    'a***b\\**' is translated to 'a.*b\\*.*'       if $CaptureAny is false (default)
                                 'a(.*)b\\*(.*)'   if $CaptureAny > 0
                                 'a(.*?)b\\*(.*?)' otherwise

    For SQL wildcards :
    'a%%%b\\%%' is translated to 'a.*b\\%.*'       if $CaptureAny is false (default)
                                 'a(.*)b\\%(.*)'   if $CaptureAny > 0
                                 'a(.*?)b\\%(.*?)' otherwise

=item C<brackets>

If this variable is set to true, valid brackets constructs are made into C<( | )> captures, and otherwise they are replaced by non-capturing alternations (C<(?: | >)), which is the default.

    'a{b\\},\\{c}' is translated to 'a(b\\}|\\{c)'   if $CaptureBrackets is true
                                    'a(?:b\\}|\\{c)' otherwise (default)

=back

=head2 C<jokers>

This function takes as its only argument the wildcard string to process, and returns the corresponding regular expression where the jokers C<?> (I<"exactly one">) and C<*> (I<"any">) have been translated into their regexp equivalents (see L</VARIABLES> for more details). All other unprotected regexp metacharacters are escaped.

    # Everything is escaped.
    print 'ok' if wc2re_jokers('{a{b,c}d,e}') eq '\\{a\\{b\\,c\\}d\\,e\\}';

=cut

=head2 C<sql>

Similar to the precedent, but for the SQL wildcards C<_> (I<"exactly one">) and C<%> (I<"any">). All other unprotected regexp metacharacters are escaped.
 
=cut
  
=head2 C<shell>

This function conforms to standard Unix shell wildcard rules. It successively escapes all unprotected regexp special characters that doesn't hold any meaning for wildcards, turns C<?> and C<*> jokers into their regexp equivalents (see L</wc2re_jokers>), and changes bracketed blocks into (possibly capturing) alternations as described in L</VARIABLES>. If brackets are unbalanced, it tries to substitute as many of them as possible, and then escape the remaining C<{> and C<}>. Commas outside of any bracket-delimited block are also escaped.

    # This is a valid bracket expression, and is completely translated.
    print 'ok' if wc2re_unix('{a{b,c}d,e}') eq '(?:a(?:b|c)d|e)';

The function handles unbalanced bracket expressions, by escaping everything it can't recognize. For example :

    # The first comma is replaced, and the remaining brackets and comma are escaped.
    print 'ok' if wc2re_unix('{a\\{b,c}d,e}') eq '(?:a\\{b|c)d\\,e\\}';

    # All the brackets and commas are escaped.
    print 'ok' if wc2re_unix('{a{b,c\\}d,e}') eq '\\{a\\{b\\,c\\}d\\,e\\}';

This one works just like the one before, but for Windows wildcards. Bracketed blocks are no longer handled (which means that brackets are escaped), but you can provide a comma-separated list of items.

    # All the brackets are escaped, and commas are seen as list delimiters.
    print 'ok' if wc2re_win32('{a{b,c}d,e}') eq '(?:\\{a\\{b|c\\}d|e\\})';

=cut

=head2 C<convert>

A generic function that wraps around all the different rules. The first argument is the wildcard expression, and the second one is the type of rules to apply which can be :

=over 4

=item C<'unix'>, C<'win32'>, C<'jokers'>, C<'sql'>

For one of those raw rule names, C<wc2re> simply maps to C<wc2re_unix>, C<wc2re_win32>, C<wc2re_jokers> and C<wc2re_sql> respectively.

=item C<$^O>

If you supply the Perl operating system name, the call is deferred to C<wc2re_win32> for C< $^O> equal to C<'dos'>, C<'os2'>, C<'MSWin32'> or C<'cygwin'>, and to C<wc2re_unix> in all the other cases.

=back

If the type is undefined or not supported, it defaults to C<'unix'>.

     # Wraps to wc2re_jokers ($re eq 'a\\{b\\,c\\}.*').
     $re = wc2re 'a{b,c}*' => 'jokers';

     # Wraps to wc2re_win32 ($re eq '(?:a\\{b|c\\}.*)')
     #       or wc2re_unix  ($re eq 'a(?:b|c).*')       depending on $^O.
     $re = wc2re 'a{b,c}*' => $^O;

=cut

sub convert {
 my ($self, $wc, $type) = @_;
 _check_self $self;
 my $config;
 if (defined $type) {
  $config = $self->_type($type);
 } else {
  $config = $self;
 }
 return unless defined $wc;
 my $do = $config->{do};
 my $e  = $config->{escape};
 $wc =~ s/(?<!\\)((?:\\\\)*[^\w\s\\$e])/\\$1/g;
 return $self->_sql($wc)   if $do->{sql};
 $wc = $self->_jokers($wc) if $do->{jokers};
 if ($do->{brackets}) {
  $wc = $self->_bracketed($wc);
 } elsif ($do->{commas}) {
  if ($wc =~ /(?<!\\)(?:\\\\)*,/) { # win32 allows comma-separated lists
   $wc = $self->{'c_brackets'} . $self->_commas($wc) . ')';
  }
 }
 return $wc;
}

=head1 EXPORT

An object module shouldn't export any function, and so does this one.

=head1 DEPENDENCIES

L<Text::Balanced>, which is bundled with perl since version 5.7.3

=head1 CAVEATS

This module does not implement the strange behaviours of Windows shell that result from the special handling of the three last characters (for the file extension). For example, Windows XP shell matches C<*a> like C<.*a>, C<*a?> like C<.*a.?>, C<*a??> like C<.*a.{0,2}> and so on.

=head1 SEE ALSO

Some modules provide incomplete alternatives as helper functions :

L<Net::FTPServer> has a method for that. Only jokers are translated, and escaping won't preserve them.

L<File::Find::Match::Util> has a C<wildcard> function that compiles a matcher. It only handles C<*>.

L<Text::Buffer> has the C<convertWildcardToRegex> class method that handles jokers.

=head1 AUTHOR

Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.

You can contact me by mail or on #perl @ FreeNode (vincent or Prof_Vince).

=head1 BUGS

Please report any bugs or feature requests to C<bug-regexp-wildcards at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Regexp-Wildcards>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc Regexp::Wildcards

Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Regexp-Wildcards>.

=head1 COPYRIGHT & LICENSE

Copyright 2007-2008 Vincent Pit, all rights reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

=cut

sub _extract ($) { extract_bracketed $_[0], '{',  qr/.*?(?<!\\)(?:\\\\)*(?={)/ }

sub _jokers {
 my $self = shift;
 local $_ = $_[0];
 # escape an odd number of \ that doesn't protect a regexp/wildcard special char
 s/(?<!\\)((?:\\\\)*\\(?:[\w\s]|$))/\\$1/g;
 # substitute ? preceded by an even number of \
 my $s = $self->{c_single};
 s/(?<!\\)((?:\\\\)*)\?/$1$s/g;
 # substitute * preceded by an even number of \
 $s = $self->{c_any};
 s/(?<!\\)((?:\\\\)*)\*+/$1$s/g;
 return $_;
}

sub _sql {
 my $self = shift;
 local $_ = $_[0];
 # escape an odd number of \ that doesn't protect a regexp/wildcard special char
 s/(?<!\\)((?:\\\\)*\\(?:[^\W_]|\s|$))/\\$1/g;
 # substitute _ preceded by an even number of \
 my $s = $self->{c_single};
 s/(?<!\\)((?:\\\\)*)_/$1$s/g;
 # substitute % preceded by an even number of \
 $s = $self->{c_any};
 s/(?<!\\)((?:\\\\)*)%+/$1$s/g;
 return $_;
}

sub _commas {
 local $_ = $_[1];
 # substitute , preceded by an even number of \
 s/(?<!\\)((?:\\\\)*),/$1|/g;
 return $_;
}

sub _brackets {
 my ($self, $rest) = @_;
 substr $rest, 0, 1, '';
 chop $rest;
 my ($re, $bracket, $prefix) = ('');
 while (do { ($bracket, $rest, $prefix) = _extract $rest; $bracket }) {
  $re .= $self->_commas($prefix) . $self->_brackets($bracket);
 }
 $re .= $self->_commas($rest);
 return $self->{c_brackets} . $re . ')';
}

sub _bracketed {
 my ($self, $rest) = @_;
 my ($re, $bracket, $prefix) = ('');
 while (do { ($bracket, $rest, $prefix) = _extract $rest; $bracket }) {
  $re .= $prefix . $self->_brackets($bracket);
 }
 $re .= $rest;
 $re =~ s/(?<!\\)((?:\\\\)*[\{\},])/\\$1/g;
 return $re;
}

1; # End of Regexp::Wildcards
