Skip to content

Instantly share code, notes, and snippets.

@z-------------
Created January 28, 2023 12:34
Show Gist options
  • Save z-------------/dd9751ec3fd3382a25c7bce9f2b609ee to your computer and use it in GitHub Desktop.
Save z-------------/dd9751ec3fd3382a25c7bce9f2b609ee to your computer and use it in GitHub Desktop.
iterator walkDirRecEx*(dir: string; yieldFilter = {pcFile}; followFilter = {pcDir}; relative = false; checkDir = false; depth = -1): string {.raises: [OSError].} =
## Same as std/os.walkDirRec but with added `depth` parameter. `depth < 0`
## means no depth limit.
if depth != 0:
var stack = @[("", 1)]
var checkDir = checkDir
while stack.len > 0:
let (subDir, subDepth) = stack.pop()
for kind, path in walkDir(dir / subDir, relative = true, checkDir = checkDir):
let rel = subDir / path
if kind in {pcDir, pcLinkToDir} and kind in followFilter and (depth < 0 or subDepth + 1 <= depth):
stack.add (rel, subDepth + 1)
if kind in yieldFilter:
yield if relative: rel else: dir / rel
checkDir = false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment