paths.nim 10 KB

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