import CryptoKit import Darwin import Foundation /// Release commands keep downloaded metadata as data, never as executable input. enum ReleaseTools { static var root: URL { URL( fileURLWithPath: ProcessInfo.processInfo.environment["PARCEL_DEV_ROOT"] ?? FileManager.default.currentDirectoryPath) } static func run(_ command: String, _ args: [String]) throws { switch command { case "release-order": try ReleaseOrder.run(args) case "update-metadata": try UpdateMetadata.run(args) case "generate-update-key": try UpdateKey.run(args) case "update-crypto": try UpdateCrypto.run(args) case "launch-feed": try LaunchFeed.run(args) case "release-summary": guard args.count == 4 else { throw DevError("Usage: release-summary FILE TAG COMMIT SUBJECT") } let text = "## Release approval\n\nTag: `\(args[1])`\n\nCommit: `\(args[2])`\n\nSubject:
\(html(args[3]))
\n" let descriptor = open(args[0], O_WRONLY | O_CREAT | O_APPEND, 0o666) guard descriptor >= 0 else { throw DevError("Could not open the release summary") } let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true) try handle.write(contentsOf: Data(text.utf8)) try handle.close() case "release-checksum": guard args.count == 2 else { throw DevError("Usage: release-checksum ARCHIVE SHA256SUMS") } let archive = URL(fileURLWithPath: args[0]) let expected = try "\(UpdateCrypto.digest(archive)) \(archive.lastPathComponent)\n" guard try String(contentsOfFile: args[1], encoding: .utf8) == expected else { throw DevError("Release checksum does not match the DMG") } case "release-state": guard args.count == 1 else { throw DevError("Usage: release-state TAG < RELEASES") } let releases = try DevJSON.decode(FileHandle.standardInput.readDataToEndOfFile()).requireArray() let found = releases.first { $0["tagName"]?.string == args[0] } if let found { guard let draft = found["isDraft"]?.bool else { throw DevError("Release has no draft state") } print(draft ? "draft" : "published") } else { print("missing") } case "release-certificate-json": guard args.isEmpty else { throw DevError("Usage: release-certificate-json < PASSWORD-NUL-CERTIFICATE") } let data = FileHandle.standardInput.readDataToEndOfFile() guard let text = String(data: data, encoding: .utf8), let separator = text.firstIndex(of: "\0"), !text[text.index(after: separator)...].contains("\0") else { throw DevError("Expected a certificate password and certificate on stdin") } let value = DevJSON.object([ "certificatePassword": .string(String(text[..= 2 else { throw DevError("Usage: release-data-not-contained LOG PRIVATE_FILES...") } let output = try Data(contentsOf: URL(fileURLWithPath: args[0])) for path in args.dropFirst() { let privateData = try Data(contentsOf: URL(fileURLWithPath: path)) guard privateData.isEmpty || output.range(of: privateData) == nil else { throw DevError("Private input appears in the output") } } default: throw DevError("Unknown release command: \(command)") } } static func html(_ value: String) -> String { value.replacingOccurrences(of: "&", with: "&") .replacingOccurrences(of: "<", with: "<") .replacingOccurrences(of: ">", with: ">") .replacingOccurrences(of: "\"", with: """) .replacingOccurrences(of: "'", with: "'") } static func distributionPermissions(_ app: URL) throws { guard let enumerator = FileManager.default.enumerator( at: app, includingPropertiesForKeys: [.isSymbolicLinkKey, .isDirectoryKey, .isRegularFileKey]) else { throw DevError("Could not enumerate distribution files") } try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: app.path) for case let path as URL in enumerator { let values = try path.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey, .isRegularFileKey]) if values.isSymbolicLink == true { enumerator.skipDescendants(); continue } let mode: Int if values.isDirectory == true { mode = 0o755 } else { guard values.isRegularFile == true else { throw DevError("Unexpected distribution file type") } let permissions = try FileManager.default.attributesOfItem(atPath: path.path)[.posixPermissions] guard let permissions = permissions as? NSNumber else { throw DevError("Missing file permissions") } mode = permissions.intValue & 0o111 == 0 ? 0o644 : 0o755 } try FileManager.default.setAttributes([.posixPermissions: mode], ofItemAtPath: path.path) } } } struct ReleaseFiles { static func regular(_ path: URL) throws -> Bool { var info = stat() guard lstat(path.path, &info) == 0 else { if errno == ENOENT { return false } throw DevError("Could not inspect \(path.path): \(String(cString: strerror(errno)))") } return info.st_mode & S_IFMT == S_IFREG } static func symlink(_ path: URL) throws -> Bool { var info = stat() guard lstat(path.path, &info) == 0 else { if errno == ENOENT { return false } throw DevError("Could not inspect \(path.path): \(String(cString: strerror(errno)))") } return info.st_mode & S_IFMT == S_IFLNK } static func atomic(_ data: Data, to path: URL) throws { var name = Array(path.deletingLastPathComponent().appendingPathComponent(".appcast-XXXXXX").path.utf8CString) let descriptor = mkstemp(&name) guard descriptor >= 0 else { throw DevError("Could not create the temporary appcast") } let temporary = String(decoding: name.prefix(while: { $0 != 0 }).map { UInt8(bitPattern: $0) }, as: UTF8.self) var closed = false defer { if !closed { close(descriptor) } if unlink(temporary) != 0 && errno != ENOENT { FileHandle.standardError.write(Data("Could not remove temporary appcast: \(temporary)\n".utf8)) } } try data.withUnsafeBytes { bytes in guard let base = bytes.baseAddress else { return } var written = 0 while written < bytes.count { let count = Darwin.write(descriptor, base.advanced(by: written), bytes.count - written) if count < 0 && errno == EINTR { continue } guard count > 0 else { throw DevError("Could not write appcast") } written += count } } guard fsync(descriptor) == 0, fchmod(descriptor, 0o644) == 0 else { throw DevError("Could not flush appcast") } let status = close(descriptor) closed = true guard status == 0, rename(temporary, path.path) == 0 else { throw DevError("Could not publish appcast") } } }