Prune and preserve necessary updates in generate_appcast (#2218)

We preserve a batch of updates for each branch point (defined by an update's {majorVersion, minSystemVersion, maxSystemVersion, channel}). The latest for each branch point is used for generating delta updates.

We prune older update items that are no longer needed in the feed or needed for generating delta updates from newer items. We move pruned update files into a separate hidden directory, which is later garbage collected after a couple weeks based on each file's last modification date.

To insert new update items that are older than the latest update in the feed, --version flag needs to be used.

The overall goal is to have the feed only keep a small window of updates to serve to the user. This will also ease future processing generate_appcast needs to do and ensure the cache's directory doesn't blow up by pruning old updates.
This commit is contained in:
Zorg authored and GitHub committed 2022-08-07 19:13:20 -07:00
1 parent 6a69f26dcc
commit 37ef179284
5 files changed
+494 -113

No files matched your search

+334 -62
View File
@@ -11,77 +11,205 @@ func makeError(code: SUError, _ description: String) -> NSError {
])
}
func makeAppcast(archivesSourceDir: URL, cacheDirectory cacheDir: URL, keys: PrivateKeys, versions: Set<String>?, maximumDeltas: Int, deltaCompressionModeDescription: String, deltaCompressionLevel: UInt8, disableNestedCodeCheck: Bool, verbose: Bool) throws -> [String: [ArchiveItem]] {
let comparator = SUStandardVersionComparator()
typealias UpdateVersion = String
typealias FeedName = String
struct Appcast {
let inferredAppName: String
let versionsInFeed: [UpdateVersion]
let ignoredVersionsToInsert: Set<UpdateVersion>
let archives: [UpdateVersion: ArchiveItem]
let deltaPathsUsed: Set<String>
let deltaFromVersionsUsed: Set<UpdateVersion>
}
func makeAppcasts(archivesSourceDir: URL, outputPathURL: URL?, cacheDirectory cacheDir: URL, keys: PrivateKeys, versions: Set<String>?, maxVersionsPerBranchInFeed: Int, newChannel: String?, majorVersion: String?, maximumDeltas: Int, deltaCompressionModeDescription: String, deltaCompressionLevel: UInt8, disableNestedCodeCheck: Bool, downloadURLPrefix: URL?, releaseNotesURLPrefix: URL?, verbose: Bool) throws -> [FeedName: Appcast] {
let standardComparator = SUStandardVersionComparator()
let descendingVersionComparator: (String, String) -> Bool = {
return standardComparator.compareVersion($0, toVersion: $1) == .orderedDescending
}
let allUpdates = (try unarchiveUpdates(archivesSourceDir: archivesSourceDir, archivesDestDir: cacheDir, disableNestedCodeCheck: disableNestedCodeCheck, verbose: verbose))
.sorted(by: {
.orderedDescending == comparator.compareVersion($0.version, toVersion: $1.version)
})
.sorted(by: { descendingVersionComparator($0.version, $1.version) })
if allUpdates.count == 0 {
throw makeError(code: .noUpdateError, "No usable archives found in \(archivesSourceDir.path)")
}
var updatesByAppcast: [String: [ArchiveItem]] = [:]
let group = DispatchGroup()
// Apply download and release notes prefixes
for update in allUpdates {
group.enter()
DispatchQueue.global().async {
if let privateDSAKey = keys.privateDSAKey {
do {
update.dsaSignature = try dsaSignature(path: update.archivePath, privateDSAKey: privateDSAKey)
} catch {
print(update, error)
}
} else if update.supportsDSA {
print("Note: did not sign with legacy DSA \(update.archivePath.path) because private DSA key file was not specified")
}
if let publicEdKey = update.publicEdKey {
if let privateEdKey = keys.privateEdKey, let expectedPublicKey = keys.publicEdKey {
if publicEdKey == expectedPublicKey {
do {
update.edSignature = try edSignature(path: update.archivePath, publicEdKey: publicEdKey, privateEdKey: privateEdKey)
} catch {
print(update, error)
}
} else {
print("Warning: SUPublicEDKey in the app \(update.archivePath.path) does not match key EdDSA in the Keychain. Run generate_keys and update Info.plist to match")
}
} else {
print("Warning: could not sign \(update.archivePath.path) due to lack of private EdDSA key")
}
}
group.leave()
}
let appcastFile = update.feedURL?.lastPathComponent ?? "appcast.xml"
if updatesByAppcast[appcastFile] == nil {
updatesByAppcast[appcastFile] = []
}
updatesByAppcast[appcastFile]!.append(update)
update.downloadUrlPrefix = downloadURLPrefix
update.releaseNotesURLPrefix = releaseNotesURLPrefix
}
// If a (single) output filename was specified on the command-line, but more than one
// appcast file was found in the archives, then it's an error.
if let outputPathURL = outputPathURL, allUpdates.count > 1 {
throw makeError(code: .appcastError, "Cannot write to \(outputPathURL.path): multiple appcasts found")
}
for (_, updates) in updatesByAppcast {
var latestUpdatePerOS: [String: ArchiveItem] = [:]
// Group updates by appcast feed
var updatesByAppcast: [FeedName: [ArchiveItem]] = [:]
for update in allUpdates {
let appcastFile = update.feedURL?.lastPathComponent ?? "appcast.xml"
updatesByAppcast[appcastFile, default: []].append(update)
}
let group = DispatchGroup()
var appcastByFeed: [FeedName: Appcast] = [:]
for (feed, updates) in updatesByAppcast {
var archivesTable: [UpdateVersion: ArchiveItem] = [:]
for update in updates {
// If the new versions are specified, ignore everything else
if let versions = versions, !versions.contains(update.version) {
archivesTable[update.version] = update
}
let feedURL = outputPathURL ?? archivesSourceDir.appendingPathComponent(feed)
guard let reachable = try? feedURL.checkResourceIsReachable(), reachable else {
continue
}
// Find all the update versions & branches from our existing feed
let feedUpdateBranches: [UpdateVersion: UpdateBranch] = try readAppcast(archives: archivesTable, appcastURL: feedURL)
// Find which versions are new and old but aren't in the feed and that we should ignore/skip
var ignoredVersionsToInsert: Set<UpdateVersion> = Set()
var ignoredOldVersions: Set<UpdateVersion> = Set()
if let versions = versions {
// Note for this path we may be adding old updates to ignoredVersionsToInsert too.
// It is difficult to differentiate between old and potential new updates that aren't in the feed
// As a consequence, some old updates may not be pruned with this option.
for update in updates {
if feedUpdateBranches[update.version] == nil && !versions.contains(update.version) {
ignoredVersionsToInsert.insert(update.version)
}
}
} else {
// If the user doesn't specify which versions to generate updates for,
// then by default we ignore generating updates that are less than the latest update in the existing feed
for latestUpdateCandidate in updates {
if feedUpdateBranches[latestUpdateCandidate.version] != nil {
// Found the latest update in the feed
let latestUpdateVersionInFeed = latestUpdateCandidate.version
// Filter out any new potential updates that are less than our latest update in our existing feed
for update in updates {
if feedUpdateBranches[update.version] == nil && descendingVersionComparator(latestUpdateVersionInFeed, update.version) {
ignoredOldVersions.insert(update.version)
}
}
break
}
}
}
// Find new update versions and their branches
var newUpdateBranches: [UpdateVersion: UpdateBranch] = [:]
do {
for update in updates {
if !ignoredOldVersions.contains(update.version) && !ignoredVersionsToInsert.contains(update.version) && feedUpdateBranches[update.version] == nil {
newUpdateBranches[update.version] = UpdateBranch(minimumSystemVersion: update.minimumSystemVersion, maximumSystemVersion: nil, minimumAutoupdateVersion: majorVersion, channel: newChannel)
}
}
}
// Compute latest versions per distinct branch we need to keep
// Also compute the batch of recent versions we should preserve/add in the feed
let versionsPreservedInFeed: [UpdateVersion]
var latestVersionPerBranch: Set<UpdateVersion> = []
do {
// Group update versions by branch
var updatesGroupedByBranch: [UpdateBranch: [UpdateVersion]] = [:]
for (version, branch) in feedUpdateBranches {
updatesGroupedByBranch[branch, default: []].append(version)
}
for (version, branch) in newUpdateBranches {
updatesGroupedByBranch[branch, default: []].append(version)
}
// Grab latest batch of versions per branch
for (branch, versions) in updatesGroupedByBranch {
updatesGroupedByBranch[branch] = Array(versions.sorted(by: descendingVersionComparator).prefix(maxVersionsPerBranchInFeed))
}
// Remove extraneous versions for branches that have converged
for (branch, versions) in updatesGroupedByBranch {
guard branch.channel != nil else {
continue
}
let defaultChannelBranch = UpdateBranch(minimumSystemVersion: branch.minimumSystemVersion, maximumSystemVersion: branch.maximumSystemVersion, minimumAutoupdateVersion: branch.minimumAutoupdateVersion, channel: nil)
guard let defaultChannelVersions = updatesGroupedByBranch[defaultChannelBranch] else {
continue
}
if descendingVersionComparator(defaultChannelVersions[0], versions[0]) {
updatesGroupedByBranch[branch] = [versions[0]]
}
}
// Grab latest versions per branch
var latestBatchOfVersionsPerBranch: Set<UpdateVersion> = []
for (_, versions) in updatesGroupedByBranch {
latestBatchOfVersionsPerBranch.formUnion(versions)
latestVersionPerBranch.insert(versions[0])
}
versionsPreservedInFeed = Array(latestBatchOfVersionsPerBranch).sorted(by: descendingVersionComparator)
}
// Update signatures for the latest updates we keep in the feed
for version in versionsPreservedInFeed {
guard let update = archivesTable[version] else {
continue
}
// items are ordered starting latest first
let os = update.minimumSystemVersion
if latestUpdatePerOS[os] == nil {
latestUpdatePerOS[os] = update
group.enter()
DispatchQueue.global().async {
if let privateDSAKey = keys.privateDSAKey {
do {
update.dsaSignature = try dsaSignature(path: update.archivePath, privateDSAKey: privateDSAKey)
} catch {
print(update, error)
}
} else if update.supportsDSA {
print("Note: did not sign with legacy DSA \(update.archivePath.path) because private DSA key file was not specified")
}
if let publicEdKey = update.publicEdKey {
if let privateEdKey = keys.privateEdKey, let expectedPublicKey = keys.publicEdKey {
if publicEdKey == expectedPublicKey {
do {
update.edSignature = try edSignature(path: update.archivePath, publicEdKey: publicEdKey, privateEdKey: privateEdKey)
} catch {
print(update, error)
}
} else {
print("Warning: SUPublicEDKey in the app \(update.archivePath.path) does not match key EdDSA in the Keychain. Run generate_keys and update Info.plist to match")
}
} else {
print("Warning: could not sign \(update.archivePath.path) due to lack of private EdDSA key")
}
}
group.leave()
}
}
for (_, latestItem) in latestUpdatePerOS {
// Generate delta updates from the latest updates we keep
// Keep track of which delta archives we need referenced in the appcast still
var deltaPathsUsed: Set<String> = []
var deltaFromVersionsUsed: Set<UpdateVersion> = []
for version in versionsPreservedInFeed {
guard let latestItem = archivesTable[version] else {
continue
}
// We only generate deltas for the latest version per branch,
// but we still wanted to record the used delta updates for a batch of recent updates
let generatingDeltas = latestVersionPerBranch.contains(version)
var numDeltas = 0
let appBaseName = latestItem.appPath.deletingPathExtension().lastPathComponent
for item in updates {
@@ -90,9 +218,10 @@ func makeAppcast(archivesSourceDir: URL, cacheDirectory cacheDir: URL, keys: Pri
}
// No downgrades
if .orderedAscending != comparator.compareVersion(item.version, toVersion: latestItem.version) {
if .orderedAscending != standardComparator.compareVersion(item.version, toVersion: latestItem.version) {
continue
}
// Old version will not be able to verify the new version
if !item.supportsDSA && item.publicEdKey == nil {
continue
@@ -100,6 +229,15 @@ func makeAppcast(archivesSourceDir: URL, cacheDirectory cacheDir: URL, keys: Pri
let deltaBaseName = appBaseName + latestItem.version + "-" + item.version
let deltaPath = archivesSourceDir.appendingPathComponent(deltaBaseName).appendingPathExtension("delta")
deltaPathsUsed.insert(deltaPath.path)
deltaFromVersionsUsed.insert(item.version)
numDeltas += 1
if !generatingDeltas {
continue
}
var delta: DeltaUpdate
let ignoreMarkerPath = cacheDir.appendingPathComponent(deltaPath.lastPathComponent).appendingPathExtension(".ignore")
@@ -128,7 +266,7 @@ func makeAppcast(archivesSourceDir: URL, cacheDirectory cacheDir: URL, keys: Pri
// Decide the most appropriate delta version
let deltaVersion: SUBinaryDeltaMajorVersion
if let frameworkVersion = item.frameworkVersion {
switch comparator.compareVersion(frameworkVersion, toVersion: "2010") {
switch standardComparator.compareVersion(frameworkVersion, toVersion: "2010") {
case .orderedSame:
fallthrough
case .orderedDescending:
@@ -180,8 +318,6 @@ func makeAppcast(archivesSourceDir: URL, cacheDirectory cacheDir: URL, keys: Pri
delta = DeltaUpdate(fromVersion: item.version, archivePath: deltaPath)
}
numDeltas += 1
// Require delta to be a bit smaller
if delta.fileSize / 7 > latestItem.fileSize / 8 {
markDeltaAsIgnored(delta: delta, markerPath: ignoreMarkerPath)
@@ -214,11 +350,147 @@ func makeAppcast(archivesSourceDir: URL, cacheDirectory cacheDir: URL, keys: Pri
}
}
}
let inferredAppName = updates[0].appPath.deletingPathExtension().lastPathComponent
let appcast = Appcast(inferredAppName: inferredAppName, versionsInFeed: versionsPreservedInFeed, ignoredVersionsToInsert: ignoredVersionsToInsert, archives: archivesTable, deltaPathsUsed: deltaPathsUsed, deltaFromVersionsUsed: deltaFromVersionsUsed)
appcastByFeed[feed] = appcast
}
group.wait()
return updatesByAppcast
return appcastByFeed
}
func pruneUpdatesFromAppcast(archivesSourceDir: URL, prunedDirectory: URL, cacheDirectory: URL, appcast: Appcast) -> Int {
let fileManager = FileManager.default
let suFileManager = SUFileManager()
// Create pruned updates directory if needed
var createdPrunedDirectory = false
let makePrunedFilesDirectory: () -> Bool = {
guard !createdPrunedDirectory else {
return true
}
if fileManager.fileExists(atPath: prunedDirectory.path) {
createdPrunedDirectory = true
return true
}
do {
try fileManager.createDirectory(at: prunedDirectory, withIntermediateDirectories: false)
createdPrunedDirectory = true
return true
} catch {
print("Warning: failed to create \(prunedDirectory.lastPathComponent) in \(archivesSourceDir.lastPathComponent): \(error)")
return false
}
}
var prunedItemsCount = 0
// Prune all unused update items
let versionsInFeedSet = Set(appcast.versionsInFeed)
for (version, update) in appcast.archives {
guard !versionsInFeedSet.contains(version) && !appcast.deltaFromVersionsUsed.contains(version) && !appcast.ignoredVersionsToInsert.contains(version) else {
continue
}
let archivePath = update.archivePath
guard makePrunedFilesDirectory() else {
return prunedItemsCount
}
do {
try suFileManager.updateModificationAndAccessTimeOfItem(at: archivePath)
} catch {
print("Warning: failed to update modification time for \(archivePath.path): \(error)")
}
do {
try fileManager.moveItem(at: archivePath, to: prunedDirectory.appendingPathComponent(archivePath.lastPathComponent))
} catch {
print("Warning: failed to move \(archivePath.lastPathComponent) to \(prunedDirectory.lastPathComponent): \(error)")
}
prunedItemsCount += 1
// Prune cache for the update
let appCachePath = update.appPath.deletingLastPathComponent()
let _ = try? fileManager.removeItem(at: appCachePath)
}
// Prune all unused delta items in the archives directory
// We will be missing out on ignore markers in the cache for delta items because they're difficult to fetch
// However they are zero-sized so they don't take much space anyway
do {
let directoryContents = try fileManager.contentsOfDirectory(atPath: archivesSourceDir.path)
for filename in directoryContents {
guard filename.hasSuffix(".delta") else {
continue
}
let deltaURL = archivesSourceDir.appendingPathComponent(filename)
guard !appcast.deltaPathsUsed.contains(deltaURL.path) else {
continue
}
guard makePrunedFilesDirectory() else {
return prunedItemsCount
}
prunedItemsCount += 1
do {
try suFileManager.updateModificationAndAccessTimeOfItem(at: deltaURL)
} catch {
print("Warning: Failed to update modification time for \(deltaURL.lastPathComponent): \(error)")
}
do {
try fileManager.moveItem(at: deltaURL, to: prunedDirectory.appendingPathComponent(filename))
} catch {
print("Warning: failed to move \(deltaURL.lastPathComponent) to \(prunedDirectory.lastPathComponent): \(error)")
}
}
} catch {
print("Warning: failed to list contents of \(archivesSourceDir.lastPathComponent) during pruning: \(error)")
}
// Garbage collect the pruned updates directory
do {
let directoryContents = try fileManager.contentsOfDirectory(atPath: prunedDirectory.path)
// Delete files that have roughly not been touched for 14 days
let prunedFileDeletionInterval: TimeInterval = 86400 * 14
let currentDate = Date()
for filename in directoryContents {
guard !filename.hasPrefix(".") else {
continue
}
let fileURL = prunedDirectory.appendingPathComponent(filename)
if let resourceValues = try? fileURL.resourceValues(forKeys: [.contentModificationDateKey]),
let lastModificationDate = resourceValues.contentModificationDate {
if currentDate.timeIntervalSince(lastModificationDate) >= prunedFileDeletionInterval {
do {
try fileManager.removeItem(at: fileURL)
} catch {
print("Warning: failed to delete old pruned file \(prunedDirectory.lastPathComponent)/\(fileURL.lastPathComponent): \(error)")
}
}
}
}
} catch {
// Nothing to log for failing to fetch prunedDirectory
}
return prunedItemsCount
}
func markDeltaAsIgnored(delta: DeltaUpdate, markerPath: URL) {
+7
View File
@@ -6,6 +6,13 @@
import Foundation
import UniformTypeIdentifiers
struct UpdateBranch: Hashable {
let minimumSystemVersion: String?
let maximumSystemVersion: String?
let minimumAutoupdateVersion: String?
let channel: String?
}
class DeltaUpdate {
let fromVersion: String
let archivePath: URL
+1
View File
@@ -11,4 +11,5 @@
#import "SUSignatures.h"
#import "SUCodeSigningVerifier.h"
#import "SPUInstallationType.h"
#import "SUFileManager.h"
#import "ed25519.h" // Run `git submodule update --init` if you get an error here
+129 -17
View File
@@ -49,8 +49,91 @@ func extractVersion(parent: XMLNode) -> String? {
return nil
}
func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem], newVersions: Set<String>?, maxNewVersionsInFeed: Int, fullReleaseNotesLink: String?, maxCDATAThreshold: Int, link: String?, newChannel: String?, majorVersion: String?, ignoreSkippedUpgradesBelowVersion: String?, phasedRolloutInterval: Int?, criticalUpdateVersion: String?, informationalUpdateVersions: [String]?) throws -> (numNewUpdates: Int, numExistingUpdates: Int) {
let appBaseName = updates[0].appPath.deletingPathExtension().lastPathComponent
func readAppcast(archives: [String: ArchiveItem], appcastURL: URL) throws -> [String: UpdateBranch] {
let options: XMLNode.Options = [
XMLNode.Options.nodeLoadExternalEntitiesNever,
XMLNode.Options.nodePreserveCDATA,
XMLNode.Options.nodePreserveWhitespace,
]
let doc = try XMLDocument(contentsOf: appcastURL, options: options)
let rootNodes = try doc.nodes(forXPath: "/rss")
if rootNodes.count != 1 {
throw makeError(code: .appcastError, "Weird XML? \(appcastURL.path)")
}
let root = rootNodes[0] as! XMLElement
let channelNodes = try root.nodes(forXPath: "channel")
if channelNodes.count == 0 {
throw makeError(code: .appcastError, "Weird Feed? No channels: \(appcastURL.path)")
}
let channel = channelNodes[0] as! XMLElement
guard let itemNodes = try? channel.nodes(forXPath: "item") else {
return [:]
}
var updateBranches: [String: UpdateBranch] = [:]
for item in itemNodes {
guard let item = item as? XMLElement else {
continue
}
let version: String?
if let versionElement = findElement(name: SUAppcastElementVersion, parent: item) {
version = versionElement.stringValue
} else if let enclosure = findElement(name: "enclosure", parent: item), let versionAttribute = enclosure.attribute(forName: SUAppcastAttributeVersion) {
version = versionAttribute.stringValue
} else {
version = nil
}
guard let version = version else {
continue
}
let minimumSystemVersion: String?
if let minVer = findElement(name: SUAppcastElementMinimumSystemVersion, parent: item) {
minimumSystemVersion = minVer.stringValue
} else if let archive = archives[version] {
minimumSystemVersion = archive.minimumSystemVersion
} else {
minimumSystemVersion = nil
}
let maximumSystemVersion: String?
if let maxVer = findElement(name: SUAppcastElementMaximumSystemVersion, parent: item) {
maximumSystemVersion = maxVer.stringValue
} else {
maximumSystemVersion = nil
}
let minimumAutoupdateVersion: String?
if let minimumAutoupdateVersionElement = findElement(name: SUAppcastElementMinimumAutoupdateVersion, parent: item) {
minimumAutoupdateVersion = minimumAutoupdateVersionElement.stringValue
} else {
minimumAutoupdateVersion = nil
}
let sparkleChannel: String?
if let sparkleChannelElement = findElement(name: SUAppcastElementChannel, parent: item) {
sparkleChannel = sparkleChannelElement.stringValue
} else {
sparkleChannel = nil
}
let updateBranch = UpdateBranch(minimumSystemVersion: minimumSystemVersion, maximumSystemVersion: maximumSystemVersion, minimumAutoupdateVersion: minimumAutoupdateVersion, channel: sparkleChannel)
updateBranches[version] = updateBranch
}
return updateBranches
}
func writeAppcast(appcastDestPath: URL, appcast: Appcast, fullReleaseNotesLink: String?, maxCDATAThreshold: Int, link: String?, newChannel: String?, majorVersion: String?, ignoreSkippedUpgradesBelowVersion: String?, phasedRolloutInterval: Int?, criticalUpdateVersion: String?, informationalUpdateVersions: [String]?) throws -> (numNewUpdates: Int, numExistingUpdates: Int, numUpdatesRemoved: Int) {
let appBaseName = appcast.inferredAppName
let sparkleNS = "http://www.andymatuschak.org/xml-namespaces/sparkle"
@@ -78,8 +161,45 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem], newVersions: Set
}
let root = rootNodes[0] as! XMLElement
let channelNodes = try root.nodes(forXPath: "channel")
var numUpdatesRemoved: Int = 0
if channelNodes.count > 0 {
channel = channelNodes[0] as! XMLElement
// Enumerate through all existing update items and remove any that we aren't going to keep
let versionsInFeedSet = Set(appcast.versionsInFeed)
var nodesToRemove: [XMLElement] = []
if let itemNodes = try? channel.nodes(forXPath: "item") {
for item in itemNodes {
guard let item = item as? XMLElement else {
continue
}
let version: String?
if let versionElement = findElement(name: SUAppcastElementVersion, parent: item) {
version = versionElement.stringValue
} else if let enclosure = findElement(name: "enclosure", parent: item), let versionAttribute = enclosure.attribute(forName: SUAppcastAttributeVersion) {
version = versionAttribute.stringValue
} else {
version = nil
}
guard let version = version else {
continue
}
if !versionsInFeedSet.contains(version) {
nodesToRemove.append(item)
}
}
// Remove old nodes from highest-to-lowest index order
for node in nodesToRemove.reversed() {
channel.removeChild(at: node.index)
}
numUpdatesRemoved = nodesToRemove.count
}
} else {
channel = XMLElement(name: "channel")
channel.addChild(XMLElement.element(withName: "title", stringValue: appBaseName) as! XMLElement)
@@ -92,7 +212,11 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem], newVersions: Set
let versionComparator = SUStandardVersionComparator()
var numItems = 0
for update in updates {
for version in appcast.versionsInFeed {
guard let update = appcast.archives[version] else {
continue
}
var item: XMLElement
var existingItems = try channel.nodes(forXPath: "item[enclosure[@\(SUAppcastAttributeVersion)=\"\(update.version)\"]]")
@@ -102,20 +226,8 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem], newVersions: Set
}
let createNewItem = (existingItems.count == 0)
// Update all old items, but aim for less than maxNewVersionsInFeed in new feeds,
// unless the user specifies which versions they want to generate
if createNewItem {
if let newVersions = newVersions {
if !newVersions.contains(update.version) {
continue
}
} else {
if numItems >= maxNewVersionsInFeed {
continue
}
}
numNewUpdates += 1
} else {
numExistingUpdates += 1
@@ -359,5 +471,5 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem], newVersions: Set
_ = try XMLDocument(data: docData, options: XMLNode.Options()); // Verify that it was generated correctly, which does not always happen!
try docData.write(to: appcastDestPath)
return (numNewUpdates, numExistingUpdates)
return (numNewUpdates, numExistingUpdates, numUpdatesRemoved)
}
+23 -34
View File
@@ -52,8 +52,9 @@ struct GenerateAppcast: ParsableCommand {
static let programName = "generate_appcast"
static let programNamePath: String = CommandLine.arguments.first ?? "./\(programName)"
static let cacheDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("Sparkle_generate_appcast")
static let prunedDirectoryName = ".pruned-updates"
static let DEFAULT_MAX_NEW_VERSIONS_IN_FEED = 5
static let DEFAULT_MAX_VERSIONS_PER_BRANCH_IN_FEED = 3
static let DEFAULT_MAXIMUM_DELTAS = 5
@Option(help: ArgumentHelp("The account name in your keychain associated with your private EdDSA (ed25519) key to use for signing new updates."))
@@ -86,10 +87,10 @@ struct GenerateAppcast: ParsableCommand {
@Option(name: .long, help: ArgumentHelp("A URL to the application's website which Sparkle may use for directing users to if they cannot download a new update from within the application. This will be used for new generated update items. By default, no product link is used.", valueName: "link"))
var link: String?
@Option(name: .long, help: ArgumentHelp("An optional comma delimited list of application versions (specified by CFBundleVersion) to generate new update items for. By default, new update items are inferred from the available archives and are only generated if they are in the latest \(DEFAULT_MAX_NEW_VERSIONS_IN_FEED) updates in the appcast.", valueName: "versions"), transform: { Set($0.components(separatedBy: ",")) })
@Option(name: .long, help: ArgumentHelp("An optional comma delimited list of application versions (specified by CFBundleVersion) to generate new update items for. By default, new update items are inferred from the available archives. Use this option if you need to insert old updates in the feed at a different branch point (for example with a different minimum OS requirement).", valueName: "versions"), transform: { Set($0.components(separatedBy: ",")) })
var versions: Set<String>?
@Option(name: .long, help: ArgumentHelp("The maximum number of delta items to create for the latest update for each minimum required operating system.", valueName: "maximum-deltas"))
@Option(name: .long, help: ArgumentHelp("The maximum number of delta items to create for the latest update for each branch point (for example with a different minimum OS requirement).", valueName: "maximum-deltas"))
var maximumDeltas: Int = DEFAULT_MAXIMUM_DELTAS
@Option(name: .long, help: ArgumentHelp(COMPRESSION_METHOD_ARGUMENT_DESCRIPTION, valueName: "delta-compression"))
@@ -122,11 +123,10 @@ struct GenerateAppcast: ParsableCommand {
@Argument(help: "The path to the directory containing the update archives and delta files.", transform: { URL(fileURLWithPath: $0, isDirectory: true) })
var archivesSourceDir: URL
// New update items are only generated if they are in the latest maxNewVersionsInFeed updates in the appcast
// If the `versions` to generate is specified however, this counter has no effect.
// Keep this option hidden from the user for now
// Rough indication of how many versions we should keep in the feed per branch point
// Keep this option hidden from the user
@Option(name: .long, help: .hidden)
var maxNewVersionsInFeed: Int = DEFAULT_MAX_NEW_VERSIONS_IN_FEED
var maxVersionsPerBranchInFeed: Int = DEFAULT_MAX_VERSIONS_PER_BRANCH_IN_FEED
@Flag(help: .hidden)
var verbose: Bool = false
@@ -144,7 +144,7 @@ struct GenerateAppcast: ParsableCommand {
Appcast files and deltas will be written to the archives directory.
If an appcast file is already present in the archives directory, that file will be re-used and updated with new entries.
Old entries in the appcast are kept intact. Otherwise, a new appcast file will be generated and written.
Old entries in the appcast that are still needed are kept intact. Otherwise, a new appcast file will be generated and written.
.html files that have the same filename as an archive (except for the file extension) will be used for release notes for that item.
If the contents of these files are short (< \(DEFAULT_MAX_CDATA_THRESHOLD) characters) and do not include a DOCTYPE or body tags, they will be treated as embedded CDATA release notes.
@@ -168,6 +168,8 @@ struct GenerateAppcast: ParsableCommand {
Extracted archives are cached in \((cacheDirectory.path as NSString).abbreviatingWithTildeInPath) to avoid re-computation in subsequent runs.
Old updates are automatically pruned from the generated appcast feed and their update files are moved to \(prunedDirectoryName). Old update files in this directory are deleted after 2 weeks.
Note that \(programName) does not support package-based (.pkg) updates.
""")
@@ -258,45 +260,32 @@ struct GenerateAppcast: ParsableCommand {
let keys = loadPrivateKeys(account, privateDSAKey, privateEdKeyString)
do {
let allUpdates = try makeAppcast(archivesSourceDir: archivesSourceDir, cacheDirectory: GenerateAppcast.cacheDirectory, keys: keys, versions: versions, maximumDeltas: maximumDeltas, deltaCompressionModeDescription: deltaCompression, deltaCompressionLevel: deltaCompressionLevel, disableNestedCodeCheck: disableNestedCodeCheck, verbose: verbose)
let appcastsByFeed = try makeAppcasts(archivesSourceDir: archivesSourceDir, outputPathURL: outputPathURL, cacheDirectory: GenerateAppcast.cacheDirectory, keys: keys, versions: versions, maxVersionsPerBranchInFeed: maxVersionsPerBranchInFeed, newChannel: channel, majorVersion: majorVersion, maximumDeltas: maximumDeltas, deltaCompressionModeDescription: deltaCompression, deltaCompressionLevel: deltaCompressionLevel, disableNestedCodeCheck: disableNestedCodeCheck, downloadURLPrefix: downloadURLPrefix, releaseNotesURLPrefix: releaseNotesURLPrefix, verbose: verbose)
// If a URL prefix was provided, set on the archive items
if downloadURLPrefix != nil || releaseNotesURLPrefix != nil {
for (_, archiveItems) in allUpdates {
for archiveItem in archiveItems {
if let downloadURLPrefix = downloadURLPrefix {
archiveItem.downloadUrlPrefix = downloadURLPrefix
}
if let releaseNotesURLPrefix = releaseNotesURLPrefix {
archiveItem.releaseNotesURLPrefix = releaseNotesURLPrefix
}
}
}
}
let prunedDirectory = archivesSourceDir.appendingPathComponent(GenerateAppcast.prunedDirectoryName)
// If a (single) output filename was specified on the command-line, but more than one
// appcast file was found in the archives, then it's an error.
if let outputPathURL = outputPathURL,
allUpdates.count > 1 {
print("Cannot write to \(outputPathURL.path): multiple appcasts found")
throw ExitCode(1)
}
for (appcastFile, updates) in allUpdates {
for (appcastFile, appcast) in appcastsByFeed {
// If an output filename was specified, use it.
// Otherwise, use the name of the appcast file found in the archive.
let appcastDestPath = outputPathURL ?? URL(fileURLWithPath: appcastFile,
relativeTo: archivesSourceDir)
// Write the appcast
let (numNewUpdates, numExistingUpdates) = try writeAppcast(appcastDestPath: appcastDestPath, updates: updates, newVersions: versions, maxNewVersionsInFeed: maxNewVersionsInFeed, fullReleaseNotesLink: fullReleaseNotesURL, maxCDATAThreshold: maxCDATAThreshold, link: link, newChannel: channel, majorVersion: majorVersion, ignoreSkippedUpgradesBelowVersion: ignoreSkippedUpgradesBelowVersion, phasedRolloutInterval: phasedRolloutInterval, criticalUpdateVersion: criticalUpdateVersion, informationalUpdateVersions: informationalUpdateVersions)
let (numNewUpdates, numExistingUpdates, numUpdatesRemoved) = try writeAppcast(appcastDestPath: appcastDestPath, appcast: appcast, fullReleaseNotesLink: fullReleaseNotesURL, maxCDATAThreshold: maxCDATAThreshold, link: link, newChannel: channel, majorVersion: majorVersion, ignoreSkippedUpgradesBelowVersion: ignoreSkippedUpgradesBelowVersion, phasedRolloutInterval: phasedRolloutInterval, criticalUpdateVersion: criticalUpdateVersion, informationalUpdateVersions: informationalUpdateVersions)
// Inform the user, pluralizing "update" if necessary
let pluralizeUpdates = { $0 == 1 ? "update" : "updates" }
let pluralizeWord = { $0 == 1 ? $1 : "\($1)s" }
let pluralizeUpdates = { pluralizeWord($0, "update") }
let newUpdatesString = pluralizeUpdates(numNewUpdates)
let existingUpdatesString = pluralizeUpdates(numExistingUpdates)
let removedUpdatesString = pluralizeUpdates(numUpdatesRemoved)
print("Wrote \(numNewUpdates) new \(newUpdatesString) and updated \(numExistingUpdates) existing \(existingUpdatesString)")
print("Wrote \(numNewUpdates) new \(newUpdatesString), updated \(numExistingUpdates) existing \(existingUpdatesString), and removed \(numUpdatesRemoved) old \(removedUpdatesString)")
let pruneCount = pruneUpdatesFromAppcast(archivesSourceDir: archivesSourceDir, prunedDirectory: prunedDirectory, cacheDirectory: GenerateAppcast.cacheDirectory, appcast: appcast)
if pruneCount > 0 {
print("Pruned \(pruneCount) old update \(pluralizeWord(pruneCount, "file")) to \(prunedDirectory.lastPathComponent)")
}
}
} catch {
print("Error generating appcast from directory", archivesSourceDir.path, "\n", error)