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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
import Foundation
enum TestSupport {
struct Error: Swift.Error, CustomStringConvertible {
let description: String
init(description: String) {
self.description = description
}
init(errno: Int32) {
self.init(description: String(cString: strerror(errno)))
}
}
static func withTemporaryDirectory<Result>(
_ body: (String, _ shouldRetain: inout Bool) throws -> Result
) throws -> Result {
let tempdir = URL(fileURLWithPath: NSTemporaryDirectory())
let templatePath = tempdir.appendingPathComponent("WasmKit.XXXXXX")
var template = [UInt8](templatePath.path.utf8).map({ Int8($0) }) + [Int8(0)]
#if os(Windows)
if _mktemp_s(&template, template.count) != 0 {
throw Error(errno: errno)
}
if _mkdir(template) != 0 {
throw Error(errno: errno)
}
#else
if mkdtemp(&template) == nil {
#if os(Android)
throw Error(errno: __errno().pointee)
#else
throw Error(errno: errno)
#endif
}
#endif
let path = String(cString: template)
var shouldRetain = false
defer {
if !shouldRetain {
_ = try? FileManager.default.removeItem(atPath: path)
}
}
return try body(path, &shouldRetain)
}
static func lookupExecutable(_ name: String) -> URL? {
let envName = "\(name.uppercased())_EXEC"
if let path = ProcessInfo.processInfo.environment[envName] {
let url = URL(fileURLWithPath: path).deletingLastPathComponent().appendingPathComponent(name)
if FileManager.default.isExecutableFile(atPath: url.path) {
return url
}
print("Executable path \(url.path) specified by \(envName) is not found or not executable, falling back to PATH lookup")
}
#if os(Windows)
let pathEnvVar = "Path"
let pathSeparator: Character = ";"
#else
let pathEnvVar = "PATH"
let pathSeparator: Character = ":"
#endif
let paths = ProcessInfo.processInfo.environment[pathEnvVar] ?? ""
let searchPaths = paths.split(separator: pathSeparator).map(String.init)
for path in searchPaths {
let url = URL(fileURLWithPath: path).appendingPathComponent(name)
if FileManager.default.isExecutableFile(atPath: url.path) {
return url
}
}
return nil
}
}
|