forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemporaryDirectory.swift
More file actions
30 lines (27 loc) · 1016 Bytes
/
TemporaryDirectory.swift
File metadata and controls
30 lines (27 loc) · 1016 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import Foundation
struct MakeTemporaryDirectoryError: Error {
let error: CInt
}
internal func withTemporaryDirectory<T>(
prefixDirectory: URL = FileManager.default.temporaryDirectory,
body: (URL, _ retain: inout Bool) throws -> T
) throws -> T {
// Create a temporary directory using mkdtemp
var template = prefixDirectory.appendingPathComponent("PackageToJSTests.XXXXXX").path
return try template.withUTF8 { template in
let copy = UnsafeMutableBufferPointer<CChar>.allocate(capacity: template.count + 1)
template.copyBytes(to: copy)
copy[template.count] = 0
guard let result = mkdtemp(copy.baseAddress!) else {
throw MakeTemporaryDirectoryError(error: errno)
}
let tempDir = URL(fileURLWithPath: String(cString: result))
var retain = false
defer {
if !retain {
try? FileManager.default.removeItem(at: tempDir)
}
}
return try body(tempDir, &retain)
}
}