Skip to content

Commit 7ff51ef

Browse files
authored
Merge pull request #2910 from readdle/temporary-slash
[Windows] Add trailing slash to NSTemporaryDirectory result
2 parents 46b20d4 + 7fb98b7 commit 7ff51ef

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

Sources/Foundation/NSPathUtilities.swift

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,20 @@ let validPathSeps: [Character] = ["/"]
1616
#endif
1717

1818
public func NSTemporaryDirectory() -> String {
19+
func normalizedPath(with path: String) -> String {
20+
if validPathSeps.contains(where: { path.hasSuffix(String($0)) }) {
21+
return path
22+
} else {
23+
return path + String(validPathSeps.last!)
24+
}
25+
}
1926
#if os(Windows)
2027
let cchLength: DWORD = GetTempPathW(0, nil)
2128
var wszPath: [WCHAR] = Array<WCHAR>(repeating: 0, count: Int(cchLength + 1))
2229
guard GetTempPathW(DWORD(wszPath.count), &wszPath) <= cchLength else {
2330
preconditionFailure("GetTempPathW mutation race")
2431
}
25-
return String(decodingCString: wszPath, as: UTF16.self).standardizingPath
32+
return normalizedPath(with: String(decodingCString: wszPath, as: UTF16.self).standardizingPath)
2633
#else
2734
#if canImport(Darwin)
2835
let safe_confstr = { (name: Int32, buf: UnsafeMutablePointer<Int8>?, len: Int) -> Int in
@@ -57,11 +64,7 @@ public func NSTemporaryDirectory() -> String {
5764
}
5865
#endif
5966
if let tmpdir = ProcessInfo.processInfo.environment["TMPDIR"] {
60-
if !validPathSeps.contains(where: { tmpdir.hasSuffix(String($0)) }) {
61-
return tmpdir + "/"
62-
} else {
63-
return tmpdir
64-
}
67+
return normalizedPath(with: tmpdir)
6568
}
6669
#if os(Android)
6770
// Bionic uses /data/local/tmp/ as temporary directory. TMPDIR is rarely

Tests/Foundation/Tests/TestFileManager.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ class TestFileManager : XCTestCase {
2424
let pathSep = "/"
2525
#endif
2626

27+
func test_NSTemporaryDirectory() {
28+
let tempDir = NSTemporaryDirectory()
29+
XCTAssertTrue(validPathSeps.contains(where: { tempDir.hasSuffix(String($0)) }), "Temporary directory path must end with path separator")
30+
}
31+
2732
func test_createDirectory() {
2833
let fm = FileManager.default
2934
let path = NSTemporaryDirectory() + "testdir\(NSUUID().uuidString)"
@@ -1974,6 +1979,7 @@ VIDEOS=StopgapVideos
19741979
/* ⚠️ */ ("test_replacement", testExpectedToFail(test_replacement,
19751980
/* ⚠️ */ "<https://bugs.swift.org/browse/SR-10819> Re-enable Foundation test TestFileManager.test_replacement")),
19761981
("test_concurrentGetItemReplacementDirectory", test_concurrentGetItemReplacementDirectory),
1982+
("test_NSTemporaryDirectory", test_NSTemporaryDirectory),
19771983
]
19781984

19791985
#if !DEPLOYMENT_RUNTIME_OBJC && NS_FOUNDATION_ALLOWS_TESTABLE_IMPORT && !os(Android)

0 commit comments

Comments
 (0)