1 ! Copyright (C) 2007, 2009 Slava Pestov, Daniel Ehrenberg.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays combinators combinators.short-circuit
4 io.directories io.files io.files.info io.pathnames kernel locals
5 make peg.ebnf regexp regexp.combinators sequences splitting
6 strings system unicode.case ;
9 : not-path-separator ( -- sep )
10 os windows? R! [^/\\]! R! [^/]! ? ; foldable
14 Character = "\\" .:c => [[ c 1string <literal> ]]
15 | !(","|"}") . => [[ 1string <literal> ]]
17 RangeCharacter = !("]") .
19 Range = RangeCharacter:a "-" RangeCharacter:b => [[ a b <char-range> ]]
20 | RangeCharacter => [[ 1string <literal> ]]
22 StartRange = .:a "-" RangeCharacter:b => [[ a b <char-range> ]]
23 | . => [[ 1string <literal> ]]
25 Ranges = StartRange:s Range*:r => [[ r s prefix ]]
27 CharClass = "^"?:n Ranges:e => [[ e <or> n [ <not> ] when ]]
29 AlternationBody = Concatenation:c "," AlternationBody:a => [[ a c prefix ]]
30 | Concatenation => [[ 1array ]]
32 Element = "*" => [[ not-path-separator <zero-or-more> ]]
33 | "?" => [[ not-path-separator ]]
34 | "[" CharClass:c "]" => [[ c ]]
35 | "{" AlternationBody:b "}" => [[ b <or> ]]
38 Concatenation = Element* => [[ <sequence> ]]
42 Main = Concatenation End
46 : glob-matches? ( input glob -- ? )
47 [ >case-fold ] bi@ <glob> matches? ;
49 : glob-pattern? ( string -- ? )
50 [ "\\*?[{" member? ] any? ;
54 DEFER: glob-directory%
56 : ?glob-directory% ( root remaining entry -- )
60 empty? [ , ] [ drop ] if
63 :: glob-wildcard% ( root globs -- )
64 globs ?second :> next-glob
65 next-glob dup pair? [ second ] [ drop f ] if :> next-glob-regexp
67 root directory-entries [| entry |
68 root entry name>> append-path
70 { [ next-glob not ] [ dup , ] }
71 { [ next-glob empty? ] [ entry directory? [ dup , ] when ] }
74 entry name>> >case-fold next-glob-regexp matches?
78 [ entry name>> next-glob = ]
94 { [ entry directory? ] [ next-glob ] } 0&& [
101 :: glob-pattern% ( root globs -- )
102 globs unclip second :> ( remaining glob )
104 root directory-entries [| entry |
105 entry name>> >case-fold glob matches? [
106 root entry name>> append-path
107 remaining entry ?glob-directory%
111 :: glob-literal% ( root globs -- )
112 globs unclip :> ( remaining glob )
114 root glob append-path dup exists? [
115 remaining over file-info ?glob-directory%
120 : glob-directory% ( root globs -- )
123 { "**" [ glob-wildcard% ] }
124 [ pair? [ glob-pattern% ] [ glob-literal% ] if ]
127 : split-glob ( glob -- path globs )
132 path-separator first over last-index
133 [ cut rest ] [ "" swap ] if*
137 : glob-path ( glob -- path globs )
139 dup { [ "**" = not ] [ glob-pattern? ] } 1&& [
140 dup >case-fold <glob> 2array
146 : glob-directory ( glob -- files )
147 glob-path [ glob-directory% ] { } make ;