tempfiles.nim 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2021 Nim contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module creates temporary files and directories.
  10. ##
  11. ## Experimental API, subject to change.
  12. #[
  13. See also:
  14. * `GetTempFileName` (on windows), refs https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettempfilenamea
  15. * `mkstemp` (posix), refs https://man7.org/linux/man-pages/man3/mkstemp.3.html
  16. ]#
  17. import os, random
  18. const
  19. maxRetry = 10000
  20. letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  21. nimTempPathLength {.intdefine.} = 8
  22. when defined(windows):
  23. import winlean
  24. var O_RDWR {.importc: "_O_RDWR", header: "<fcntl.h>".}: cint
  25. proc c_fdopen(
  26. filehandle: cint,
  27. mode: cstring
  28. ): File {.importc: "_fdopen",header: "<stdio.h>".}
  29. proc open_osfhandle(osh: Handle, mode: cint): cint {.
  30. importc: "_open_osfhandle", header: "<io.h>".}
  31. proc close_osfandle(fd: cint): cint {.
  32. importc: "_close", header: "<io.h>".}
  33. else:
  34. import posix
  35. proc c_fdopen(
  36. filehandle: cint,
  37. mode: cstring
  38. ): File {.importc: "fdopen",header: "<stdio.h>".}
  39. proc safeOpen(filename: string): File =
  40. ## Open files exclusively; returns `nil` if the file already exists.
  41. # xxx this should be clarified; it doesn't in particular prevent other processes
  42. # from opening the file, at least currently.
  43. when defined(windows):
  44. let dwShareMode = FILE_SHARE_DELETE or FILE_SHARE_READ or FILE_SHARE_WRITE
  45. let dwCreation = CREATE_NEW
  46. let dwFlags = FILE_FLAG_BACKUP_SEMANTICS or FILE_ATTRIBUTE_NORMAL
  47. let handle = createFileW(newWideCString(filename), GENERIC_READ or GENERIC_WRITE, dwShareMode,
  48. nil, dwCreation, dwFlags, Handle(0))
  49. if handle == INVALID_HANDLE_VALUE:
  50. if getLastError() == ERROR_FILE_EXISTS:
  51. return nil
  52. else:
  53. raiseOSError(osLastError(), filename)
  54. let fileHandle = open_osfhandle(handle, O_RDWR)
  55. if fileHandle == -1:
  56. discard closeHandle(handle)
  57. raiseOSError(osLastError(), filename)
  58. result = c_fdopen(fileHandle, "w+")
  59. if result == nil:
  60. discard close_osfandle(fileHandle)
  61. raiseOSError(osLastError(), filename)
  62. else:
  63. # xxx we need a `proc toMode(a: FilePermission): Mode`, possibly by
  64. # exposing fusion/filepermissions.fromFilePermissions to stdlib; then we need
  65. # to expose a `perm` param so users can customize this (e.g. the temp file may
  66. # need execute permissions), and figure out how to make the API cross platform.
  67. let mode = Mode(S_IRUSR or S_IWUSR)
  68. let flags = posix.O_RDWR or posix.O_CREAT or posix.O_EXCL
  69. let fileHandle = posix.open(filename, flags, mode)
  70. if fileHandle == -1:
  71. if errno == EEXIST:
  72. # xxx `getLastError()` should be defined on posix too and resolve to `errno`?
  73. return nil
  74. else:
  75. raiseOSError(osLastError(), filename)
  76. result = c_fdopen(fileHandle, "w+")
  77. if result == nil:
  78. discard posix.close(fileHandle) # TODO handles failure when closing file
  79. raiseOSError(osLastError(), filename)
  80. type
  81. NimTempPathState = object
  82. state: Rand
  83. isInit: bool
  84. var nimTempPathState {.threadvar.}: NimTempPathState
  85. template randomPathName(length: Natural): string =
  86. var res = newString(length)
  87. if not nimTempPathState.isInit:
  88. nimTempPathState.isInit = true
  89. nimTempPathState.state = initRand()
  90. for i in 0 ..< length:
  91. res[i] = nimTempPathState.state.sample(letters)
  92. res
  93. proc getTempDirImpl(dir: string): string {.inline.} =
  94. result = dir
  95. if result.len == 0:
  96. result = getTempDir()
  97. proc genTempPath*(prefix, suffix: string, dir = ""): string =
  98. ## Generates a path name in `dir`.
  99. ##
  100. ## If `dir` is empty, (`getTempDir <os.html#getTempDir>`_) will be used.
  101. ## The path begins with `prefix` and ends with `suffix`.
  102. let dir = getTempDirImpl(dir)
  103. result = dir / (prefix & randomPathName(nimTempPathLength) & suffix)
  104. proc createTempFile*(prefix, suffix: string, dir = ""): tuple[cfile: File, path: string] =
  105. ## Creates a new temporary file in the directory `dir`.
  106. ##
  107. ## This generates a path name using `genTempPath(prefix, suffix, dir)` and
  108. ## returns a file handle to an open file and the path of that file, possibly after
  109. ## retrying to ensure it doesn't already exist.
  110. ##
  111. ## If failing to create a temporary file, `OSError` will be raised.
  112. ##
  113. ## .. note:: It is the caller's responsibility to close `result.cfile` and
  114. ## remove `result.file` when no longer needed.
  115. ## .. note:: `dir` must exist (empty `dir` will resolve to `getTempDir()`).
  116. runnableExamples:
  117. import std/os
  118. doAssertRaises(OSError): discard createTempFile("", "", "nonexistent")
  119. let (cfile, path) = createTempFile("tmpprefix_", "_end.tmp")
  120. # path looks like: getTempDir() / "tmpprefix_FDCIRZA0_end.tmp"
  121. cfile.write "foo"
  122. cfile.setFilePos 0
  123. assert readAll(cfile) == "foo"
  124. close cfile
  125. assert readFile(path) == "foo"
  126. removeFile(path)
  127. # xxx why does above work without `cfile.flushFile` ?
  128. let dir = getTempDirImpl(dir)
  129. for i in 0 ..< maxRetry:
  130. result.path = genTempPath(prefix, suffix, dir)
  131. result.cfile = safeOpen(result.path)
  132. if result.cfile != nil:
  133. return
  134. raise newException(OSError, "Failed to create a temporary file under directory " & dir)
  135. proc createTempDir*(prefix, suffix: string, dir = ""): string =
  136. ## Creates a new temporary directory in the directory `dir`.
  137. ##
  138. ## This generates a dir name using `genTempPath(prefix, suffix, dir)`, creates
  139. ## the directory and returns it, possibly after retrying to ensure it doesn't
  140. ## already exist.
  141. ##
  142. ## If failing to create a temporary directory, `OSError` will be raised.
  143. ##
  144. ## .. note:: It is the caller's responsibility to remove the directory when no longer needed.
  145. ## .. note:: `dir` must exist (empty `dir` will resolve to `getTempDir()`).
  146. runnableExamples:
  147. import std/os
  148. doAssertRaises(OSError): discard createTempDir("", "", "nonexistent")
  149. let dir = createTempDir("tmpprefix_", "_end")
  150. # dir looks like: getTempDir() / "tmpprefix_YEl9VuVj_end"
  151. assert dirExists(dir)
  152. removeDir(dir)
  153. let dir = getTempDirImpl(dir)
  154. for i in 0 ..< maxRetry:
  155. result = genTempPath(prefix, suffix, dir)
  156. if not existsOrCreateDir(result):
  157. return
  158. raise newException(OSError, "Failed to create a temporary directory under directory " & dir)