Skip to content

Commit 090fc5f

Browse files
committed
[TSCBasic] Allow overriding the temporary directory
SwiftPM used to allow overriding the temporary directory using the TMPDIR variable. This facility was removed recently in favor of NSTemporaryDirectory() but that method doesn't respect TMPDIR on macOS. <rdar://problem/55147926>
1 parent 11e94b1 commit 090fc5f

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

Sources/TSCBasic/TemporaryFile.swift

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,23 @@ private extension TempFileError {
4545
///
4646
/// - Returns: Path to directory in which temporary file should be created.
4747
public func determineTempDirectory(_ dir: AbsolutePath? = nil) throws -> AbsolutePath {
48-
// FIXME: Add other platform specific locations.
49-
let tmpDir = dir ?? AbsolutePath(NSTemporaryDirectory())
48+
let tmpDir = dir ?? cachedTempDirectory
5049
guard localFileSystem.isDirectory(tmpDir) else {
5150
throw TempFileError.couldNotFindTmpDir
5251
}
5352
return tmpDir
5453
}
5554

55+
/// Returns temporary directory location by searching relevant env variables.
56+
///
57+
/// Evaluates once per execution.
58+
private var cachedTempDirectory: AbsolutePath = {
59+
let override = ProcessEnv.vars["TMPDIR"] ?? ProcessEnv.vars["TEMP"] ?? ProcessEnv.vars["TMP"]
60+
if let path = override.flatMap({ try? AbsolutePath(validating: $0) }) {
61+
return path
62+
}
63+
return AbsolutePath(NSTemporaryDirectory())
64+
}()
5665

5766
/// The closure argument of the `body` closue of `withTemporaryFile`.
5867
public struct TemporaryFile {

0 commit comments

Comments
 (0)