ossymlinks.nim 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. include system/inclrtl
  2. import std/oserrors
  3. import oscommon
  4. export symlinkExists
  5. when defined(nimPreviewSlimSystem):
  6. import std/[syncio, assertions, widestrs]
  7. when weirdTarget:
  8. discard
  9. elif defined(windows):
  10. import std/[winlean, times]
  11. elif defined(posix):
  12. import std/posix
  13. else:
  14. {.error: "OS module not ported to your operating system!".}
  15. when weirdTarget:
  16. {.pragma: noWeirdTarget, error: "this proc is not available on the NimScript/js target".}
  17. else:
  18. {.pragma: noWeirdTarget.}
  19. when defined(nimscript):
  20. # for procs already defined in scriptconfig.nim
  21. template noNimJs(body): untyped = discard
  22. elif defined(js):
  23. {.pragma: noNimJs, error: "this proc is not available on the js target".}
  24. else:
  25. {.pragma: noNimJs.}
  26. ## .. importdoc:: os.nim
  27. proc createSymlink*(src, dest: string) {.noWeirdTarget.} =
  28. ## Create a symbolic link at `dest` which points to the item specified
  29. ## by `src`. On most operating systems, will fail if a link already exists.
  30. ##
  31. ## .. warning:: Some OS's (such as Microsoft Windows) restrict the creation
  32. ## of symlinks to root users (administrators) or users with developer mode enabled.
  33. ##
  34. ## See also:
  35. ## * `createHardlink proc`_
  36. ## * `expandSymlink proc`_
  37. when defined(windows):
  38. const SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE = 2
  39. # allows anyone with developer mode on to create a link
  40. let flag = dirExists(src).int32 or SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
  41. var wSrc = newWideCString(src)
  42. var wDst = newWideCString(dest)
  43. if createSymbolicLinkW(wDst, wSrc, flag) == 0 or getLastError() != 0:
  44. raiseOSError(osLastError(), $(src, dest))
  45. else:
  46. if symlink(src, dest) != 0:
  47. raiseOSError(osLastError(), $(src, dest))
  48. proc expandSymlink*(symlinkPath: string): string {.noWeirdTarget.} =
  49. ## Returns a string representing the path to which the symbolic link points.
  50. ##
  51. ## On Windows this is a noop, `symlinkPath` is simply returned.
  52. ##
  53. ## See also:
  54. ## * `createSymlink proc`_
  55. when defined(windows) or defined(nintendoswitch):
  56. result = symlinkPath
  57. else:
  58. var bufLen = 1024
  59. while true:
  60. result = newString(bufLen)
  61. let len = readlink(symlinkPath.cstring, result.cstring, bufLen)
  62. if len < 0:
  63. raiseOSError(osLastError(), symlinkPath)
  64. if len < bufLen:
  65. result.setLen(len)
  66. break
  67. bufLen = bufLen shl 1