globs.nim 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. ##[
  2. unstable API, internal use only for now.
  3. this can eventually be moved to std/os and `walkDirRec` can be implemented in terms of this
  4. to avoid duplication
  5. ]##
  6. import std/[os]
  7. when defined(windows):
  8. from strutils import replace
  9. type
  10. PathEntry* = object
  11. kind*: PathComponent
  12. path*: string
  13. iterator walkDirRecFilter*(dir: string, follow: proc(entry: PathEntry): bool = nil,
  14. relative = false, checkDir = true): PathEntry {.tags: [ReadDirEffect].} =
  15. ## Improved `os.walkDirRec`.
  16. #[
  17. note: a yieldFilter isn't needed because caller can filter at call site, without
  18. loss of generality, unlike `follow`.
  19. Future work:
  20. * need to document
  21. * add a `sort` option, which can be implemented efficiently only here, not at call site.
  22. * provide a way to do error reporting, which is tricky because iteration cannot be resumed
  23. ]#
  24. var stack = @["."]
  25. var checkDir = checkDir
  26. var entry: PathEntry
  27. while stack.len > 0:
  28. let d = stack.pop()
  29. for k, p in walkDir(dir / d, relative = true, checkDir = checkDir):
  30. let rel = d / p
  31. entry.kind = k
  32. if relative: entry.path = rel
  33. else: entry.path = dir / rel
  34. if k in {pcDir, pcLinkToDir}:
  35. if follow == nil or follow(entry): stack.add rel
  36. yield entry
  37. checkDir = false
  38. # We only check top-level dir, otherwise if a subdir is invalid (eg. wrong
  39. # permissions), it'll abort iteration and there would be no way to
  40. # continue iteration.
  41. proc nativeToUnixPath*(path: string): string =
  42. # pending https://github.com/nim-lang/Nim/pull/13265
  43. doAssert not path.isAbsolute # not implemented here; absolute files need more care for the drive
  44. when DirSep == '\\':
  45. result = replace(path, '\\', '/')
  46. else: result = path
  47. when isMainModule:
  48. import sugar
  49. for a in walkDirRecFilter(".", follow = a=>a.path.lastPathPart notin ["nimcache", ".git", ".csources", "bin"]):
  50. echo a