paths.nim 10 KB

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