packagehandling.nim 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2017 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. iterator myParentDirs(p: string): string =
  10. # XXX os's parentDirs is stupid (multiple yields) and triggers an old bug...
  11. var current = p
  12. while true:
  13. current = current.parentDir
  14. if current.len == 0: break
  15. yield current
  16. template newPackageCache(): untyped =
  17. newStringTable(when FileSystemCaseSensitive:
  18. modeCaseInsensitive
  19. else:
  20. modeCaseSensitive)
  21. var packageCache = newPackageCache()
  22. proc resetPackageCache*() = packageCache = newPackageCache()
  23. proc getPackageName*(path: string): string =
  24. var parents = 0
  25. block packageSearch:
  26. for d in myParentDirs(path):
  27. if packageCache.hasKey(d):
  28. #echo "from cache ", d, " |", packageCache[d], "|", path.splitFile.name
  29. return packageCache[d]
  30. inc parents
  31. for file in walkFiles(d / "*.nimble"):
  32. result = file.splitFile.name
  33. break packageSearch
  34. for file in walkFiles(d / "*.babel"):
  35. result = file.splitFile.name
  36. break packageSearch
  37. # we also store if we didn't find anything:
  38. if result.isNil: result = ""
  39. for d in myParentDirs(path):
  40. #echo "set cache ", d, " |", result, "|", parents
  41. packageCache[d] = result
  42. dec parents
  43. if parents <= 0: break
  44. proc withPackageName*(path: string): string =
  45. let x = path.getPackageName
  46. if x.len == 0:
  47. result = path
  48. else:
  49. let (p, file, ext) = path.splitFile
  50. result = (p / (x & '_' & file)) & ext