import Foundation public enum NotifyClient { /// Sends one event line. Throws a descriptive error when the app is not listening, so the CLI can /// report it on stderr while still exiting 0. public static func send(_ event: NotifyEvent, to path: String) throws { let line = try NotifySocket.encodeLine(event) let descriptor = socket(AF_UNIX, SOCK_STREAM, 0) guard descriptor >= 0 else { throw SocketError.syscall("socket", errno) } defer { close(descriptor) } var address = try NotifySocket.makeAddress(path) let connected = withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(descriptor, $0, socklen_t(MemoryLayout.size)) } } guard connected == 0 else { throw SocketError.syscall("connect to \(path)", errno) } try writeAll(line, to: descriptor) } private static func writeAll(_ data: Data, to descriptor: Int32) throws { var sent = 0 try data.withUnsafeBytes { buffer in while sent < data.count { let count = write(descriptor, buffer.baseAddress!.advanced(by: sent), data.count - sent) guard count > 0 else { throw SocketError.syscall("write", errno) } sent += count } } } }