import Darwin import Foundation struct AppStandardStreams { static func redirect( environment: [String: String], outputDescriptor: Int32 = STDOUT_FILENO, errorDescriptor: Int32 = STDERR_FILENO ) throws { guard environment["PARCEL_E2E"] == "1", let path = environment["PARCEL_E2E_LOG_PATH"] else { return } guard path.hasPrefix("/"), !path.contains("\0") else { throw CocoaError(.fileWriteInvalidFileName, userInfo: [NSFilePathErrorKey: path]) } let descriptor = Darwin.open(path, O_WRONLY | O_CREAT | O_APPEND | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK, 0o600) guard descriptor >= 0 else { throw posixError() } defer { Darwin.close(descriptor) } var info = stat() guard fstat(descriptor, &info) == 0 else { throw posixError() } guard info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_nlink == 1 else { throw CocoaError(.fileWriteNoPermission, userInfo: [NSFilePathErrorKey: path]) } guard dup2(descriptor, outputDescriptor) >= 0, dup2(descriptor, errorDescriptor) >= 0 else { throw posixError() } } private static func posixError() -> NSError { NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } }