Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
Find what is new in each waiting update, from the app's own sources
Țugui Dragoș62a942ef91f9
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/AppStoreLookup.swift b/Packages/PeelCore/Sources/PeelCore/Updates/AppStoreLookup.swiftindex e08fe8bb..7c8d4697 100644--- a/Packages/PeelCore/Sources/PeelCore/Updates/AppStoreLookup.swift+++ b/Packages/PeelCore/Sources/PeelCore/Updates/AppStoreLookup.swift@@ -2,9 +2,10 @@ import Foundationenum AppStoreLookup {enum Answer: Equatable {- /// The Mac app's version, its store page (where the user can read what changed and update), and its- /// developer as `artistName` gives it ("Apple" for Apple's own apps, where `sellerName` gives "Apple Inc.").- case mac(version: String, page: URL?, developer: String?)+ /// The Mac app's version, its store page (where the user can read what changed and update), its developer+ /// as `artistName` gives it ("Apple" for Apple's own apps, where `sellerName` gives "Apple Inc."), and what+ /// is new in that version, as plain text.+ case mac(version: String, page: URL?, developer: String?, notes: ReleaseNotes? = nil)/// Apple answered, but with no Mac record. An app sold as one purchase for iPhone, iPad, and Mac has a/// single record of kind "software" that carries the iPhone version, which cannot be compared with the/// Mac app's. Apple also answers with no record at all for an app the store doesn't sell in this region,@@ -28,7 +29,8 @@ enum AppStoreLookup {return .mac(version: version,page: mac.trackViewUrl.flatMap(URL.init(string:)),- developer: mac.artistName.flatMap { $0.isEmpty ? nil : $0 }+ developer: mac.artistName.flatMap { $0.isEmpty ? nil : $0 },+ notes: mac.releaseNotes.flatMap { ReleaseNotes($0, format: .plainText) })}@@ -38,6 +40,7 @@ enum AppStoreLookup {let version: String?let trackViewUrl: String?let artistName: String?+ let releaseNotes: String?}let results: [Result]diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/Appcast.swift b/Packages/PeelCore/Sources/PeelCore/Updates/Appcast.swiftindex 88bf0290..0f4351dc 100644--- a/Packages/PeelCore/Sources/PeelCore/Updates/Appcast.swift+++ b/Packages/PeelCore/Sources/PeelCore/Updates/Appcast.swift@@ -11,6 +11,18 @@ struct AppcastItem: Equatable {/// `sparkle:hardwareRequirements`, in lowercase. Sparkle knows one: `arm64`, a release for Apple silicon only.var hardwareRequirements: Set<String> = []var releaseNotes: URL?+ /// The page `sparkle:releaseNotesLink` names, which holds what is new. Unlike `releaseNotes`, never the product+ /// page an item's `link` names.+ var notesPage: URL?+ /// The item's `description` in the reader's language, and the format its `sparkle:format` names.+ var description: String?+ var descriptionFormat: ReleaseNotes.Format = .html++ /// What is new, as the item writes it in its `description`. Read once the feed has been, since reading HTML+ /// while `XMLParser` is still reading the feed stops it.+ var notes: ReleaseNotes? {+ description.flatMap { ReleaseNotes($0, format: descriptionFormat) }+ }var displayVersion: String? {shortVersion ?? version@@ -31,12 +43,20 @@ enum Appcast {/// items for another operating system, items that need a newer or older macOS, and, on an Intel Mac, items/// that need Apple silicon. Sparkle offers those under Rosetta, which only an Apple silicon Mac has.static func read(_ data: Data, systemVersion: String, isAppleSilicon: Bool) -> Reading {+ guard let releases = releases(in: data, systemVersion: systemVersion, isAppleSilicon: isAppleSilicon) else {+ return .unreadable+ }+ return releases.max(by: isOlder).map(Reading.latest) ?? .nothingForThisMac+ }++ /// Every release in the feed that runs on `systemVersion`, in feed order. Nil for a feed that cannot be read.+ static func releases(in data: Data, systemVersion: String, isAppleSilicon: Bool) -> [AppcastItem]? {let delegate = ParserDelegate()let parser = XMLParser(data: data)parser.delegate = delegate- guard parser.parse() else { return .unreadable }+ guard parser.parse() else { return nil }- let releases = delegate.items.filter { item in+ return delegate.items.filter { item inguard item.channel == nil, item.displayVersion != nil, item.system == nil || item.system == "macos" else {return false}@@ -49,23 +69,32 @@ enum Appcast {if !isAppleSilicon, item.hardwareRequirements.contains("arm64") { return false }return true}- return releases.max(by: isOlder).map(Reading.latest) ?? .nothingForThisMac}- /// Picks the release notes link in the user's language, then a link with no language, then the first link.+ /// Picks the release notes in the user's language, then notes with no language, then the first./// `Bundle.preferredLocalizations` returns a language even when none matches (the first one offered, or `en`- /// when none is offered), so its pick is used only when the user reads that language and a link has it.- static func preferred(- _ links: [(language: String, url: URL)],+ /// when none is offered), so its pick is used only when the user reads that language and notes have it.+ static func preferred<Value>(+ _ notes: [(language: String, value: Value)],languages: [String] = Locale.preferredLanguages- ) -> URL? {+ ) -> Value? {func base(_ tag: String) -> String { Locale(identifier: tag).language.languageCode?.identifier ?? tag }- let tagged = links.map(\.language).filter { !$0.isEmpty }+ let tagged = notes.map(\.language).filter { !$0.isEmpty }if let best = Bundle.preferredLocalizations(from: tagged, forPreferences: languages).first,- Set(languages.map(base)).contains(base(best)), let url = links.first(where: { $0.language == best })?.url {- return url+ Set(languages.map(base)).contains(base(best)),+ let value = notes.first(where: { $0.language == best })?.value {+ return value+ }+ return notes.first { $0.language.isEmpty }?.value ?? notes.first?.value+ }++ /// The format a `description` is read in, as Sparkle reads `sparkle:format`: HTML unless it says otherwise.+ static func format(named name: String?) -> ReleaseNotes.Format {+ switch name?.lowercased() {+ case "plain-text": .plainText+ case "markdown": .markdown+ default: .html}- return links.first { $0.language.isEmpty }?.url ?? links.first?.url}private static func isOlder(_ lhs: AppcastItem, than rhs: AppcastItem) -> Bool {@@ -84,8 +113,11 @@ enum Appcast {private var elementShortVersion: String?/// The item's release notes links by element, in feed order, each with its `xml:lang` language or ""./// An item's `<link>` is usually the product page, so it is the last choice for release notes.- private var notes: [String: [(language: String, url: URL)]] = [:]+ private var notes: [String: [(language: String, value: URL)]] = [:]private var noteLanguage = ""+ /// The item's `description` elements, each with its language and its `sparkle:format`.+ private var descriptions: [(language: String, value: (text: String, format: String?))] = []+ private var descriptionFormat: String?func parser(_ parser: XMLParser,@@ -98,9 +130,12 @@ enum Appcast {switch elementName {case "item":current = AppcastItem()- (elementVersion, elementShortVersion, notes) = (nil, nil, [:])+ (elementVersion, elementShortVersion, notes, descriptions) = (nil, nil, [:], [])case "sparkle:releaseNotesLink", "releaseNotesLink", "sparkle:fullReleaseNotesLink", "link":noteLanguage = attributes["xml:lang"] ?? ""+ case "description":+ noteLanguage = attributes["xml:lang"] ?? ""+ descriptionFormat = attributes["sparkle:format"]case "enclosure":guard var item = current, item.version == nil, item.shortVersion == nil, item.system == nil else {break@@ -137,6 +172,12 @@ enum Appcast {item.releaseNotes =["sparkle:releaseNotesLink", "releaseNotesLink", "sparkle:fullReleaseNotesLink", "link"].lazy.compactMap { self.notes[$0].flatMap { Appcast.preferred($0) } }.first+ item.notesPage = ["sparkle:releaseNotesLink", "releaseNotesLink"]+ .lazy.compactMap { self.notes[$0].flatMap { Appcast.preferred($0) } }.first+ if let description = Appcast.preferred(descriptions) {+ item.description = description.text+ item.descriptionFormat = Appcast.format(named: description.format)+ }items.append(item)}current = nil@@ -160,6 +201,8 @@ enum Appcast {notes[elementName]?.contains(where: { $0.language == noteLanguage }) != true {notes[elementName, default: []].append((noteLanguage, url))}+ case "description" where current != nil:+ descriptions.append((noteLanguage, (value, descriptionFormat)))default:break}diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/ElectronUpdater.swift b/Packages/PeelCore/Sources/PeelCore/Updates/ElectronUpdater.swiftindex 8a0a79f7..04c29926 100644--- a/Packages/PeelCore/Sources/PeelCore/Updates/ElectronUpdater.swift+++ b/Packages/PeelCore/Sources/PeelCore/Updates/ElectronUpdater.swift@@ -24,6 +24,75 @@ enum ElectronUpdater {topLevelFields(in: text)["version"]}+ /// What is new in the release: the feed's top-level `releaseNotes`, which electron-builder writes from the app's+ /// release notes, in Markdown, as a plain, quoted or block scalar. The list it writes instead when told to keep+ /// every version's notes is not read.+ static func releaseNotes(fromFeed text: String) -> ReleaseNotes? {+ let lines = text.split(separator: "\n", omittingEmptySubsequences: false)+ let key = "releaseNotes:"+ guard let start = lines.firstIndex(where: { $0.hasPrefix(key) }) else { return nil }+ let value = lines[start].dropFirst(key.count).trimmingCharacters(in: .whitespaces)+ let notes: String+ switch value.first {+ case "|", ">":+ let block = lines[(start + 1)...].prefix { $0.isEmpty || $0.first?.isWhitespace == true }+ notes = scalar(of: block, keepingLineBreaks: value.first == "|")+ case "'":+ guard value.count >= 2, value.hasSuffix("'") else { return nil }+ notes = String(value.dropFirst().dropLast()).replacingOccurrences(of: "''", with: "'")+ case "\"":+ guard value.count >= 2, value.hasSuffix("\"") else { return nil }+ notes = unescaped(value.dropFirst().dropLast())+ case nil:+ return nil+ default:+ notes = value+ }+ return ReleaseNotes(notes, format: .markdown)+ }++ /// A block scalar's lines without their common indentation: kept as lines for `|`, and folded into paragraphs+ /// for `>`, where an empty line is a line break.+ private static func scalar(of block: ArraySlice<Substring>, keepingLineBreaks: Bool) -> String {+ func indentation(_ line: Substring) -> Int { line.prefix { $0 == " " }.count }+ let written = block.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }+ let common = written.map(indentation).min() ?? 0+ let lines = block.map { String($0.dropFirst(min(common, indentation($0)))) }+ guard !keepingLineBreaks else { return lines.joined(separator: "\n") }+ return lines.reduce(into: "") { folded, line in+ if line.isEmpty {+ folded += "\n"+ } else {+ if !folded.isEmpty, folded.last != "\n" { folded += " " }+ folded += line+ }+ }+ }++ /// A double-quoted scalar's text, with YAML's escapes read: a line break, a tab, a quote, a backslash, a slash and+ /// a character by its code.+ private static func unescaped(_ quoted: Substring) -> String {+ var text = ""+ var characters = quoted.makeIterator()+ while let character = characters.next() {+ guard character == "\\", let escaped = characters.next() else {+ text.append(character)+ continue+ }+ switch escaped {+ case "n": text.append("\n")+ case "t": text.append("\t")+ case "u":+ let digits = String((0..<4).compactMap { _ in characters.next() })+ if let code = UInt32(digits, radix: 16), let scalar = Unicode.Scalar(code) {+ text.unicodeScalars.append(scalar)+ }+ default: text.append(escaped)+ }+ }+ return text+ }+private static func topLevelFields(in text: String) -> [String: String] {var fields: [String: String] = [:]for line in text.split(whereSeparator: \.isNewline) where line.first?.isWhitespace == false {diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/GitHubRelease.swift b/Packages/PeelCore/Sources/PeelCore/Updates/GitHubRelease.swiftindex 849b3ea1..8c9b272c 100644--- a/Packages/PeelCore/Sources/PeelCore/Updates/GitHubRelease.swift+++ b/Packages/PeelCore/Sources/PeelCore/Updates/GitHubRelease.swift@@ -6,25 +6,27 @@ enum GitHubRelease {/// Peel's own releases, the one repository Peel asks about: no other app says where it is released.static let peel = URL(string: "https://api.github.com/repos/TuguiDragos/Peel/releases/latest")!- /// The version the release's tag names, and the release's page on GitHub, where it is downloaded. Nil for an- /// answer in any other form.- static func latest(in data: Data) -> (version: String, page: URL?)? {+ /// The version the release's tag names, the release's page on GitHub, where it is downloaded, and its+ /// description, in Markdown. Nil for an answer in any other form.+ static func latest(in data: Data) -> (version: String, page: URL?, notes: ReleaseNotes?)? {guard let release = try? JSONDecoder().decode(Release.self, from: data) else { return nil }let version = release.tagName.first == "v" || release.tagName.first == "V"? String(release.tagName.dropFirst()): release.tagNameguard !version.isEmpty else { return nil }let page = release.htmlURL.flatMap(URL.init(string:)).flatMap { $0.scheme == "https" && $0.host() == "github.com" ? $0 : nil }- return (version, page)+ return (version, page, release.body.flatMap { ReleaseNotes($0, format: .markdown) })}private struct Release: Decodable {let tagName: Stringlet htmlURL: String?+ let body: String?enum CodingKeys: String, CodingKey {case tagName = "tag_name"case htmlURL = "html_url"+ case body}}}diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/ReleaseNotes.swift b/Packages/PeelCore/Sources/PeelCore/Updates/ReleaseNotes.swiftindex 01586a58..407c8707 100644--- a/Packages/PeelCore/Sources/PeelCore/Updates/ReleaseNotes.swift+++ b/Packages/PeelCore/Sources/PeelCore/Updates/ReleaseNotes.swift@@ -120,9 +120,13 @@ private struct HTMLReader {// Read from text rather than bytes: HTML's parser takes bytes as Latin-1 unless an old-style meta tag says// otherwise.let options: XMLNode.Options = [.documentTidyHTML, .nodeLoadExternalEntitiesNever]- guard let root = (try? XMLDocument(xmlString: html, options: options))?.rootElement() else { return [] }var reader = HTMLReader()- reader.read(root, lists: 0, style: AttributeContainer())+ if let root = (try? XMLDocument(xmlString: html, options: options))?.rootElement() {+ reader.read(root, lists: 0, style: AttributeContainer())+ } else if !html.contains("<") {+ // Text with no tag at all is no document to the parser, while a browser shows it as a paragraph.+ reader.add(html, style: AttributeContainer())+ }reader.endLine()return reader.blocks}diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swiftindex 1810abb2..b9132947 100644--- a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift+++ b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift@@ -102,47 +102,57 @@ public struct UpdateChecker: Sendable {guard let installed = app.version else { return UpdateAnswer(status: .unsupported) }return switch app.updateFeed {case nil: UpdateAnswer(status: .unsupported)- case .sparkle(let url): UpdateAnswer(status: await sparkleStatus(for: app, installed: installed, at: url))- case .electron(let url): UpdateAnswer(status: await electronStatus(installed: installed, at: url))- case .gitHubRelease(let url): UpdateAnswer(status: await gitHubReleaseStatus(installed: installed, at: url))+ case .sparkle(let url): await sparkleAnswer(for: app, installed: installed, at: url)+ case .electron(let url): await electronAnswer(installed: installed, at: url)+ case .gitHubRelease(let url): await gitHubReleaseAnswer(installed: installed, at: url)case .appStore: await appStoreAnswer(for: app)}}- private func sparkleStatus(for app: InstalledApp, installed: String, at url: URL) async -> UpdateStatus {- guard let data = await fetch(url) else { return .failed }+ private func sparkleAnswer(for app: InstalledApp, installed: String, at url: URL) async -> UpdateAnswer {+ guard let data = await fetch(url) else { return UpdateAnswer(status: .failed) }let item: AppcastItemswitch Appcast.read(data, systemVersion: systemVersion, isAppleSilicon: isAppleSilicon) {- case .unreadable: return .failed- case .nothingForThisMac: return .upToDate+ case .unreadable: return UpdateAnswer(status: .failed)+ case .nothingForThisMac: return UpdateAnswer(status: .upToDate)case .latest(let latest): item = latest}- guard let latest = item.displayVersion else { return .failed }+ guard let latest = item.displayVersion else { return UpdateAnswer(status: .failed) }let isNewer = if let version = item.version, let build = app.buildVersion {VersionComparison.isNewer(version, than: build)} else {VersionComparison.isNewer(latest, than: installed)}- return isNewer- ? .updateAvailable(version: latest, source: .developer, releaseNotes: item.releaseNotes)- : .upToDate+ guard isNewer else { return UpdateAnswer(status: .upToDate) }+ return UpdateAnswer(+ status: .updateAvailable(version: latest, source: .developer, releaseNotes: item.releaseNotes),+ notes: item.notes,+ notesPage: item.notesPage+ )}- private func electronStatus(installed: String, at url: URL) async -> UpdateStatus {- guard- let data = await fetch(url),- let latest = ElectronUpdater.version(fromFeed: String(decoding: data, as: UTF8.self))- else { return .failed }- return VersionComparison.isNewer(latest, than: installed)- ? .updateAvailable(version: latest, source: .developer, releaseNotes: nil)- : .upToDate+ private func electronAnswer(installed: String, at url: URL) async -> UpdateAnswer {+ guard let data = await fetch(url) else { return UpdateAnswer(status: .failed) }+ let feed = String(decoding: data, as: UTF8.self)+ guard let latest = ElectronUpdater.version(fromFeed: feed) else { return UpdateAnswer(status: .failed) }+ guard VersionComparison.isNewer(latest, than: installed) else { return UpdateAnswer(status: .upToDate) }+ return UpdateAnswer(+ status: .updateAvailable(version: latest, source: .developer, releaseNotes: nil),+ notes: ElectronUpdater.releaseNotes(fromFeed: feed)+ )}- private func gitHubReleaseStatus(installed: String, at url: URL) async -> UpdateStatus {- guard let data = await fetch(url), let release = GitHubRelease.latest(in: data) else { return .failed }- return VersionComparison.isNewer(release.version, than: installed)- ? .updateAvailable(version: release.version, source: .developer, releaseNotes: release.page)- : .upToDate+ private func gitHubReleaseAnswer(installed: String, at url: URL) async -> UpdateAnswer {+ guard let data = await fetch(url), let release = GitHubRelease.latest(in: data) else {+ return UpdateAnswer(status: .failed)+ }+ guard VersionComparison.isNewer(release.version, than: installed) else {+ return UpdateAnswer(status: .upToDate)+ }+ return UpdateAnswer(+ status: .updateAvailable(version: release.version, source: .developer, releaseNotes: release.page),+ notes: release.notes+ )}/// Asks the App Store about `app`, but only when the app has an App Store receipt, whoever calls this.@@ -160,16 +170,20 @@ public struct UpdateChecker: Sendable {return UpdateAnswer(status: .failed)case .noMacRecord:return UpdateAnswer(status: .unsupported)- case .mac(let latest, let page, let developer):- let status: UpdateStatus = VersionComparison.isNewer(latest, than: installed)- ? .updateAvailable(version: latest, source: .appStore, releaseNotes: page)- : .upToDate- return UpdateAnswer(status: status, developer: developer)+ case .mac(let latest, let page, let developer, let notes):+ guard VersionComparison.isNewer(latest, than: installed) else {+ return UpdateAnswer(status: .upToDate, developer: developer)+ }+ return UpdateAnswer(+ status: .updateAvailable(version: latest, source: .appStore, releaseNotes: page),+ developer: developer,+ notes: notes+ )}}- private func lookup(_ identifier: String, in country: String) async -> (data: Data?, status: Int?) {- guard let url = AppStoreLookup.url(bundleIdentifier: identifier, country: country) else { return (nil, nil) }+ private func lookup(_ identifier: String, in country: String) async -> Reply {+ guard let url = AppStoreLookup.url(bundleIdentifier: identifier, country: country) else { return Reply() }return await fetchReply(url)}@@ -177,12 +191,82 @@ public struct UpdateChecker: Sendable {await fetchReply(url).data}- private func fetchReply(_ url: URL) async -> (data: Data?, status: Int?) {+ /// What is new in the update `answer` found, asked of the app's own addresses when the answer does not say: the+ /// notes page its feed names, or, for an update Homebrew found, the app's own feed. Nothing else is asked: a+ /// product page, a store page or a cask's homepage is a link to show, not notes to read.+ @concurrent+ public func releaseNotes(for app: InstalledApp, answer: UpdateAnswer) async -> ReleaseNotesLookup {+ guard case .updateAvailable = answer.status, let version = answer.status.displayVersion else {+ return .notGiven+ }+ if let notes = answer.notes { return .found(notes) }+ if let page = answer.notesPage { return await notes(at: page) }+ guard answer.status.source == .homebrew else { return .notGiven }+ switch app.updateFeed {+ case .sparkle(let url):+ guard let data = await fetch(url) else { return .unanswered }+ let releases = Appcast.releases(in: data, systemVersion: systemVersion, isAppleSilicon: isAppleSilicon)+ guard let item = releases?.first(where: { item in+ item.displayVersion.map { VersionComparison.compare($0, version) == .orderedSame } ?? false+ }) else { return .notGiven }+ if let notes = item.notes { return .found(notes) }+ guard let page = item.notesPage else { return .notGiven }+ return await notes(at: page)+ case .electron(let url):+ guard let data = await fetch(url) else { return .unanswered }+ let feed = String(decoding: data, as: UTF8.self)+ guard let latest = ElectronUpdater.version(fromFeed: feed),+ VersionComparison.compare(latest, version) == .orderedSame,+ let notes = ElectronUpdater.releaseNotes(fromFeed: feed)+ else { return .notGiven }+ return .found(notes)+ case .gitHubRelease, .appStore, nil:+ return .notGiven+ }+ }++ /// The notes a page holds, read as Sparkle reads a release notes page: in UTF-8 unless the server names another+ /// encoding, and as Markdown, plain text or HTML by the page's type or extension.+ private func notes(at page: URL) async -> ReleaseNotesLookup {+ let reply = await fetchReply(page)+ guard let data = reply.data else { return .unanswered }+ let named = reply.textEncodingName.map { CFStringConvertIANACharSetNameToEncoding($0 as CFString) }+ let encoding = named.flatMap { encoding in+ encoding == kCFStringEncodingInvalidId+ ? nil : String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(encoding))+ }+ let text = String(data: data, encoding: encoding ?? .utf8) ?? String(decoding: data, as: UTF8.self)+ let notes = ReleaseNotes(text, format: Self.format(ofNotesAt: page, type: reply.mimeType))+ return notes.map(ReleaseNotesLookup.found) ?? .notGiven+ }++ /// Markdown is asked first, since a server may send it as `text/plain`; a page with no type is HTML (Sparkle's+ /// `SUUpdateAlert`).+ static func format(ofNotesAt page: URL, type: String?) -> ReleaseNotes.Format {+ let type = type?.lowercased() ?? "text/html"+ let pathExtension = page.pathExtension.lowercased()+ if type == "text/markdown" || type == "text/x-markdown" || pathExtension == "md" || pathExtension == "markdown" {+ return .markdown+ }+ if type == "text/plain" || pathExtension == "txt" { return .plainText }+ return .html+ }++ /// A server's reply: the body when it answered 200 within the size limit, and what it said of it.+ private struct Reply {+ var data: Data?+ var status: Int?+ var mimeType: String?+ var textEncodingName: String?+ }++ private func fetchReply(_ url: URL) async -> Reply {let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15)let reply = try? await session.bytes(for: request, delegate: SecureRedirects())- guard let (stream, response) = reply else { return (nil, nil) }+ guard let (stream, response) = reply else { return Reply() }let status = (response as? HTTPURLResponse)?.statusCode- guard status == 200, response.expectedContentLength <= Self.maximumFeedBytes else { return (nil, status) }+ var answer = Reply(status: status, mimeType: response.mimeType, textEncodingName: response.textEncodingName)+ guard status == 200, response.expectedContentLength <= Self.maximumFeedBytes else { return answer }// Reads raw bytes, giving up once the reply passes the size limit. Reading lines would be faster, but it// decodes UTF-8 and drops line endings, while an appcast may declare another encoding in its first line,@@ -192,12 +276,13 @@ public struct UpdateChecker: Sendable {do {for try await byte in stream {bytes.append(byte)- guard bytes.count <= Self.maximumFeedBytes else { return (nil, status) }+ guard bytes.count <= Self.maximumFeedBytes else { return answer }}} catch {- return (nil, status)+ return answer}- return (Data(bytes), status)+ answer.data = Data(bytes)+ return answer}}@@ -217,9 +302,24 @@ private final class SecureRedirects: NSObject, URLSessionTaskDelegate {public struct UpdateAnswer: Sendable, Hashable {public let status: UpdateStatuspublic let developer: String?+ /// What is new in the update found, when the answer itself says.+ public let notes: ReleaseNotes?+ /// The page the feed names for what is new in the update found, when it does not write it in.+ public let notesPage: URL?- public init(status: UpdateStatus, developer: String? = nil) {+ public init(status: UpdateStatus, developer: String? = nil, notes: ReleaseNotes? = nil, notesPage: URL? = nil) {self.status = statusself.developer = developer+ self.notes = notes+ self.notesPage = notesPage}}++/// What asking for an update's notes came to.+public enum ReleaseNotesLookup: Sendable, Hashable {+ case found(ReleaseNotes)+ /// None are given for this version, or there is no address of the app's own to ask: not asked again.+ case notGiven+ /// The server did not answer, so they are asked for again with the next check.+ case unanswered+}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ReleaseNotesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ReleaseNotesTests.swiftindex dbaaccc4..4b35b344 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/ReleaseNotesTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/ReleaseNotesTests.swift@@ -4,6 +4,10 @@ import Testingstruct ReleaseNotesTests {/// Each block as one line: its kind, a list item's depth, and its words.+ private func outline(_ html: String) -> [String] {+ outline(ReleaseNotes(html, format: .html))+ }+private func outline(_ notes: ReleaseNotes?) -> [String] {(notes?.blocks ?? []).map { block inswitch block {@@ -72,6 +76,22 @@ struct ReleaseNotesTests {#expect(outline(ReleaseNotes("<p>Café déjà vu, 日本語, Ελληνικά</p>", format: .html)) == ["p Café déjà vu, 日本語, Ελληνικά"])}+ @Test func readsNoEntityAPageDeclares() {+ let laughs = (1...5).map { level in+ "<!ENTITY l\(level) \"" + String(repeating: "&l\(level - 1);", count: 10) + "\">"+ }.joined()+ let bomb = "<!DOCTYPE html [<!ENTITY l0 \"laugh\">\(laughs)]><p>&l5;</p>"+ let outside = "<!DOCTYPE html [<!ENTITY secret SYSTEM \"file:///etc/passwd\">]><p>Notes &secret;</p>"++ let words = [bomb, outside].flatMap(outline)+ #expect(words.joined().count < 100)+ #expect(!words.joined().contains("root"))+ }++ @Test func readsTextWithNoTagAsAParagraph() {+ #expect(outline(ReleaseNotes("New search\nand more", format: .html)) == ["p New search and more"])+ }+@Test func keepsNothingFromNotesWithNoWords() {#expect(ReleaseNotes(" \n\t", format: .plainText) == nil)#expect(ReleaseNotes("<p> </p><img src=\"https://example.com/a.png\">", format: .html) == nil)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swiftindex a18c87ea..28626e57 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift@@ -8,6 +8,7 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {struct Reply {var status = 200var body = Data()+ var headers: [String: String]?}static let replies = Mutex<[String: Reply]>([:])@@ -21,7 +22,9 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {let host = request.url?.host() ?? ""Self.asked.withLock { $0.append(host) }guard let reply = Self.replies.withLock({ $0[host] }), let url = request.url,- let response = HTTPURLResponse(url: url, statusCode: reply.status, httpVersion: "HTTP/1.1", headerFields: nil)+ let response = HTTPURLResponse(+ url: url, statusCode: reply.status, httpVersion: "HTTP/1.1", headerFields: reply.headers+ )else {client?.urlProtocol(self, didFailWithError: URLError(.cannotFindHost))return@@ -251,4 +254,118 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {}#expect(CannedProtocol.asked.withLock { $0 }.isEmpty)}+ private var storeApp: InstalledApp {+ InstalledApp(+ url: URL(filePath: "/Applications/Notes Pro.app"), bundleIdentifier: "com.example.notes", name: "Notes Pro",+ version: "1.0", isFromAppStore: true, updateFeed: .appStore+ )+ }++ @Test func readsTheNotesInTheAnswerThatFoundTheUpdate() async {+ reply("feed.example.com", appcast("<item><enclosure url=\"https://feed.example.com/a.zip\" sparkle:version=\"200\" sparkle:shortVersionString=\"2.0\" /><description><![CDATA[<ul><li>New search</li></ul>]]></description></item>"))+ #expect(await checker.answer(for: sparkleApp()).notes == ReleaseNotes("<ul><li>New search</li></ul>", format: .html))++ reply("itunes.apple.com", #"{"resultCount":1,"results":[{"kind":"mac-software","version":"2.0","releaseNotes":"• Faster search\n• Fixed a crash"}]}"#)+ #expect(await checker.answer(for: storeApp).notes == ReleaseNotes("• Faster search\n• Fixed a crash", format: .plainText))++ let peel = InstalledApp(+ url: URL(filePath: "/Applications/Peel.app"), bundleIdentifier: "com.tuguidragos.Peel", name: "Peel",+ version: "1.0.1", updateFeed: .gitHubRelease(GitHubRelease.peel)+ )+ reply("api.github.com", ###"{"tag_name":"v1.0.2","html_url":"https://github.com/TuguiDragos/Peel/releases/tag/v1.0.2","body":"## Fixed\n- One"}"###)+ #expect(await checker.answer(for: peel).notes == ReleaseNotes("## Fixed\n- One", format: .markdown))++ let chat = InstalledApp(+ url: URL(filePath: "/Applications/Chat.app"), bundleIdentifier: "com.example.chat", name: "Chat",+ version: "1.0", updateFeed: .electron(URL(string: "https://updates.example.com/latest-mac.yml")!)+ )+ reply("updates.example.com", "version: 2.0\nreleaseNotes: Fixed a crash\nfiles:\n - url: a.zip\n")+ #expect(await checker.answer(for: chat).notes == ReleaseNotes("Fixed a crash", format: .markdown))++ reply("feed.example.com", appcast("<item><enclosure url=\"https://feed.example.com/a.zip\" sparkle:version=\"100\" sparkle:shortVersionString=\"1.0\" /><description>Old</description></item>"))+ #expect(await checker.answer(for: sparkleApp()).notes == nil, "nothing waits for an app that is up to date")+ }++ @Test func asksTheAppsOwnFeedForTheNotesOfAnUpdateHomebrewFound() async throws {+ let cask = HomebrewPackage(+ name: "editor", kind: .cask, installedVersion: "1.0", latestVersion: "2.0,200", isOutdated: true,+ appNames: ["Editor.app"]+ )+ reply("feed.example.com", appcast("<item><sparkle:version>300</sparkle:version><sparkle:shortVersionString>3.0</sparkle:shortVersionString><description>Too new</description></item><item><sparkle:version>200</sparkle:version><sparkle:shortVersionString>2.0</sparkle:shortVersionString><description>New search</description></item>"))+ let answer = await checker.answer(for: sparkleApp(), preference: .automatic, casks: [cask])++ #expect(answer.status.source == .homebrew)+ #expect(answer.notes == nil)+ #expect(CannedProtocol.asked.withLock { $0 }.isEmpty, "Homebrew's answer is found without asking anyone")+ let notes = try #require(ReleaseNotes("New search", format: .html))+ #expect(await checker.releaseNotes(for: sparkleApp(), answer: answer) == .found(notes))+ #expect(CannedProtocol.asked.withLock { $0 } == ["feed.example.com"])++ reply("feed.example.com", appcast("<item><sparkle:version>300</sparkle:version><sparkle:shortVersionString>3.0</sparkle:shortVersionString></item>"))+ #expect(await checker.releaseNotes(for: sparkleApp(), answer: answer) == .notGiven)++ reply("feed.example.com", status: 503, "")+ #expect(await checker.releaseNotes(for: sparkleApp(), answer: answer) == .unanswered)+ }++ @Test func readsTheNotesPageAFeedLinksToAsSparkleDoes() async throws {+ func answer(linking page: String, _ body: Data, type: String) async -> UpdateAnswer {+ let item = "<item><enclosure url=\"https://feed.example.com/a.zip\" sparkle:version=\"200\" sparkle:shortVersionString=\"2.0\" /><sparkle:releaseNotesLink>https://notes.example.com/\(page)</sparkle:releaseNotesLink></item>"+ CannedProtocol.replies.withLock {+ $0 = [+ "feed.example.com": .init(body: Data(appcast(item).utf8)),+ "notes.example.com": .init(body: body, headers: ["Content-Type": type]),+ ]+ }+ CannedProtocol.asked.withLock { $0 = [] }+ return await checker.answer(for: sparkleApp())+ }++ let html = await answer(linking: "2.0.html", Data("<h2>2.0</h2><ul><li>New search</li></ul>".utf8), type: "text/html")+ #expect(html.notes == nil)+ #expect(html.notesPage == URL(string: "https://notes.example.com/2.0.html"))+ let page = try #require(ReleaseNotes("<h2>2.0</h2><ul><li>New search</li></ul>", format: .html))+ #expect(await checker.releaseNotes(for: sparkleApp(), answer: html) == .found(page))+ #expect(CannedProtocol.asked.withLock { $0 } == ["feed.example.com", "notes.example.com"])++ let markdown = await answer(linking: "2.0.md", Data("## 2.0\n- New search".utf8), type: "text/plain")+ let markdownNotes = try #require(ReleaseNotes("## 2.0\n- New search", format: .markdown))+ #expect(await checker.releaseNotes(for: sparkleApp(), answer: markdown) == .found(markdownNotes))++ let text = await answer(linking: "notes", Data("New search".utf8), type: "text/plain")+ let textNotes = try #require(ReleaseNotes("New search", format: .plainText))+ #expect(await checker.releaseNotes(for: sparkleApp(), answer: text) == .found(textNotes))++ let latin = await answer(linking: "2.0.html", "<p>Café</p>".data(using: .isoLatin1)!, type: "text/html; charset=iso-8859-1")+ let latinNotes = try #require(ReleaseNotes("<p>Café</p>", format: .html))+ #expect(await checker.releaseNotes(for: sparkleApp(), answer: latin) == .found(latinNotes))+ }++ @Test func readsANotesPagesFormatInSparklesOrder() {+ let page = URL(string: "https://notes.example.com/2.0")!++ #expect(UpdateChecker.format(ofNotesAt: page.appendingPathExtension("md"), type: "text/plain") == .markdown)+ #expect(UpdateChecker.format(ofNotesAt: page, type: "text/x-markdown") == .markdown)+ #expect(UpdateChecker.format(ofNotesAt: page.appendingPathExtension("txt"), type: "text/html") == .plainText)+ #expect(UpdateChecker.format(ofNotesAt: page, type: "Text/Plain") == .plainText)+ #expect(UpdateChecker.format(ofNotesAt: page, type: nil) == .html)+ }++ @Test func asksForNoNotesWhereNoAddressOfTheAppGivesThem() async {+ reply("feed.example.com", appcast("<item><enclosure url=\"https://feed.example.com/a.zip\" sparkle:version=\"200\" sparkle:shortVersionString=\"2.0\" /><link>https://feed.example.com/product</link></item>"))+ let product = await checker.answer(for: sparkleApp())+ #expect(product.status.releaseNotes == URL(string: "https://feed.example.com/product"), "the product page stays the link")+ #expect(product.notesPage == nil)+ #expect(await checker.releaseNotes(for: sparkleApp(), answer: product) == .notGiven)+ #expect(CannedProtocol.asked.withLock { $0 } == ["feed.example.com"], "only the check itself")++ reply("example.com", "<p>A product page</p>")+ let named = InstalledApp(url: URL(filePath: "/Applications/Example.app"), bundleIdentifier: "com.example.app", name: "Example", version: "1.0")+ let homepage = UpdateAnswer(status: .updateAvailable(version: "2.0", source: .homebrew, releaseNotes: URL(string: "https://example.com")))+ #expect(await checker.releaseNotes(for: named, answer: homepage) == .notGiven)+ let store = UpdateAnswer(status: .updateAvailable(version: "2.0", source: .appStore, releaseNotes: URL(string: "https://example.com/app")))+ #expect(await checker.releaseNotes(for: storeApp, answer: store) == .notGiven)+ #expect(await checker.releaseNotes(for: sparkleApp(), answer: UpdateAnswer(status: .upToDate)) == .notGiven)+ #expect(CannedProtocol.asked.withLock { $0 }.isEmpty)+ }}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UpdateTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UpdateTests.swiftindex 9d968c61..7344b433 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/UpdateTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/UpdateTests.swift@@ -140,7 +140,7 @@ struct AppcastTests {"""let item = try #require(latestItem(in: feed))#expect(item.releaseNotes != nil)- let links: [(language: String, url: URL)] = [+ let links: [(language: String, value: URL)] = [("de", URL(string: "https://example.com/de.html")!), ("", URL(string: "https://example.com/en.html")!),("fr", URL(string: "https://example.com/fr.html")!),]@@ -189,6 +189,36 @@ struct AppcastTests {#expect(item.version == "3")}++ @Test func readsTheNotesAFeedWritesInsideAnItem() throws {+ let feed = """+ <rss xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle"><channel>+ <description>The channel's own words</description>+ <item><sparkle:version>2</sparkle:version>+ <description><![CDATA[<ul><li>New search</li></ul>]]></description>+ </item></channel></rss>+ """++ #expect(try #require(latestItem(in: feed)).notes == ReleaseNotes("<ul><li>New search</li></ul>", format: .html))+ }++ @Test(arguments: [("plain-text", ReleaseNotes.Format.plainText), ("Markdown", .markdown), ("html", .html)])+ func readsTheFormatAFeedGivesItsNotes(_ name: String, _ format: ReleaseNotes.Format) throws {+ let feed = """+ <rss xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle"><channel><item>+ <sparkle:version>2</sparkle:version><description sparkle:format="\(name)">New search</description>+ </item></channel></rss>+ """++ #expect(try #require(latestItem(in: feed)).notes?.format == format)+ }++ @Test func picksTheNotesInTheReadersLanguage() {+ let notes: [(language: String, value: String)] = [("de", "Neue Suche"), ("", "New search"), ("fr", "Nouvelle recherche")]++ #expect(Appcast.preferred(notes, languages: ["fr-FR", "en"]) == "Nouvelle recherche")+ #expect(Appcast.preferred(notes, languages: ["ro-RO", "en"]) == "New search")+ }}struct ElectronUpdaterTests {@@ -212,6 +242,19 @@ struct ElectronUpdaterTests {let feed = "version: 1.33.0\nfiles:\n - url: TuneIn-1.33.0-universal-mac.zip\n version: 9.9.9\nreleaseDate: '2026-03-30T19:23:16.416Z'\n"#expect(ElectronUpdater.version(fromFeed: feed) == "1.33.0")}++ @Test func readsTheNotesAnElectronFeedWrites() {+ func notes(_ line: String) -> String? {+ ElectronUpdater.releaseNotes(fromFeed: "version: 2.0\n\(line)files:\n - url: a.zip\n")?.text+ }++ #expect(notes("releaseNotes: Fixed a crash\n") == "Fixed a crash")+ #expect(notes("releaseNotes: 'It''s fixed'\n") == "It's fixed")+ #expect(notes("releaseNotes: \"Line one\\nLine \\\"two\\\"\"\n") == "Line one\nLine \"two\"")+ #expect(notes("releaseNotes: |-\n ## 2.0\n - One\n\n - Two\n") == "## 2.0\n- One\n\n- Two")+ #expect(notes("releaseNotes: >-\n One line\n goes on\n") == "One line goes on")+ #expect(notes("") == nil)+ }}struct AppStoreLookupTests {