xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XUtils / TemporaryDirectory.swift
TemporaryDirectory.swift184 lines · 7.1 KiBRaw
| 1 | import Foundation |
| 2 | |
| 3 | package struct TemporaryDirectory: ~Copyable { |
| 4 | private static let debugTmp = ProcessInfo.processInfo.environment["XTL_DEBUG_TMP"] != nil |
| 5 | |
| 6 | private var shouldDelete: Bool |
| 7 | private let base: URL |
| 8 | package let url: URL |
| 9 | |
| 10 | /// Prepares a fresh tmpdir root. |
| 11 | /// |
| 12 | /// Optional, but try calling this at launch to clean up old resources. |
| 13 | package static func prepare() { |
| 14 | _ = TemporaryDirectoryRoot.shared |
| 15 | } |
| 16 | |
| 17 | /// Creates a temporary directory where `lastPathComponent` is exactly `name`. |
| 18 | /// |
| 19 | /// The directory is deleted on deinit or (if the object never deinits) on next launch. |
| 20 | /// To save the contents, move them elsewhere with ``persist(at:)``. |
| 21 | package init(name: String) throws { |
| 22 | do { |
| 23 | let basename = name |
| 24 | .replacingOccurrences(of: ".", with: "_") |
| 25 | .replacingOccurrences(of: "/", with: "_") |
| 26 | .prefix(32) |
| 27 | self.base = try TemporaryDirectoryRoot.shared.url |
| 28 | // ensures uniqueness |
| 29 | .appendingPathComponent("dir-\(basename)-\(UUID().uuidString)") |
| 30 | self.url = base.appendingPathComponent(name, isDirectory: true) |
| 31 | self.shouldDelete = true |
| 32 | } catch { |
| 33 | // non-copyable types can't be partially initialized so we need a stub value |
| 34 | self.base = URL(fileURLWithPath: "") |
| 35 | self.url = base |
| 36 | self.shouldDelete = false |
| 37 | throw error |
| 38 | } |
| 39 | try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) |
| 40 | |
| 41 | if Self.debugTmp { |
| 42 | stderrPrint("Created TemporaryDirectory: \(url.path)") |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | private func _delete() { |
| 47 | guard !Self.debugTmp else { return } |
| 48 | try? FileManager.default.removeItem(at: base) |
| 49 | } |
| 50 | |
| 51 | package consuming func persist(at location: URL) throws { |
| 52 | try FileManager.default.moveItem(at: url, to: location) |
| 53 | _delete() |
| 54 | // we do this after moving, so that if the move fails we clean up |
| 55 | shouldDelete = false |
| 56 | } |
| 57 | |
| 58 | deinit { |
| 59 | if shouldDelete { _delete() } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | private struct TemporaryDirectoryRoot { |
| 64 | static let shared = TemporaryDirectoryRoot() |
| 65 | |
| 66 | private let _url: Result<URL, Errors> |
| 67 | var url: URL { |
| 68 | get throws(Errors) { |
| 69 | try _url.get() |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | private init() { |
| 74 | let url: URL |
| 75 | let env = ProcessInfo.processInfo.environment |
| 76 | if let tmpdir = env["XTL_TMPDIR"] ?? env["TMPDIR"] { |
| 77 | url = URL(fileURLWithPath: tmpdir).appendingPathComponent("sh.xtool") |
| 78 | } else { |
| 79 | #if os(Linux) |
| 80 | // On Linux, /tmp is commonly a tmpfs mount while ~/.swiftpm lives on ext4. |
| 81 | // Foundation's FileManager.copyItem uses sendfile(2) internally, which returns |
| 82 | // EINVAL when copying between different filesystem types (e.g. tmpfs → ext4). |
| 83 | // This causes `swift sdk install` to fail on distros like Linux Mint (#181). |
| 84 | // Using a cache dir on the home filesystem avoids the cross-fs copy entirely. |
| 85 | let xdgCache = env["XDG_CACHE_HOME"].map { URL(fileURLWithPath: $0) } |
| 86 | ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".cache") |
| 87 | url = xdgCache.appendingPathComponent("xtool") |
| 88 | #else |
| 89 | url = FileManager.default.temporaryDirectory.appendingPathComponent("sh.xtool") |
| 90 | #endif |
| 91 | } |
| 92 | |
| 93 | Self.pruneOrphans(in: url) |
| 94 | |
| 95 | self._url = Result { |
| 96 | let childDir = try Self.claimDirectory(in: url) |
| 97 | try FileManager.default.createDirectory(at: childDir, withIntermediateDirectories: true) |
| 98 | return childDir |
| 99 | } |
| 100 | .mapError { $0 as? Errors ?? .tmpdirCreationFailed(url, $0) } |
| 101 | } |
| 102 | |
| 103 | private static func claimDirectory(in url: URL) throws -> URL { |
| 104 | // create a lockfile + tmpdir. while we hold the lock, other instaces of |
| 105 | // xtool will not delete the directory during their prune step. |
| 106 | |
| 107 | try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) |
| 108 | |
| 109 | let pid = ProcessInfo.processInfo.processIdentifier |
| 110 | |
| 111 | for i in 0..<10 { |
| 112 | let random = "pid-\(pid)-\(i == 0 ? "0" : UUID().uuidString)" |
| 113 | let lockFile = url.appending(path: "\(random).lock") |
| 114 | #if os(macOS) |
| 115 | let fd = try FileDescriptor.open( |
| 116 | FilePath(lockFile.path), |
| 117 | .writeOnly, |
| 118 | options: [.create, .exclusiveLock], |
| 119 | permissions: [.ownerReadWrite, .groupRead, .otherRead], |
| 120 | ) |
| 121 | #else |
| 122 | let fd = try FileDescriptor.open( |
| 123 | FilePath(lockFile.path), |
| 124 | .writeOnly, |
| 125 | options: [.create], |
| 126 | permissions: [.ownerReadWrite, .groupRead, .otherRead], |
| 127 | ) |
| 128 | guard try fd.tryLock(mode: .exclusive) else { |
| 129 | // someone else raced us and claimed the right to prune between when we created the file and |
| 130 | // when we tried to lock it |
| 131 | continue |
| 132 | } |
| 133 | #endif |
| 134 | // leak the file descriptor so that the lock is held until the process exits |
| 135 | return url.appending(path: random) |
| 136 | } |
| 137 | throw Errors.tmpdirClaimFailed(url) |
| 138 | } |
| 139 | |
| 140 | private static func pruneOrphans(in url: URL) { |
| 141 | guard let children = try? FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil) |
| 142 | else { return } |
| 143 | for lock in children { |
| 144 | do { |
| 145 | let basename = lock.lastPathComponent |
| 146 | if basename.hasPrefix("tmp-") { |
| 147 | // legacy tmpdir, remove it |
| 148 | try? FileManager.default.removeItem(at: lock) |
| 149 | continue |
| 150 | } |
| 151 | guard basename.hasPrefix("pid-") && basename.hasSuffix(".lock") else { continue } |
| 152 | let lockFD = try FileDescriptor.open(FilePath(lock.path), .readWrite) |
| 153 | defer { try? lockFD.close() } |
| 154 | if try lockFD.tryLock(mode: .exclusive) { |
| 155 | // we must remove the directory first. if we instead removed the lock first, |
| 156 | // we could be killed after the lock was removed but before the dir was |
| 157 | // removed and therefore leave it hanging around. |
| 158 | do { |
| 159 | try FileManager.default.removeItem(at: lock.deletingPathExtension()) |
| 160 | } catch CocoaError.fileNoSuchFile { |
| 161 | // pass |
| 162 | } |
| 163 | try FileManager.default.removeItem(at: lock) |
| 164 | } |
| 165 | } catch { |
| 166 | // continue |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | enum Errors: Error, CustomStringConvertible { |
| 172 | case tmpdirCreationFailed(URL, Error) |
| 173 | case tmpdirClaimFailed(URL) |
| 174 | |
| 175 | var description: String { |
| 176 | switch self { |
| 177 | case let .tmpdirCreationFailed(url, error): |
| 178 | "Could not create temporary directory in '\(url.path)': \(error)" |
| 179 | case let .tmpdirClaimFailed(url): |
| 180 | "Could not claim temporary directory in '\(url.path)'" |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | } |