tos.nim 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. discard """
  2. output: '''
  3. All:
  4. __really_obscure_dir_name/are.x
  5. __really_obscure_dir_name/created
  6. __really_obscure_dir_name/dirs
  7. __really_obscure_dir_name/files.q
  8. __really_obscure_dir_name/some
  9. __really_obscure_dir_name/test
  10. __really_obscure_dir_name/testing.r
  11. __really_obscure_dir_name/these.txt
  12. Files:
  13. __really_obscure_dir_name/are.x
  14. __really_obscure_dir_name/files.q
  15. __really_obscure_dir_name/testing.r
  16. __really_obscure_dir_name/these.txt
  17. Dirs:
  18. __really_obscure_dir_name/created
  19. __really_obscure_dir_name/dirs
  20. __really_obscure_dir_name/some
  21. __really_obscure_dir_name/test
  22. Raises
  23. Raises
  24. '''
  25. matrix: "--mm:refc; --mm:orc"
  26. joinable: false
  27. """
  28. # test os path creation, iteration, and deletion
  29. import os, strutils, pathnorm
  30. from stdtest/specialpaths import buildDir
  31. import std/[syncio, assertions]
  32. block fileOperations:
  33. let files = @["these.txt", "are.x", "testing.r", "files.q"]
  34. let dirs = @["some", "created", "test", "dirs"]
  35. let dname = "__really_obscure_dir_name"
  36. createDir(dname)
  37. doAssert dirExists(dname)
  38. block: # copyFile, copyFileToDir
  39. doAssertRaises(OSError): copyFile(dname/"nonexistent.txt", dname/"nonexistent.txt")
  40. let fname = "D20201009T112235"
  41. let fname2 = "D20201009T112235.2"
  42. let str = "foo1\0foo2\nfoo3\0"
  43. let file = dname/fname
  44. let file2 = dname/fname2
  45. writeFile(file, str)
  46. doAssert readFile(file) == str
  47. let sub = "sub"
  48. doAssertRaises(OSError): copyFile(file, dname/sub/fname2)
  49. doAssertRaises(OSError): copyFileToDir(file, dname/sub)
  50. doAssertRaises(ValueError): copyFileToDir(file, "")
  51. copyFile(file, file2)
  52. doAssert fileExists(file2)
  53. doAssert readFile(file2) == str
  54. createDir(dname/sub)
  55. copyFileToDir(file, dname/sub)
  56. doAssert fileExists(dname/sub/fname)
  57. removeDir(dname/sub)
  58. doAssert not dirExists(dname/sub)
  59. removeFile(file)
  60. removeFile(file2)
  61. # Test creating files and dirs
  62. for dir in dirs:
  63. createDir(dname/dir)
  64. doAssert dirExists(dname/dir)
  65. for file in files:
  66. let fh = open(dname/file, fmReadWrite)
  67. fh.close()
  68. doAssert fileExists(dname/file)
  69. echo "All:"
  70. template norm(x): untyped =
  71. (when defined(windows): x.replace('\\', '/') else: x)
  72. for path in walkPattern(dname/"*"):
  73. echo path.norm
  74. echo "Files:"
  75. for path in walkFiles(dname/"*"):
  76. echo path.norm
  77. echo "Dirs:"
  78. for path in walkDirs(dname/"*"):
  79. echo path.norm
  80. # Test removal of files dirs
  81. for dir in dirs:
  82. removeDir(dname/dir)
  83. doAssert: not dirExists(dname/dir)
  84. for file in files:
  85. removeFile(dname/file)
  86. doAssert: not fileExists(dname/file)
  87. removeDir(dname)
  88. doAssert: not dirExists(dname)
  89. # createDir should create recursive directories
  90. createDir(dirs[0] / dirs[1])
  91. doAssert dirExists(dirs[0] / dirs[1]) # true
  92. removeDir(dirs[0])
  93. # createDir should properly handle trailing separator
  94. createDir(dname / "")
  95. doAssert dirExists(dname) # true
  96. removeDir(dname)
  97. # createDir should raise IOError if the path exists
  98. # and is not a directory
  99. open(dname, fmWrite).close
  100. try:
  101. createDir(dname)
  102. except IOError:
  103. echo "Raises"
  104. removeFile(dname)
  105. # removeFile should not remove directory
  106. createDir(dname)
  107. try:
  108. removeFile(dname)
  109. except OSError:
  110. echo "Raises"
  111. removeDir(dname)
  112. # test copyDir:
  113. createDir("a/b")
  114. open("a/b/file.txt", fmWrite).close
  115. createDir("a/b/c")
  116. open("a/b/c/fileC.txt", fmWrite).close
  117. copyDir("a", "../dest/a")
  118. removeDir("a")
  119. doAssert dirExists("../dest/a/b")
  120. doAssert fileExists("../dest/a/b/file.txt")
  121. doAssert fileExists("../dest/a/b/c/fileC.txt")
  122. removeDir("../dest")
  123. # test copyDir:
  124. # if separator at the end of a path
  125. createDir("a/b")
  126. open("a/file.txt", fmWrite).close
  127. copyDir("a/", "../dest/a/")
  128. removeDir("a")
  129. doAssert dirExists("../dest/a/b")
  130. doAssert fileExists("../dest/a/file.txt")
  131. removeDir("../dest")
  132. # createDir should not fail if `dir` is empty
  133. createDir("")
  134. # Symlink handling in `copyFile`, `copyFileWithPermissions`, `copyFileToDir`,
  135. # `copyDir`, `copyDirWithPermissions`, `moveFile`, and `moveDir`.
  136. block:
  137. const symlinksAreHandled = not defined(windows)
  138. const dname = buildDir/"D20210116T140629"
  139. const subDir = dname/"sub"
  140. const subDir2 = dname/"sub2"
  141. const brokenSymlinkName = "D20210101T191320_BROKEN_SYMLINK"
  142. const brokenSymlink = dname/brokenSymlinkName
  143. const brokenSymlinkSrc = "D20210101T191320_nonexistent"
  144. const brokenSymlinkCopy = brokenSymlink & "_COPY"
  145. const brokenSymlinkInSubDir = subDir/brokenSymlinkName
  146. const brokenSymlinkInSubDir2 = subDir2/brokenSymlinkName
  147. createDir(subDir)
  148. createSymlink(brokenSymlinkSrc, brokenSymlink)
  149. # Test copyFile
  150. when symlinksAreHandled:
  151. doAssertRaises(OSError):
  152. copyFile(brokenSymlink, brokenSymlinkCopy)
  153. doAssertRaises(OSError):
  154. copyFile(brokenSymlink, brokenSymlinkCopy, {cfSymlinkFollow})
  155. copyFile(brokenSymlink, brokenSymlinkCopy, {cfSymlinkIgnore})
  156. doAssert not fileExists(brokenSymlinkCopy)
  157. copyFile(brokenSymlink, brokenSymlinkCopy, {cfSymlinkAsIs})
  158. when symlinksAreHandled:
  159. doAssert expandSymlink(brokenSymlinkCopy) == brokenSymlinkSrc
  160. removeFile(brokenSymlinkCopy)
  161. else:
  162. doAssert not fileExists(brokenSymlinkCopy)
  163. doAssertRaises(AssertionDefect):
  164. copyFile(brokenSymlink, brokenSymlinkCopy,
  165. {cfSymlinkAsIs, cfSymlinkFollow})
  166. # Test copyFileWithPermissions
  167. when symlinksAreHandled:
  168. doAssertRaises(OSError):
  169. copyFileWithPermissions(brokenSymlink, brokenSymlinkCopy)
  170. doAssertRaises(OSError):
  171. copyFileWithPermissions(brokenSymlink, brokenSymlinkCopy,
  172. options = {cfSymlinkFollow})
  173. copyFileWithPermissions(brokenSymlink, brokenSymlinkCopy,
  174. options = {cfSymlinkIgnore})
  175. doAssert not fileExists(brokenSymlinkCopy)
  176. copyFileWithPermissions(brokenSymlink, brokenSymlinkCopy,
  177. options = {cfSymlinkAsIs})
  178. when symlinksAreHandled:
  179. doAssert expandSymlink(brokenSymlinkCopy) == brokenSymlinkSrc
  180. removeFile(brokenSymlinkCopy)
  181. else:
  182. doAssert not fileExists(brokenSymlinkCopy)
  183. doAssertRaises(AssertionDefect):
  184. copyFileWithPermissions(brokenSymlink, brokenSymlinkCopy,
  185. options = {cfSymlinkAsIs, cfSymlinkFollow})
  186. # Test copyFileToDir
  187. when symlinksAreHandled:
  188. doAssertRaises(OSError):
  189. copyFileToDir(brokenSymlink, subDir)
  190. doAssertRaises(OSError):
  191. copyFileToDir(brokenSymlink, subDir, {cfSymlinkFollow})
  192. copyFileToDir(brokenSymlink, subDir, {cfSymlinkIgnore})
  193. doAssert not fileExists(brokenSymlinkInSubDir)
  194. copyFileToDir(brokenSymlink, subDir, {cfSymlinkAsIs})
  195. when symlinksAreHandled:
  196. doAssert expandSymlink(brokenSymlinkInSubDir) == brokenSymlinkSrc
  197. removeFile(brokenSymlinkInSubDir)
  198. else:
  199. doAssert not fileExists(brokenSymlinkInSubDir)
  200. createSymlink(brokenSymlinkSrc, brokenSymlinkInSubDir)
  201. # Test copyDir
  202. copyDir(subDir, subDir2)
  203. when symlinksAreHandled:
  204. doAssert expandSymlink(brokenSymlinkInSubDir2) == brokenSymlinkSrc
  205. else:
  206. doAssert not fileExists(brokenSymlinkInSubDir2)
  207. removeDir(subDir2)
  208. # Test copyDirWithPermissions
  209. copyDirWithPermissions(subDir, subDir2)
  210. when symlinksAreHandled:
  211. doAssert expandSymlink(brokenSymlinkInSubDir2) == brokenSymlinkSrc
  212. else:
  213. doAssert not fileExists(brokenSymlinkInSubDir2)
  214. removeDir(subDir2)
  215. # Test moveFile
  216. moveFile(brokenSymlink, brokenSymlinkCopy)
  217. when not defined(windows):
  218. doAssert expandSymlink(brokenSymlinkCopy) == brokenSymlinkSrc
  219. else:
  220. doAssert symlinkExists(brokenSymlinkCopy)
  221. removeFile(brokenSymlinkCopy)
  222. # Test moveDir
  223. moveDir(subDir, subDir2)
  224. when not defined(windows):
  225. doAssert expandSymlink(brokenSymlinkInSubDir2) == brokenSymlinkSrc
  226. else:
  227. doAssert symlinkExists(brokenSymlinkInSubDir2)
  228. removeDir(dname)
  229. block: # moveFile
  230. let tempDir = getTempDir() / "D20210609T151608"
  231. createDir(tempDir)
  232. defer: removeDir(tempDir)
  233. writeFile(tempDir / "a.txt", "")
  234. moveFile(tempDir / "a.txt", tempDir / "b.txt")
  235. doAssert not fileExists(tempDir / "a.txt")
  236. doAssert fileExists(tempDir / "b.txt")
  237. removeFile(tempDir / "b.txt")
  238. createDir(tempDir / "moveFile_test")
  239. writeFile(tempDir / "moveFile_test/a.txt", "")
  240. moveFile(tempDir / "moveFile_test/a.txt", tempDir / "moveFile_test/b.txt")
  241. doAssert not fileExists(tempDir / "moveFile_test/a.txt")
  242. doAssert fileExists(tempDir / "moveFile_test/b.txt")
  243. removeDir(tempDir / "moveFile_test")
  244. createDir(tempDir / "moveFile_test")
  245. writeFile(tempDir / "a.txt", "")
  246. moveFile(tempDir / "a.txt", tempDir / "moveFile_test/b.txt")
  247. doAssert not fileExists(tempDir / "a.txt")
  248. doAssert fileExists(tempDir / "moveFile_test/b.txt")
  249. removeDir(tempDir / "moveFile_test")
  250. block: # moveDir
  251. let tempDir = getTempDir() / "D20210609T161443"
  252. createDir(tempDir)
  253. defer: removeDir(tempDir)
  254. createDir(tempDir / "moveDir_test")
  255. moveDir(tempDir / "moveDir_test/", tempDir / "moveDir_test_dest")
  256. doAssert not dirExists(tempDir / "moveDir_test")
  257. doAssert dirExists(tempDir / "moveDir_test_dest")
  258. removeDir(tempDir / "moveDir_test_dest")
  259. createDir(tempDir / "moveDir_test")
  260. writeFile(tempDir / "moveDir_test/a.txt", "")
  261. moveDir(tempDir / "moveDir_test", tempDir / "moveDir_test_dest")
  262. doAssert not dirExists(tempDir / "moveDir_test")
  263. doAssert not fileExists(tempDir / "moveDir_test/a.txt")
  264. doAssert dirExists(tempDir / "moveDir_test_dest")
  265. doAssert fileExists(tempDir / "moveDir_test_dest/a.txt")
  266. removeDir(tempDir / "moveDir_test_dest")
  267. import times
  268. block modificationTime:
  269. # Test get/set modification times
  270. # Should support at least microsecond resolution
  271. let tm = fromUnix(0) + 100.microseconds
  272. writeFile("a", "")
  273. setLastModificationTime("a", tm)
  274. when defined(macosx):
  275. doAssert true
  276. else:
  277. doAssert getLastModificationTime("a") == tm
  278. removeFile("a")
  279. block walkDirRec:
  280. createDir("walkdir_test/a/b")
  281. open("walkdir_test/a/b/file_1", fmWrite).close()
  282. open("walkdir_test/a/file_2", fmWrite).close()
  283. for p in walkDirRec("walkdir_test"):
  284. doAssert p.fileExists
  285. doAssert p.startsWith("walkdir_test")
  286. var s: seq[string]
  287. for p in walkDirRec("walkdir_test", {pcFile}, {pcDir}, relative = true):
  288. s.add(p)
  289. doAssert s.len == 2
  290. doAssert "a" / "b" / "file_1" in s
  291. doAssert "a" / "file_2" in s
  292. removeDir("walkdir_test")
  293. import std/sequtils
  294. block: # walkDir
  295. doAssertRaises(OSError):
  296. for a in walkDir("nonexistent", checkDir = true): discard
  297. doAssertRaises(OSError):
  298. for p in walkDirRec("nonexistent", checkDir = true): discard
  299. when not defined(windows):
  300. block walkDirRelative:
  301. createDir("walkdir_test")
  302. createSymlink(".", "walkdir_test/c")
  303. for k, p in walkDir("walkdir_test", true):
  304. doAssert k == pcLinkToDir
  305. removeDir("walkdir_test")
  306. when defined(posix):
  307. block walkDirSpecial:
  308. createDir("walkdir_test")
  309. doAssert execShellCmd("mkfifo walkdir_test/fifo") == 0
  310. createSymlink("fifo", "walkdir_test/fifo_link")
  311. let withSpecialFiles = toSeq(walkDir("walkdir_test", relative = true))
  312. doAssert (withSpecialFiles.len == 2 and
  313. (pcFile, "fifo") in withSpecialFiles and
  314. (pcLinkToFile, "fifo_link") in withSpecialFiles)
  315. # now Unix special files are excluded from walkdir output:
  316. let skipSpecialFiles = toSeq(walkDir("walkdir_test", relative = true,
  317. skipSpecial = true))
  318. doAssert skipSpecialFiles.len == 0
  319. removeDir("walkdir_test")
  320. block normalizedPath:
  321. doAssert normalizedPath("") == ""
  322. block relative:
  323. doAssert normalizedPath(".") == "."
  324. doAssert normalizedPath("foo/..") == "."
  325. doAssert normalizedPath("foo//../bar/.") == "bar"
  326. doAssert normalizedPath("..") == ".."
  327. doAssert normalizedPath("../") == ".."
  328. doAssert normalizedPath("../..") == unixToNativePath"../.."
  329. doAssert normalizedPath("../a/..") == ".."
  330. doAssert normalizedPath("../a/../") == ".."
  331. doAssert normalizedPath("./") == "."
  332. block absolute:
  333. doAssert normalizedPath("/") == unixToNativePath"/"
  334. doAssert normalizedPath("/.") == unixToNativePath"/"
  335. doAssert normalizedPath("/..") == unixToNativePath"/.."
  336. doAssert normalizedPath("/../") == unixToNativePath"/.."
  337. doAssert normalizedPath("/../..") == unixToNativePath"/../.."
  338. doAssert normalizedPath("/../../") == unixToNativePath"/../.."
  339. doAssert normalizedPath("/../../../") == unixToNativePath"/../../.."
  340. doAssert normalizedPath("/a/b/../../foo") == unixToNativePath"/foo"
  341. doAssert normalizedPath("/a/b/../../../foo") == unixToNativePath"/../foo"
  342. doAssert normalizedPath("/./") == unixToNativePath"/"
  343. doAssert normalizedPath("//") == unixToNativePath"/"
  344. doAssert normalizedPath("///") == unixToNativePath"/"
  345. doAssert normalizedPath("/a//b") == unixToNativePath"/a/b"
  346. doAssert normalizedPath("/a///b") == unixToNativePath"/a/b"
  347. doAssert normalizedPath("/a/b/c/..") == unixToNativePath"/a/b"
  348. doAssert normalizedPath("/a/b/c/../") == unixToNativePath"/a/b"
  349. block isHidden:
  350. when defined(posix):
  351. doAssert ".foo.txt".isHidden
  352. doAssert "bar/.foo.ext".isHidden
  353. doAssert not "bar".isHidden
  354. doAssert not "foo/".isHidden
  355. doAssert ".foo/.".isHidden
  356. # Corner cases: `isHidden` is not yet `..` aware
  357. doAssert not ".foo/..".isHidden
  358. block absolutePath:
  359. doAssertRaises(ValueError): discard absolutePath("a", "b")
  360. doAssert absolutePath("a") == getCurrentDir() / "a"
  361. doAssert absolutePath("a", "/b") == "/b" / "a"
  362. when defined(posix):
  363. doAssert absolutePath("a", "/b/") == "/b" / "a"
  364. doAssert absolutePath("a", "/b/c") == "/b/c" / "a"
  365. doAssert absolutePath("/a", "b/") == "/a"
  366. block splitFile:
  367. doAssert splitFile("") == ("", "", "")
  368. doAssert splitFile("abc/") == ("abc", "", "")
  369. doAssert splitFile("/") == ("/", "", "")
  370. doAssert splitFile("./abc") == (".", "abc", "")
  371. doAssert splitFile(".txt") == ("", ".txt", "")
  372. doAssert splitFile("abc/.txt") == ("abc", ".txt", "")
  373. doAssert splitFile("abc") == ("", "abc", "")
  374. doAssert splitFile("abc.txt") == ("", "abc", ".txt")
  375. doAssert splitFile("/abc.txt") == ("/", "abc", ".txt")
  376. doAssert splitFile("/foo/abc.txt") == ("/foo", "abc", ".txt")
  377. doAssert splitFile("/foo/abc.txt.gz") == ("/foo", "abc.txt", ".gz")
  378. doAssert splitFile(".") == ("", ".", "")
  379. doAssert splitFile("abc/.") == ("abc", ".", "")
  380. doAssert splitFile("..") == ("", "..", "")
  381. doAssert splitFile("a/..") == ("a", "..", "")
  382. doAssert splitFile("/foo/abc....txt") == ("/foo", "abc...", ".txt")
  383. # execShellCmd is tested in tosproc
  384. block ospaths:
  385. doAssert unixToNativePath("") == ""
  386. doAssert unixToNativePath(".") == $CurDir
  387. doAssert unixToNativePath("..") == $ParDir
  388. doAssert isAbsolute(unixToNativePath("/"))
  389. doAssert isAbsolute(unixToNativePath("/", "a"))
  390. doAssert isAbsolute(unixToNativePath("/a"))
  391. doAssert isAbsolute(unixToNativePath("/a", "a"))
  392. doAssert isAbsolute(unixToNativePath("/a/b"))
  393. doAssert isAbsolute(unixToNativePath("/a/b", "a"))
  394. doAssert unixToNativePath("a/b") == joinPath("a", "b")
  395. when defined(macos):
  396. doAssert unixToNativePath("./") == ":"
  397. doAssert unixToNativePath("./abc") == ":abc"
  398. doAssert unixToNativePath("../abc") == "::abc"
  399. doAssert unixToNativePath("../../abc") == ":::abc"
  400. doAssert unixToNativePath("/abc", "a") == "abc"
  401. doAssert unixToNativePath("/abc/def", "a") == "abc:def"
  402. elif doslikeFileSystem:
  403. doAssert unixToNativePath("./") == ".\\"
  404. doAssert unixToNativePath("./abc") == ".\\abc"
  405. doAssert unixToNativePath("../abc") == "..\\abc"
  406. doAssert unixToNativePath("../../abc") == "..\\..\\abc"
  407. doAssert unixToNativePath("/abc", "a") == "a:\\abc"
  408. doAssert unixToNativePath("/abc/def", "a") == "a:\\abc\\def"
  409. else:
  410. #Tests for unix
  411. doAssert unixToNativePath("./") == "./"
  412. doAssert unixToNativePath("./abc") == "./abc"
  413. doAssert unixToNativePath("../abc") == "../abc"
  414. doAssert unixToNativePath("../../abc") == "../../abc"
  415. doAssert unixToNativePath("/abc", "a") == "/abc"
  416. doAssert unixToNativePath("/abc/def", "a") == "/abc/def"
  417. block extractFilenameTest:
  418. doAssert extractFilename("") == ""
  419. when defined(posix):
  420. doAssert extractFilename("foo/bar") == "bar"
  421. doAssert extractFilename("foo/bar.txt") == "bar.txt"
  422. doAssert extractFilename("foo/") == ""
  423. doAssert extractFilename("/") == ""
  424. when doslikeFileSystem:
  425. doAssert extractFilename(r"foo\bar") == "bar"
  426. doAssert extractFilename(r"foo\bar.txt") == "bar.txt"
  427. doAssert extractFilename(r"foo\") == ""
  428. doAssert extractFilename(r"C:\") == ""
  429. block lastPathPartTest:
  430. doAssert lastPathPart("") == ""
  431. when defined(posix):
  432. doAssert lastPathPart("foo/bar.txt") == "bar.txt"
  433. doAssert lastPathPart("foo/") == "foo"
  434. doAssert lastPathPart("/") == ""
  435. when doslikeFileSystem:
  436. doAssert lastPathPart(r"foo\bar.txt") == "bar.txt"
  437. doAssert lastPathPart(r"foo\") == "foo"
  438. template canon(x): untyped = normalizePath(x, '/')
  439. doAssert canon"/foo/../bar" == "/bar"
  440. doAssert canon"foo/../bar" == "bar"
  441. doAssert canon"/f/../bar///" == "/bar"
  442. doAssert canon"f/..////bar" == "bar"
  443. doAssert canon"../bar" == "../bar"
  444. doAssert canon"/../bar" == "/../bar"
  445. doAssert canon("foo/../../bar/") == "../bar"
  446. doAssert canon("./bla/blob/") == "bla/blob"
  447. doAssert canon(".hiddenFile") == ".hiddenFile"
  448. doAssert canon("./bla/../../blob/./zoo.nim") == "../blob/zoo.nim"
  449. doAssert canon("C:/file/to/this/long") == "C:/file/to/this/long"
  450. doAssert canon("") == ""
  451. doAssert canon("foobar") == "foobar"
  452. doAssert canon("f/////////") == "f"
  453. doAssert relativePath("/foo/bar//baz.nim", "/foo", '/') == "bar/baz.nim"
  454. doAssert normalizePath("./foo//bar/../baz", '/') == "foo/baz"
  455. doAssert relativePath("/Users/me/bar/z.nim", "/Users/other/bad", '/') == "../../me/bar/z.nim"
  456. doAssert relativePath("/Users/me/bar/z.nim", "/Users/other", '/') == "../me/bar/z.nim"
  457. # `//` is a UNC path, `/` is the current working directory's drive, so can't
  458. # run this test on Windows.
  459. when not doslikeFileSystem:
  460. doAssert relativePath("/Users///me/bar//z.nim", "//Users/", '/') == "me/bar/z.nim"
  461. doAssert relativePath("/Users/me/bar/z.nim", "/Users/me", '/') == "bar/z.nim"
  462. doAssert relativePath("", "/users/moo", '/') == ""
  463. doAssert relativePath("foo", "", '/') == "foo"
  464. doAssert relativePath("/foo", "/Foo", '/') == (when FileSystemCaseSensitive: "../foo" else: ".")
  465. doAssert relativePath("/Foo", "/foo", '/') == (when FileSystemCaseSensitive: "../Foo" else: ".")
  466. doAssert relativePath("/foo", "/fOO", '/') == (when FileSystemCaseSensitive: "../foo" else: ".")
  467. doAssert relativePath("/foO", "/foo", '/') == (when FileSystemCaseSensitive: "../foO" else: ".")
  468. doAssert relativePath("foo", ".", '/') == "foo"
  469. doAssert relativePath(".", ".", '/') == "."
  470. doAssert relativePath("..", ".", '/') == ".."
  471. doAssert relativePath("foo", "foo") == "."
  472. doAssert relativePath("", "foo") == ""
  473. doAssert relativePath("././/foo", "foo//./") == "."
  474. doAssert relativePath(getCurrentDir() / "bar", "foo") == "../bar".unixToNativePath
  475. doAssert relativePath("bar", getCurrentDir() / "foo") == "../bar".unixToNativePath
  476. when doslikeFileSystem:
  477. doAssert relativePath(r"c:\foo.nim", r"C:\") == r"foo.nim"
  478. doAssert relativePath(r"c:\foo\bar\baz.nim", r"c:\foo") == r"bar\baz.nim"
  479. doAssert relativePath(r"c:\foo\bar\baz.nim", r"d:\foo") == r"c:\foo\bar\baz.nim"
  480. doAssert relativePath(r"\foo\baz.nim", r"\foo") == r"baz.nim"
  481. doAssert relativePath(r"\foo\bar\baz.nim", r"\bar") == r"..\foo\bar\baz.nim"
  482. doAssert relativePath(r"\\foo\bar\baz.nim", r"\\foo\bar") == r"baz.nim"
  483. doAssert relativePath(r"\\foo\bar\baz.nim", r"\\foO\bar") == r"baz.nim"
  484. doAssert relativePath(r"\\foo\bar\baz.nim", r"\\bar\bar") == r"\\foo\bar\baz.nim"
  485. doAssert relativePath(r"\\foo\bar\baz.nim", r"\\foo\car") == r"\\foo\bar\baz.nim"
  486. doAssert relativePath(r"\\foo\bar\baz.nim", r"\\goo\bar") == r"\\foo\bar\baz.nim"
  487. doAssert relativePath(r"\\foo\bar\baz.nim", r"c:\") == r"\\foo\bar\baz.nim"
  488. doAssert relativePath(r"\\foo\bar\baz.nim", r"\foo") == r"\\foo\bar\baz.nim"
  489. doAssert relativePath(r"c:\foo.nim", r"\foo") == r"c:\foo.nim"
  490. doAssert joinPath("usr", "") == unixToNativePath"usr"
  491. doAssert joinPath("", "lib") == "lib"
  492. doAssert joinPath("", "/lib") == unixToNativePath"/lib"
  493. doAssert joinPath("usr/", "/lib") == unixToNativePath"usr/lib"
  494. doAssert joinPath("", "") == unixToNativePath"" # issue #13455
  495. doAssert joinPath("", "/") == unixToNativePath"/"
  496. doAssert joinPath("/", "/") == unixToNativePath"/"
  497. doAssert joinPath("/", "") == unixToNativePath"/"
  498. doAssert joinPath("/" / "") == unixToNativePath"/" # weird test case...
  499. doAssert joinPath("/", "/a/b/c") == unixToNativePath"/a/b/c"
  500. doAssert joinPath("foo/", "") == unixToNativePath"foo/"
  501. doAssert joinPath("foo/", "abc") == unixToNativePath"foo/abc"
  502. doAssert joinPath("foo//./", "abc/.//") == unixToNativePath"foo/abc/"
  503. doAssert joinPath("foo", "abc") == unixToNativePath"foo/abc"
  504. doAssert joinPath("", "abc") == unixToNativePath"abc"
  505. doAssert joinPath("zook/.", "abc") == unixToNativePath"zook/abc"
  506. # controversial: inconsistent with `joinPath("zook/.","abc")`
  507. # on linux, `./foo` and `foo` are treated a bit differently for executables
  508. # but not `./foo/bar` and `foo/bar`
  509. doAssert joinPath(".", "/lib") == unixToNativePath"./lib"
  510. doAssert joinPath(".", "abc") == unixToNativePath"./abc"
  511. # cases related to issue #13455
  512. doAssert joinPath("foo", "", "") == "foo"
  513. doAssert joinPath("foo", "") == "foo"
  514. doAssert joinPath("foo/", "") == unixToNativePath"foo/"
  515. doAssert joinPath("foo/", ".") == "foo"
  516. doAssert joinPath("foo", "./") == unixToNativePath"foo/"
  517. doAssert joinPath("foo", "", "bar/") == unixToNativePath"foo/bar/"
  518. # issue #13579
  519. doAssert joinPath("/foo", "../a") == unixToNativePath"/a"
  520. doAssert joinPath("/foo/", "../a") == unixToNativePath"/a"
  521. doAssert joinPath("/foo/.", "../a") == unixToNativePath"/a"
  522. doAssert joinPath("/foo/.b", "../a") == unixToNativePath"/foo/a"
  523. doAssert joinPath("/foo///", "..//a/") == unixToNativePath"/a/"
  524. doAssert joinPath("foo/", "../a") == unixToNativePath"a"
  525. when doslikeFileSystem:
  526. doAssert joinPath("C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\Tools\\", "..\\..\\VC\\vcvarsall.bat") == r"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat"
  527. doAssert joinPath("C:\\foo", "..\\a") == r"C:\a"
  528. doAssert joinPath("C:\\foo\\", "..\\a") == r"C:\a"
  529. block getTempDir:
  530. block TMPDIR:
  531. # TMPDIR env var is not used if either of these are defined.
  532. when not (defined(tempDir) or defined(windows) or defined(android)):
  533. if existsEnv("TMPDIR"):
  534. let origTmpDir = getEnv("TMPDIR")
  535. putEnv("TMPDIR", "/mytmp")
  536. doAssert getTempDir() == "/mytmp/"
  537. delEnv("TMPDIR")
  538. doAssert getTempDir() == "/tmp/"
  539. putEnv("TMPDIR", origTmpDir)
  540. else:
  541. doAssert getTempDir() == "/tmp/"
  542. block: # getCacheDir
  543. doAssert getCacheDir().dirExists
  544. block isRelativeTo:
  545. doAssert isRelativeTo("/foo", "/")
  546. doAssert isRelativeTo("/foo/bar", "/foo")
  547. doAssert isRelativeTo("foo/bar", "foo")
  548. doAssert isRelativeTo("/foo/bar.nim", "/foo/bar.nim")
  549. doAssert isRelativeTo("./foo/", "foo")
  550. doAssert isRelativeTo("foo", "./foo/")
  551. doAssert isRelativeTo(".", ".")
  552. doAssert isRelativeTo("foo/bar", ".")
  553. doAssert not isRelativeTo("foo/bar.nims", "foo/bar.nim")
  554. doAssert not isRelativeTo("/foo2", "/foo")
  555. block: # quoteShellWindows
  556. doAssert quoteShellWindows("aaa") == "aaa"
  557. doAssert quoteShellWindows("aaa\"") == "aaa\\\""
  558. doAssert quoteShellWindows("") == "\"\""
  559. block: # quoteShellCommand
  560. when defined(windows):
  561. doAssert quoteShellCommand(["a b c", "d", "e"]) == """"a b c" d e"""
  562. doAssert quoteShellCommand(["""ab"c""", r"\", "d"]) == """ab\"c \ d"""
  563. doAssert quoteShellCommand(["""ab"c""", """ \""", "d"]) == """ab\"c " \\" d"""
  564. doAssert quoteShellCommand(["""a\\\b""", """de fg""", "h"]) == """a\\\b "de fg" h"""
  565. doAssert quoteShellCommand(["""a\"b""", "c", "d"]) == """a\\\"b c d"""
  566. doAssert quoteShellCommand(["""a\\b c""", "d", "e"]) == """"a\\b c" d e"""
  567. doAssert quoteShellCommand(["""a\\b\ c""", "d", "e"]) == """"a\\b\ c" d e"""
  568. doAssert quoteShellCommand(["ab", ""]) == """ab """""
  569. block: # quoteShellPosix
  570. doAssert quoteShellPosix("aaa") == "aaa"
  571. doAssert quoteShellPosix("aaa a") == "'aaa a'"
  572. doAssert quoteShellPosix("") == "''"
  573. doAssert quoteShellPosix("a'a") == "'a'\"'\"'a'"
  574. block: # quoteShell
  575. when defined(posix):
  576. doAssert quoteShell("") == "''"
  577. block: # normalizePathEnd
  578. # handle edge cases correctly: shouldn't affect whether path is
  579. # absolute/relative
  580. doAssert "".normalizePathEnd(true) == ""
  581. doAssert "".normalizePathEnd(false) == ""
  582. doAssert "/".normalizePathEnd(true) == $DirSep
  583. doAssert "/".normalizePathEnd(false) == $DirSep
  584. when defined(posix):
  585. doAssert "//".normalizePathEnd(false) == "/"
  586. doAssert "foo.bar//".normalizePathEnd == "foo.bar"
  587. doAssert "bar//".normalizePathEnd(trailingSep = true) == "bar/"
  588. when defined(windows):
  589. doAssert r"C:\foo\\".normalizePathEnd == r"C:\foo"
  590. doAssert r"C:\foo".normalizePathEnd(trailingSep = true) == r"C:\foo\"
  591. # this one is controversial: we could argue for returning `D:\` instead,
  592. # but this is simplest.
  593. doAssert r"D:\".normalizePathEnd == r"D:"
  594. doAssert r"E:/".normalizePathEnd(trailingSep = true) == r"E:\"
  595. doAssert "/".normalizePathEnd == r"\"
  596. import sugar
  597. block: # normalizeExe
  598. doAssert "".dup(normalizeExe) == ""
  599. when defined(posix):
  600. doAssert "foo".dup(normalizeExe) == "./foo"
  601. doAssert "foo/../bar".dup(normalizeExe) == "foo/../bar"
  602. when defined(windows):
  603. doAssert "foo".dup(normalizeExe) == "foo"
  604. block: # isAdmin
  605. let isAzure = existsEnv("TF_BUILD") # xxx factor with testament.specs.isAzure
  606. # In Azure on Windows tests run as an admin user
  607. if isAzure and defined(windows): doAssert isAdmin()
  608. # In Azure on POSIX tests run as a normal user
  609. if isAzure and defined(posix): doAssert not isAdmin()
  610. import sugar
  611. block: # normalizeExe
  612. doAssert "".dup(normalizeExe) == ""
  613. when defined(posix):
  614. doAssert "foo".dup(normalizeExe) == "./foo"
  615. doAssert "foo/../bar".dup(normalizeExe) == "foo/../bar"
  616. when defined(windows):
  617. doAssert "foo".dup(normalizeExe) == "foo"
  618. block: # isAdmin
  619. let isAzure = existsEnv("TF_BUILD") # xxx factor with testament.specs.isAzure
  620. # In Azure on Windows tests run as an admin user
  621. if isAzure and defined(windows): doAssert isAdmin()
  622. # In Azure on POSIX tests run as a normal user
  623. if isAzure and defined(posix): doAssert not isAdmin()
  624. when doslikeFileSystem:
  625. import std/private/ntpath
  626. block: # Bug #19103 UNC paths
  627. # Easiest way of generating a valid, readable and writable UNC path
  628. let tempDir = r"\\?\" & getTempDir()
  629. doAssert dirExists tempDir
  630. createDir tempDir / "test"
  631. removeDir tempDir / "test"
  632. createDir tempDir / "recursive" / "test"
  633. removeDir tempDir / "recursive" / "test"
  634. let tempDir2 = getTempDir()
  635. let (drive, pathNoDrive) = splitDrive(tempDir2)
  636. setCurrentDir drive
  637. doAssert cmpIgnoreCase(getCurrentDir().splitDrive.drive, drive) == 0
  638. # Test `\Users` path syntax on Windows by stripping away drive. `\`
  639. # resolves to the drive in current working directory. This drive will be
  640. # the same as `tempDir2` because of the `setCurrentDir` above.
  641. doAssert pathNoDrive[0] == '\\'
  642. createDir pathNoDrive / "test"
  643. doAssert dirExists pathNoDrive / "test"
  644. removeDir pathNoDrive / "test"
  645. doAssert splitPath("//?/c:") == ("//?/c:", "")
  646. doAssert relativePath("//?/c:///Users//me", "//?/c:", '/') == "Users/me"
  647. doAssert parentDir(r"\\?\c:") == r""
  648. doAssert parentDir(r"//?/c:/Users") == r"\\?\c:"
  649. doAssert parentDir(r"\\localhost\c$") == r""
  650. doAssert parentDir(r"\Users") == r"\"
  651. doAssert tailDir("//?/c:") == ""
  652. doAssert tailDir("//?/c:/Users") == "Users"
  653. doAssert tailDir(r"\\localhost\c$\Windows\System32") == r"Windows\System32"
  654. doAssert isRootDir("//?/c:")
  655. doAssert isRootDir("//?/UNC/localhost/c$")
  656. doAssert not isRootDir(r"\\?\c:\Users")
  657. doAssert parentDirs(r"C:\Users", fromRoot = true).toSeq == @[r"C:\", r"C:\Users"]
  658. doAssert parentDirs(r"C:\Users", fromRoot = false).toSeq == @[r"C:\Users", r"C:"]
  659. doAssert parentDirs(r"\\?\c:\Users", fromRoot = true).toSeq ==
  660. @[r"\\?\c:\", r"\\?\c:\Users"]
  661. doAssert parentDirs(r"\\?\c:\Users", fromRoot = false).toSeq ==
  662. @[r"\\?\c:\Users", r"\\?\c:"]
  663. doAssert parentDirs(r"//localhost/c$/Users", fromRoot = true).toSeq ==
  664. @[r"//localhost/c$/", r"//localhost/c$/Users"]
  665. doAssert parentDirs(r"//?/UNC/localhost/c$/Users", fromRoot = false).toSeq ==
  666. @[r"//?/UNC/localhost/c$/Users", r"\\?\UNC\localhost\c$"]
  667. doAssert parentDirs(r"\Users", fromRoot = true).toSeq == @[r"\", r"\Users"]
  668. doAssert parentDirs(r"\Users", fromRoot = false).toSeq == @[r"\Users", r"\"]
  669. doAssert r"//?/c:" /../ "d/e" == r"\\?\c:\d\e"
  670. doAssert r"//?/c:/Users" /../ "d/e" == r"\\?\c:\d\e"
  671. doAssert r"\\localhost\c$" /../ "d/e" == r"\\localhost\c$\d\e"
  672. doAssert splitFile("//?/c:") == ("//?/c:", "", "")
  673. doAssert splitFile("//?/c:/Users") == ("//?/c:", "Users", "")
  674. doAssert splitFile(r"\\localhost\c$\test.txt") == (r"\\localhost\c$", "test", ".txt")
  675. else:
  676. block: # parentDirs
  677. doAssert parentDirs("/home", fromRoot=true).toSeq == @["/", "/home"]
  678. doAssert parentDirs("/home", fromRoot=false).toSeq == @["/home", "/"]
  679. doAssert parentDirs("home", fromRoot=true).toSeq == @["home"]
  680. doAssert parentDirs("home", fromRoot=false).toSeq == @["home"]
  681. doAssert parentDirs("/home/user", fromRoot=true).toSeq == @["/", "/home/", "/home/user"]
  682. doAssert parentDirs("/home/user", fromRoot=false).toSeq == @["/home/user", "/home", "/"]
  683. doAssert parentDirs("home/user", fromRoot=true).toSeq == @["home/", "home/user"]
  684. doAssert parentDirs("home/user", fromRoot=false).toSeq == @["home/user", "home"]
  685. # https://github.com/nim-lang/Nim/pull/19643#issuecomment-1235102314
  686. block: # isValidFilename
  687. # Negative Tests.
  688. doAssert not isValidFilename("abcd", maxLen = 2)
  689. doAssert not isValidFilename("0123456789", maxLen = 8)
  690. doAssert not isValidFilename("con")
  691. doAssert not isValidFilename("aux")
  692. doAssert not isValidFilename("prn")
  693. doAssert not isValidFilename("OwO|UwU")
  694. doAssert not isValidFilename(" foo")
  695. doAssert not isValidFilename("foo ")
  696. doAssert not isValidFilename("foo.")
  697. doAssert not isValidFilename("con.txt")
  698. doAssert not isValidFilename("aux.bat")
  699. doAssert not isValidFilename("prn.exe")
  700. doAssert not isValidFilename("nim>.nim")
  701. doAssert not isValidFilename(" foo.log")
  702. # Positive Tests.
  703. doAssert isValidFilename("abcd", maxLen = 42.Positive)
  704. doAssert isValidFilename("c0n")
  705. doAssert isValidFilename("foo.aux")
  706. doAssert isValidFilename("bar.prn")
  707. doAssert isValidFilename("OwO_UwU")
  708. doAssert isValidFilename("cron")
  709. doAssert isValidFilename("ux.bat")
  710. doAssert isValidFilename("nim.nim")
  711. doAssert isValidFilename("foo.log")
  712. block: # searchExtPos
  713. doAssert "foo.nim".searchExtPos == 3
  714. doAssert "/foo.nim".searchExtPos == 4
  715. doAssert "".searchExtPos == -1
  716. doAssert "/".searchExtPos == -1
  717. doAssert "a.b/foo".searchExtPos == -1
  718. doAssert ".".searchExtPos == -1
  719. doAssert "foo.".searchExtPos == 3
  720. doAssert "foo..".searchExtPos == 4
  721. doAssert "..".searchExtPos == -1
  722. doAssert "...".searchExtPos == -1
  723. doAssert "./".searchExtPos == -1
  724. doAssert "../".searchExtPos == -1
  725. doAssert "/.".searchExtPos == -1
  726. doAssert "/..".searchExtPos == -1
  727. doAssert ".b".searchExtPos == -1
  728. doAssert "..b".searchExtPos == -1
  729. doAssert "/.b".searchExtPos == -1
  730. doAssert "a/.b".searchExtPos == -1
  731. doAssert ".a.b".searchExtPos == 2
  732. doAssert "a/.b.c".searchExtPos == 4
  733. doAssert "a/..b".searchExtPos == -1
  734. doAssert "a/b..c".searchExtPos == 4
  735. when doslikeFileSystem:
  736. doAssert "c:a.b".searchExtPos == 3
  737. doAssert "c:.a".searchExtPos == -1
  738. doAssert r"c:\.a".searchExtPos == -1
  739. doAssert "c:..a".searchExtPos == -1
  740. doAssert r"c:\..a".searchExtPos == -1
  741. doAssert "c:.a.b".searchExtPos == 4