paths.nim 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. import std/private/osseps
  2. export osseps
  3. import std/envvars
  4. import std/private/osappdirs
  5. import pathnorm
  6. from std/private/ospaths2 import joinPath, splitPath,
  7. ReadDirEffect, WriteDirEffect,
  8. isAbsolute, relativePath,
  9. normalizePathEnd, isRelativeTo, parentDir,
  10. tailDir, isRootDir, parentDirs, `/../`,
  11. extractFilename, lastPathPart,
  12. changeFileExt, addFileExt, cmpPaths, splitFile,
  13. unixToNativePath, absolutePath, normalizeExe,
  14. normalizePath
  15. export ReadDirEffect, WriteDirEffect
  16. type
  17. Path* = distinct string
  18. func `==`*(x, y: Path): bool {.inline.} =
  19. ## Compares two paths.
  20. ##
  21. ## On a case-sensitive filesystem this is done
  22. ## case-sensitively otherwise case-insensitively.
  23. result = cmpPaths(x.string, y.string) == 0
  24. template endsWith(a: string, b: set[char]): bool =
  25. a.len > 0 and a[^1] in b
  26. func add(x: var string, tail: string) =
  27. var state = 0
  28. let trailingSep = tail.endsWith({DirSep, AltSep}) or tail.len == 0 and x.endsWith({DirSep, AltSep})
  29. normalizePathEnd(x, trailingSep=false)
  30. addNormalizePath(tail, x, state, DirSep)
  31. normalizePathEnd(x, trailingSep=trailingSep)
  32. func add*(x: var Path, y: Path) {.borrow.}
  33. func `/`*(head, tail: Path): Path {.inline.} =
  34. ## Joins two directory names to one.
  35. ##
  36. ## returns normalized path concatenation of `head` and `tail`, preserving
  37. ## whether or not `tail` has a trailing slash (or, if tail if empty, whether
  38. ## head has one).
  39. ##
  40. ## See also:
  41. ## * `splitPath proc`_
  42. ## * `uri.combine proc <uri.html#combine,Uri,Uri>`_
  43. ## * `uri./ proc <uri.html#/,Uri,string>`_
  44. Path(joinPath(head.string, tail.string))
  45. func splitPath*(path: Path): tuple[head, tail: Path] {.inline.} =
  46. ## Splits a directory into `(head, tail)` tuple, so that
  47. ## ``head / tail == path`` (except for edge cases like "/usr").
  48. ##
  49. ## See also:
  50. ## * `add proc`_
  51. ## * `/ proc`_
  52. ## * `/../ proc`_
  53. ## * `relativePath proc`_
  54. let res = splitPath(path.string)
  55. result = (Path(res.head), Path(res.tail))
  56. func splitFile*(path: Path): tuple[dir, name: Path, ext: string] {.inline.} =
  57. ## Splits a filename into `(dir, name, extension)` tuple.
  58. ##
  59. ## `dir` does not end in DirSep unless it's `/`.
  60. ## `extension` includes the leading dot.
  61. ##
  62. ## If `path` has no extension, `ext` is the empty string.
  63. ## If `path` has no directory component, `dir` is the empty string.
  64. ## If `path` has no filename component, `name` and `ext` are empty strings.
  65. ##
  66. ## See also:
  67. ## * `extractFilename proc`_
  68. ## * `lastPathPart proc`_
  69. ## * `changeFileExt proc`_
  70. ## * `addFileExt proc`_
  71. let res = splitFile(path.string)
  72. result = (Path(res.dir), Path(res.name), res.ext)
  73. func isAbsolute*(path: Path): bool {.inline, raises: [].} =
  74. ## Checks whether a given `path` is absolute.
  75. ##
  76. ## On Windows, network paths are considered absolute too.
  77. result = isAbsolute(path.string)
  78. proc relativePath*(path, base: Path, sep = DirSep): Path {.inline.} =
  79. ## Converts `path` to a path relative to `base`.
  80. ##
  81. ## The `sep` (default: DirSep) is used for the path normalizations,
  82. ## this can be useful to ensure the relative path only contains `'/'`
  83. ## so that it can be used for URL constructions.
  84. ##
  85. ## On Windows, if a root of `path` and a root of `base` are different,
  86. ## returns `path` as is because it is impossible to make a relative path.
  87. ## That means an absolute path can be returned.
  88. ##
  89. ## See also:
  90. ## * `splitPath proc`_
  91. ## * `parentDir proc`_
  92. ## * `tailDir proc`_
  93. result = Path(relativePath(path.string, base.string, sep))
  94. proc isRelativeTo*(path: Path, base: Path): bool {.inline.} =
  95. ## Returns true if `path` is relative to `base`.
  96. result = isRelativeTo(path.string, base.string)
  97. func parentDir*(path: Path): Path {.inline.} =
  98. ## Returns the parent directory of `path`.
  99. ##
  100. ## This is similar to ``splitPath(path).head`` when ``path`` doesn't end
  101. ## in a dir separator, but also takes care of path normalizations.
  102. ## The remainder can be obtained with `lastPathPart(path) proc`_.
  103. ##
  104. ## See also:
  105. ## * `relativePath proc`_
  106. ## * `splitPath proc`_
  107. ## * `tailDir proc`_
  108. ## * `parentDirs iterator`_
  109. result = Path(parentDir(path.string))
  110. func tailDir*(path: Path): Path {.inline.} =
  111. ## Returns the tail part of `path`.
  112. ##
  113. ## See also:
  114. ## * `relativePath proc`_
  115. ## * `splitPath proc`_
  116. ## * `parentDir proc`_
  117. result = Path(tailDir(path.string))
  118. func isRootDir*(path: Path): bool {.inline.} =
  119. ## Checks whether a given `path` is a root directory.
  120. result = isRootDir(path.string)
  121. iterator parentDirs*(path: Path, fromRoot=false, inclusive=true): Path =
  122. ## Walks over all parent directories of a given `path`.
  123. ##
  124. ## If `fromRoot` is true (default: false), the traversal will start from
  125. ## the file system root directory.
  126. ## If `inclusive` is true (default), the original argument will be included
  127. ## in the traversal.
  128. ##
  129. ## Relative paths won't be expanded by this iterator. Instead, it will traverse
  130. ## only the directories appearing in the relative path.
  131. ##
  132. ## See also:
  133. ## * `parentDir proc`_
  134. ##
  135. for p in parentDirs(path.string, fromRoot, inclusive):
  136. yield Path(p)
  137. func `/../`*(head, tail: Path): Path {.inline.} =
  138. ## The same as ``parentDir(head) / tail``, unless there is no parent
  139. ## directory. Then ``head / tail`` is performed instead.
  140. ##
  141. ## See also:
  142. ## * `/ proc`_
  143. ## * `parentDir proc`_
  144. Path(`/../`(head.string, tail.string))
  145. func extractFilename*(path: Path): Path {.inline.} =
  146. ## Extracts the filename of a given `path`.
  147. ##
  148. ## This is the same as ``name & ext`` from `splitFile(path) proc`_.
  149. ##
  150. ## See also:
  151. ## * `splitFile proc`_
  152. ## * `lastPathPart proc`_
  153. ## * `changeFileExt proc`_
  154. ## * `addFileExt proc`_
  155. result = Path(extractFilename(path.string))
  156. func lastPathPart*(path: Path): Path {.inline.} =
  157. ## Like `extractFilename proc`_, but ignores
  158. ## trailing dir separator; aka: `baseName`:idx: in some other languages.
  159. ##
  160. ## See also:
  161. ## * `splitFile proc`_
  162. ## * `extractFilename proc`_
  163. ## * `changeFileExt proc`_
  164. ## * `addFileExt proc`_
  165. result = Path(lastPathPart(path.string))
  166. func changeFileExt*(filename: Path, ext: string): Path {.inline.} =
  167. ## Changes the file extension to `ext`.
  168. ##
  169. ## If the `filename` has no extension, `ext` will be added.
  170. ## If `ext` == "" then any extension is removed.
  171. ##
  172. ## `Ext` should be given without the leading `'.'`, because some
  173. ## filesystems may use a different character. (Although I know
  174. ## of none such beast.)
  175. ##
  176. ## See also:
  177. ## * `splitFile proc`_
  178. ## * `extractFilename proc`_
  179. ## * `lastPathPart proc`_
  180. ## * `addFileExt proc`_
  181. result = Path(changeFileExt(filename.string, ext))
  182. func addFileExt*(filename: Path, ext: string): Path {.inline.} =
  183. ## Adds the file extension `ext` to `filename`, unless
  184. ## `filename` already has an extension.
  185. ##
  186. ## `Ext` should be given without the leading `'.'`, because some
  187. ## filesystems may use a different character.
  188. ## (Although I know of none such beast.)
  189. ##
  190. ## See also:
  191. ## * `splitFile proc`_
  192. ## * `extractFilename proc`_
  193. ## * `lastPathPart proc`_
  194. ## * `changeFileExt proc`_
  195. result = Path(addFileExt(filename.string, ext))
  196. func unixToNativePath*(path: Path, drive=Path("")): Path {.inline.} =
  197. ## Converts an UNIX-like path to a native one.
  198. ##
  199. ## On an UNIX system this does nothing. Else it converts
  200. ## `'/'`, `'.'`, `'..'` to the appropriate things.
  201. ##
  202. ## On systems with a concept of "drives", `drive` is used to determine
  203. ## which drive label to use during absolute path conversion.
  204. ## `drive` defaults to the drive of the current working directory, and is
  205. ## ignored on systems that do not have a concept of "drives".
  206. result = Path(unixToNativePath(path.string, drive.string))
  207. proc getCurrentDir*(): Path {.inline, tags: [].} =
  208. ## Returns the `current working directory`:idx: i.e. where the built
  209. ## binary is run.
  210. ##
  211. ## So the path returned by this proc is determined at run time.
  212. ##
  213. ## See also:
  214. ## * `getHomeDir proc <appdirs.html#getHomeDir>`_
  215. ## * `getConfigDir proc <appdirs.html#getConfigDir>`_
  216. ## * `getTempDir proc <appdirs.html#getTempDir>`_
  217. ## * `setCurrentDir proc <dirs.html#setCurrentDir>`_
  218. ## * `currentSourcePath template <system.html#currentSourcePath.t>`_
  219. ## * `getProjectPath proc <macros.html#getProjectPath>`_
  220. result = Path(ospaths2.getCurrentDir())
  221. proc normalizeExe*(file: var Path) {.borrow.}
  222. proc normalizePath*(path: var Path) {.borrow.}
  223. proc normalizePathEnd*(path: var Path, trailingSep = false) {.borrow.}
  224. proc absolutePath*(path: Path, root = getCurrentDir()): Path =
  225. ## Returns the absolute path of `path`, rooted at `root` (which must be absolute;
  226. ## default: current directory).
  227. ## If `path` is absolute, return it, ignoring `root`.
  228. ##
  229. ## See also:
  230. ## * `normalizePath proc`_
  231. result = Path(absolutePath(path.string, root.string))
  232. proc expandTildeImpl(path: string): string {.
  233. tags: [ReadEnvEffect, ReadIOEffect].} =
  234. if len(path) == 0 or path[0] != '~':
  235. result = path
  236. elif len(path) == 1:
  237. result = getHomeDir()
  238. elif (path[1] in {DirSep, AltSep}):
  239. result = joinPath(getHomeDir(), path.substr(2))
  240. else:
  241. # TODO: handle `~bob` and `~bob/` which means home of bob
  242. result = path
  243. proc expandTilde*(path: Path): Path {.inline,
  244. tags: [ReadEnvEffect, ReadIOEffect].} =
  245. ## Expands ``~`` or a path starting with ``~/`` to a full path, replacing
  246. ## ``~`` with `getHomeDir() <appdirs.html#getHomeDir>`_ (otherwise returns ``path`` unmodified).
  247. ##
  248. ## Windows: this is still supported despite the Windows platform not having this
  249. ## convention; also, both ``~/`` and ``~\`` are handled.
  250. runnableExamples:
  251. import std/appdirs
  252. assert expandTilde(Path("~") / Path("appname.cfg")) == getHomeDir() / Path("appname.cfg")
  253. assert expandTilde(Path("~/foo/bar")) == getHomeDir() / Path("foo/bar")
  254. assert expandTilde(Path("/foo/bar")) == Path("/foo/bar")
  255. result = Path(expandTildeImpl(path.string))