/
Glob.pm6
469 lines (352 loc) · 12.8 KB
/
Glob.pm6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use v6;
unit class IO::Glob:auth<github:zostay>:ver<0.6> does Iterable;
=NAME IO::Glob - Glob matching for paths & strings and listing files
=begin SYNOPSIS
use IO::Glob;
# Need a list of files somewhere?
for glob("src/core/*.pm") -> $file { say ~$file }
# Or apply the glob to a chosen directory
with glob("*.log") {
for .dir("/var/log/error") -> $err-log { ... }
for .dir("/var/log/access") -> $acc-log { ... }
}
# Use a glob to match a string or path
if "some-string" ~~ glob("some-*") { say "match string!" }
if "some/path.txt".IO ~~ glob("some/*.txt") { say "match path!" }
# Use a glob as a test in built-in IO::Path.dir()
for "/var/log".IO.dir(test => glob("*.err")) -> $err-log { ... }
# Globs are objects, which you can save, reuse, and pass around
my $file-match = glob("*.txt");
my @files := dir("$*HOME/docs", :test($file-match));
# Want to use SQL globbing with % and _ instead?
for glob("src/core/%.pm", :sql) -> $file { ... }
# Or want globbing without all the fancy bits?
# :simple turns off everything but * an ?
for glob("src/core/*.pm", :simple) -> $file { ... }
=end SYNOPSIS
=begin DESCRIPTION
Traditionally, globs provide a handy shorthand for identifying the files you're
interested in based upon their path. This class provides that shorthand using a
BSD-style glob grammar that is familiar to Perl devs. However, it is more
powerful than its Perl 5 predecessor.
=item Globs are built as IO::Glob objects which encapsulate the pattern. You may create them and pass them around.
=item By using them as an iterator, you can put globs to their traditional use: listing all the files in a directory.
=item Globs also work as smart-matches. It will match against strings or anything that stringifies and against L<IO::Path>s too.
=item Globbing can be done with different grammars. This class ships with three: simple, BSD, and SQL.
=item B<Experimental.> You can use custom grammars for your smart match.
=end DESCRIPTION
class Globber {
role Term { }
class Match does Term { has $.smart-match is rw }
class Expansion does Term { has @.alternatives }
has @.terms where { .elems > 0 && all($_) ~~ Term };
has @!matchers;
method !compile-terms-ind($base, @terms is copy) {
my $term = @terms.shift;
my @roots;
if $term ~~ Match {
my $match = $term.smart-match;
@roots = rx/$base$match/;
}
elsif $term ~~ Expansion {
my @alts = $term.alternatives;
@roots = @alts.map({ rx/$base$^alt/ });
}
else {
die "unknown match term: $term";
}
if @terms { @roots.map({ self!compile-terms-ind($^base, @terms).Slip }) }
else { @roots.Slip }
}
method is-ordered() returns Bool { any(@!terms) ~~ Expansion }
method !compile-terms() {
return if @!matchers;
@!matchers = self!compile-terms-ind(rx/<?>/, @.terms).map(-> $rx {rx/^$rx$/});
}
multi method ACCEPTS(Str:U $) returns Bool:D { False }
multi method ACCEPTS(Str:D $candidate) returns Bool:D {
self!compile-terms;
$candidate ~~ any(@!matchers);
}
method accepts-with-sort(*@candidates) {
self!compile-terms;
my @remaining = @candidates;
my @m = gather for @!matchers.kv -> $i, $matcher {
my @unused;
for @candidates -> $candidate {
if $candidate.basename ~~ $matcher {
take ($i, $candidate);
}
else {
push @unused, $candidate;
}
}
@remaining = @unused;
}
@m.sort({ $^a[0] <=> $^b[0] }).map({ .[1] });
}
}
# Unlike File::Glob in Perl 5, we don't make a bunch of options to turn off each
# kind of feature. Instead, we give callers the option to pick a grammar.
grammar Base {
token TOP {
<term>+
{ make $<term>».made }
}
token term {
|| <match>
{ make Globber::Match.new(:smart-match($<match>.made)) }
|| <expansion>
{ make Globber::Expansion.new(:alternatives($<expansion>.made)) }
|| <escape>
{ make Globber::Match.new(:smart-match($<escape>.made)) }
|| <char>
{ make Globber::Match.new(:smart-match($<char>.made)) }
}
proto token match {*}
proto token expansion { * }
proto token escape { * }
token char { $<char> = . { make $<char>.Str } }
}
grammar SQL is Base {
method whatever-match { '%' }
token match:sym<%> { <sym> { make rx/.*?/ } }
token match:sym<_> { <sym> { make rx/./ } }
}
grammar Simple is Base {
method whatever-match { '*' }
token match:sym<*> {
<!after "\\"> <sym>
{ make rx/.*?/ }
}
token match:sym<?> {
<!after "\\"> <sym>
{ make rx/./ }
}
token escape { "\\" <escape-sym> { make $<escape-sym>.Str } }
proto token escape-sym { * }
token escape-sym:sym<*> { <sym> }
token escape-sym:sym<?> { <sym> }
}
grammar BSD is Simple {
token TOP { <term>+ }
token match:character-class {
<!after "\\"> '['
$<not> = [ "!"? ]
$<class> = [ <-[ \] ]>+ ]
']'
{
my @class = $<class>.Str.comb;
make $<not> ?? rx{@class} !! rx{<!before @class> .}
}
}
token expansion:alternatives {
<!after "\\"> '{'
<list=.comma-list>
'}'
{ make my @list= ([~] $<list>).split(',') }
}
token comma-list {
[ <-[ , \} ]>+ ]+ % ','
}
token expansion:home-dir {
<!after "\\"> '~' $<user> = [ <-[/]>+ ]?
{ make $<user> ?? [ 'NYI' ]<> !! [ $*HOME ]<> }
}
token escape-sym:sym<[> { <sym> }
token escape-sym:sym<]> { <sym> }
token escape-sym:sym<{> { <sym> }
token escape-sym:sym<}> { <sym> }
token escape-sym:sym<~> { <sym> }
}
=begin pod
=head1 SUBROUTINES
=head2 sub glob
sub glob(
Str:D $pattern,
Bool :$sql,
Bool :$bsd,
Bool :$simple,
:$grammar,
:$spec = $*SPEC
) returns IO::Glob:D
sub glob(
Whatever $,
Bool :$sql,
Bool :$bsd,
Bool :$simple,
:$grammar,
:$spec = $*SPEC
) returns IO::Glob:D
When given a string, that string will be stored in the L<#method
pattern/pattern> attribute and will be parsed according to the L<#method
grammar/grammar>.
When given L<Whatever> (C<*>) as the argument, it's the same as:
glob('*');
which will match anything. (Note that what whatever matches may be grammar
specific, so C<glob(*, :sql)> is the same as C<glob('%')>.)
If you want to pick from one of the built-in grammars, you may use these options:
=item C<:bsd> is the default specifying this is explicit, but unnecessary. This grammar supports C<*>, C<?>, C<[abc]>, C<[!abc]>, C<~>, and C<{ab,cd,efg}>.
=item C<:sql> uses a SQL-ish grammar that provides C<%> and C<_> matching.
=item C<:simple> is a simplified version of C<:bsd>, but only supports C<*> and C<?>.
The C<:$spec> option allows you to specify the L<IO::Spec> to use when
matching paths. It uses C<$*SPEC>, by default. The IO::Spec is used to split
paths by directory separator when matching paths. (This is ignored when matching
against other kinds of objects.)
An alternative to this is to use the optional C<:$grammar> setting lets you
select a globbing grammar object to use. These are provided:
=item IO::Glob::BSD
=item IO::Glob::SQL
=item IO::Glob::Simple
B<Experimental.> If you want a different grammar, you may create your own as
well, but no documentation of that process has been written yet as of this
writing.
=head1 METHODS
=head2 method pattern
method pattern() returns Str:D
Returns the pattern set during construction.
=head2 method spec
method spec() returns IO::Spec:D
Returns the spec set during construction.
=head2 method grammar
method grammar() returns Any:D
Returns the grammar set during construction.
=end pod
has Str:D $.pattern is required;
has IO::Spec $.spec = $*SPEC;
has $.grammar = BSD.new;
has Globber $!globber;
has Globber @!globbers;
my sub simplify(@terms) {
my Globber::Match $prev;
my @result = gather for @terms {
when Globber::Match {
if .smart-match ~~ Str {
if $prev {
$prev.smart-match ~= .smart-match;
}
else {
$prev = $_;
}
}
else {
take $prev with $prev;
take $_;
$prev = Nil;
}
}
default {
take $prev with $prev;
take $_;
$prev = Nil;
}
}
push @result, $prev if $prev;
@result;
}
method !compile-glob() {
$!globber = Globber.new(
terms => simplify($!grammar.parse($!pattern)<term>.map({.made})),
);
}
method !compile-globs() {
my @parts = $.pattern.split($.spec.dir-sep);
@!globbers = @parts.map({
Globber.new(
terms => simplify($!grammar.parse($^pattern)<term>.map({.made})),
);
});
}
method iterator(IO::Glob:D:) { self.dir.iterator }
=begin pod
=head2 method dir
method dir(Cool $path = '.') returns Seq:D
Returns a list of files matching the glob. This will descend directories if the
pattern contains a L<IO::Spec#dir-sep> using a depth-first search. This method
is called implicitly when you use the object as an iterator. For example, these
two lines are identical:
for glob('*.*') -> $every-dos-file { ... }
for glob('*.*').dir -> $every-dos-file { ... }
This is the preferred method for listing files as it will be sure to respect ordering of files by alternates. For example,
for glob("{bc,ab}*") -> $file { say $file }
This will print all files starting with "bc" before any files starting with ab.
=end pod
method dir(Str() $path = '.') returns Seq:D {
self!compile-globs;
my $current = $path.IO;
return []<> unless $current.d;
my @globbers = @!globbers;
# Depth-first-search... commence!
my @open-list = \(:path($current), :@globbers, :origin);
gather while @open-list {
my (:$path, :@globbers, :$origin) := @open-list.shift;
if @globbers {
my ($globber, @remaining) = @globbers;
next unless $path ~~ :d;
next unless $origin || $path.basename ne '..' | '.';
my @paths = do if $globber.is-ordered {
$globber.accepts-with-sort($path.dir);
}
else {
$path.dir(test => $globber);
}
@open-list.prepend: @paths
.map({ \(:$^path, :globbers(@remaining)) })
}
else {
take $path;
}
}
}
=begin pod
=head2 method ACCEPTS
method ACCEPTS(Mu:U $) returns Bool:D
method ACCEPTS(Str:D(Any) $candiate) returns Bool:D
method ACCEPTS(IO::Path:D $path) returns Bool:D
This implements smart-match. Undefined values never match. Strings are matched
using the whole pattern, without reference to any directory separators in the
string. Paths, however, are matched and carefully respect directory separators.
For most circumstances, this will not make any difference. However, a case like
this will be treated very differently in each case:
my $glob = glob("hello{x,y/}world");
say "String" if "helloy/world" ~~ $glob; # outputs> String
say "Path" if "helloy/world".IO ~~ $glob; # outputs nothing, no match
say "Path 2" if "helloy{x,y/}world" ~~ $glob; # outputs> Path 2
The reason is that the second and third are matched in parts as follows:
"helloy" ~~ glob("hello{x,y") && "world" ~~ glob("}world")
"hello{x,y" ~~ glob("hello{x,y") && "}world" ~~ glob("}world")
=end pod
multi method ACCEPTS(Mu:U $) returns Bool:D { False }
multi method ACCEPTS(Str:D(Any) $candidate) returns Bool:D {
self!compile-glob;
$candidate ~~ $!globber
}
multi method ACCEPTS(IO::Path:D $path) returns Bool:D {
self!compile-globs;
my @parts = (~$path).split($.spec.dir-sep);
return False unless @parts.elems == @!globbers.elems;
[&&] (@parts Z @!globbers).flatmap: -> ($p, $g) { $p ~~ $g };
}
proto glob(|) is export { * }
multi sub glob(
Str:D $pattern,
Bool :$sql,
Bool :$bsd,
Bool :$simple,
:grammar($g),
:$spec = $*SPEC
) returns IO::Glob:D {
my $grammar = do with $g { $g } elsif $sql { SQL.new } elsif $simple { Simple.new } else { BSD.new };
IO::Glob.new(:$pattern, :$grammar, :$spec);
}
multi sub glob(
Whatever $,
Bool :$sql,
Bool :$bsd,
Bool :$simple,
:grammar($g),
:$spec = $*SPEC
) returns IO::Glob:D {
my $grammar = do with $g { $g } elsif $sql { SQL.new } elsif $simple { Simple.new } else { BSD.new };
IO::Glob.new(:pattern($grammar.whatever-match), :$grammar, :$spec);
}