Skip to content

Commit

Permalink
fix(walk): handle leading shallow magic correctly (#30)
Browse files Browse the repository at this point in the history
Closes #29

```
foo/a.txt
bar/a.txt
baz/a.txt
```

```nim
import glob
import sequtils

echo toSeq(walkGlob("*/a.txt"))
# -> @["foo/a.txt", "bar/a.txt", "baz/a.txt"]
```
  • Loading branch information
haltcase committed Aug 2, 2018
1 parent 589671a commit 1fa54df
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 4 deletions.
34 changes: 30 additions & 4 deletions src/glob.nim
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,23 @@ func matches* (input, pattern: string; isDos = isDosDefault, ignoreCase = isDosD

input.contains(globToRegex(pattern, isDos, ignoreCase))

proc shouldDescend (
subdir, resultPath, matchPattern: string;
isRec, ignoreCase: bool,
entry: GlobEntry,
filter: FilterDescend
): bool =
if isRec or (not filter.isNil and filter(resultPath)):
return true

let tail = entry.path.toRelative(subdir)
let head = matchPattern.splitPath.head

if head == tail: return true

let subPattern = head.globToRegex(ignoreCase = ignoreCase)
if subPattern in tail: return true

func toOutputPath (
path, root, internalRoot: string;
pattern: string | Glob,
Expand Down Expand Up @@ -455,8 +472,8 @@ iterator walkGlobKinds* (

let matcher = matchPattern.globToRegex(ignoreCase = IgnoreCase in options)
let isRec = "**" in matchPattern

var stack = toSeq(initStack(dir, {pcDir, pcLinkToDir}, IgnoreCase in options))

var last = dir
while stack.len > 0:
let (subdir, _) = stack.pop
Expand All @@ -479,14 +496,23 @@ iterator walkGlobKinds* (
continue

last = subdir

if isRec and (filterDescend.isNil or filterDescend(resultPath)):
if shouldDescend(
subdir, resultPath, matchPattern,
isRec, IgnoreCase in options,
(path, kind),
filterDescend
):
stack.add((path, kind))
of pcDir:
if Directories in options and isMatch:
push(resultPath, kind)

if isRec and (filterDescend.isNil or filterDescend(resultPath)):
if shouldDescend(
subdir, resultPath, matchPattern,
isRec, IgnoreCase in options,
(path, kind),
filterDescend
):
stack.add((path, kind))
of pcLinkToFile:
if FileLinks in options and isMatch:
Expand Down
15 changes: 15 additions & 0 deletions tests.nim
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,21 @@ suite "pattern walking / listing":
p"temp/shallow.nim"
])

test "leading magic":
let clean = createStructure("temp_leading_magic", @[
p"foo/a.txt",
p"bar/a.txt",
p"baz/a.txt"
])

check seqsEqual(toSeq(walkGlob("*/a.txt", "temp_leading_magic")), @[
p"foo/a.txt",
p"bar/a.txt",
p"baz/a.txt"
])

clean()

check seqsEqual(toSeq(walkGlob("temp/**/*.{nim,jpg}")), @[
p"temp/deep/dir/file.nim",
p"temp/not_as/deep.jpg",
Expand Down

0 comments on commit 1fa54df

Please sign in to comment.