From 80a5b80ade75b1f04a7282d5f3e8ddc1f636472f Mon Sep 17 00:00:00 2001 From: Zorg Date: Sun, 14 Aug 2022 19:07:48 -0700 Subject: [PATCH] Move old updates to old_updates in generate_appcast (#2228) Document --versions in generate_appcast better and add comments to explain why certain policies were made. Add separate option to automatically pruned old update files. Now we only automatically move old update files aside. If the user passes --auto-prune-update-files we will also remove the old update files automatically. Move old release notes files too. Don't make old-updates directory hidden. --- generate_appcast/Appcast.swift | 125 ++++++++++++++++++------------- generate_appcast/Unarchive.swift | 11 ++- generate_appcast/main.swift | 34 ++++++--- 3 files changed, 103 insertions(+), 67 deletions(-) diff --git a/generate_appcast/Appcast.swift b/generate_appcast/Appcast.swift index 4bd3a4ad..966b6320 100644 --- a/generate_appcast/Appcast.swift +++ b/generate_appcast/Appcast.swift @@ -88,6 +88,9 @@ func makeAppcasts(archivesSourceDir: URL, outputPathURL: URL?, cacheDirectory ca } 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 + // The reason why we need to do this is because new branch-specific flags the user can specify like the channel + // or the major version will be applied to new unknown updates. We can only absolutely be sure to apply this to + // updates that are greater in version than the top of the current feed, or if the user uses --versions. for latestUpdateCandidate in updates { if feedUpdateBranches[latestUpdateCandidate.version] != nil { // Found the latest update in the feed @@ -209,6 +212,7 @@ func makeAppcasts(archivesSourceDir: URL, outputPathURL: URL?, cacheDirectory ca // 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 + // This is to support rollback in case the top newly generated update isn't exactly what the user wants let generatingDeltas = latestVersionPerBranch.contains(version) var numDeltas = 0 let appBaseName = latestItem.appPath.deletingPathExtension().lastPathComponent @@ -361,37 +365,37 @@ func makeAppcasts(archivesSourceDir: URL, outputPathURL: URL?, cacheDirectory ca return appcastByFeed } -func pruneUpdatesFromAppcast(archivesSourceDir: URL, prunedDirectory: URL, cacheDirectory: URL, appcast: Appcast) -> Int { +func moveOldUpdatesFromAppcast(archivesSourceDir: URL, oldFilesDirectory: URL, cacheDirectory: URL, appcast: Appcast, autoPruneUpdates: Bool) -> (movedCount: Int, prunedCount: Int) { let fileManager = FileManager.default let suFileManager = SUFileManager() - // Create pruned updates directory if needed - var createdPrunedDirectory = false - let makePrunedFilesDirectory: () -> Bool = { - guard !createdPrunedDirectory else { + // Create old files updates directory if needed + var createdOldFilesDirectory = false + let makeOldFilesDirectory: () -> Bool = { + guard !createdOldFilesDirectory else { return true } - if fileManager.fileExists(atPath: prunedDirectory.path) { - createdPrunedDirectory = true + if fileManager.fileExists(atPath: oldFilesDirectory.path) { + createdOldFilesDirectory = true return true } do { - try fileManager.createDirectory(at: prunedDirectory, withIntermediateDirectories: false) + try fileManager.createDirectory(at: oldFilesDirectory, withIntermediateDirectories: false) - createdPrunedDirectory = true + createdOldFilesDirectory = true return true } catch { - print("Warning: failed to create \(prunedDirectory.lastPathComponent) in \(archivesSourceDir.lastPathComponent): \(error)") + print("Warning: failed to create \(oldFilesDirectory.lastPathComponent) in \(archivesSourceDir.lastPathComponent): \(error)") return false } } - var prunedItemsCount = 0 + var movedItemsCount = 0 - // Prune all unused update items + // Move aside all old 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 { @@ -400,8 +404,8 @@ func pruneUpdatesFromAppcast(archivesSourceDir: URL, prunedDirectory: URL, cache let archivePath = update.archivePath - guard makePrunedFilesDirectory() else { - return prunedItemsCount + guard makeOldFilesDirectory() else { + return (movedItemsCount, 0) } do { @@ -411,19 +415,36 @@ func pruneUpdatesFromAppcast(archivesSourceDir: URL, prunedDirectory: URL, cache } do { - try fileManager.moveItem(at: archivePath, to: prunedDirectory.appendingPathComponent(archivePath.lastPathComponent)) + try fileManager.moveItem(at: archivePath, to: oldFilesDirectory.appendingPathComponent(archivePath.lastPathComponent)) + + movedItemsCount += 1 + + // Remove cache for the update + let appCachePath = update.appPath.deletingLastPathComponent() + let _ = try? fileManager.removeItem(at: appCachePath) } catch { - print("Warning: failed to move \(archivePath.lastPathComponent) to \(prunedDirectory.lastPathComponent): \(error)") + print("Warning: failed to move \(archivePath.lastPathComponent) to \(oldFilesDirectory.lastPathComponent): \(error)") } - prunedItemsCount += 1 - - // Prune cache for the update - let appCachePath = update.appPath.deletingLastPathComponent() - let _ = try? fileManager.removeItem(at: appCachePath) + let releaseNotesFile = archivePath.deletingPathExtension().appendingPathExtension("html") + if fileManager.fileExists(atPath: releaseNotesFile.path) { + do { + try suFileManager.updateModificationAndAccessTimeOfItem(at: releaseNotesFile) + } catch { + print("Warning: failed to update modification time for \(releaseNotesFile.path): \(error)") + } + + do { + try fileManager.moveItem(at: releaseNotesFile, to: oldFilesDirectory.appendingPathComponent(releaseNotesFile.lastPathComponent)) + + movedItemsCount += 1 + } catch { + print("Warning: failed to move \(releaseNotesFile.lastPathComponent) to \(oldFilesDirectory.lastPathComponent): \(error)") + } + } } - // Prune all unused delta items in the archives directory + // Move aside 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 { @@ -438,11 +459,11 @@ func pruneUpdatesFromAppcast(archivesSourceDir: URL, prunedDirectory: URL, cache continue } - guard makePrunedFilesDirectory() else { - return prunedItemsCount + guard makeOldFilesDirectory() else { + return (movedItemsCount, 0) } - prunedItemsCount += 1 + movedItemsCount += 1 do { try suFileManager.updateModificationAndAccessTimeOfItem(at: deltaURL) @@ -451,46 +472,50 @@ func pruneUpdatesFromAppcast(archivesSourceDir: URL, prunedDirectory: URL, cache } do { - try fileManager.moveItem(at: deltaURL, to: prunedDirectory.appendingPathComponent(filename)) + try fileManager.moveItem(at: deltaURL, to: oldFilesDirectory.appendingPathComponent(filename)) } catch { - print("Warning: failed to move \(deltaURL.lastPathComponent) to \(prunedDirectory.lastPathComponent): \(error)") + print("Warning: failed to move \(deltaURL.lastPathComponent) to \(oldFilesDirectory.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 - } + var pruneCount = 0 + if autoPruneUpdates { + // Garbage collect the old updates directory + do { + let directoryContents = try fileManager.contentsOfDirectory(atPath: oldFilesDirectory.path) - let fileURL = prunedDirectory.appendingPathComponent(filename) + // Delete files that have roughly not been touched for 14 days + let prunedFileDeletionInterval: TimeInterval = 86400 * 14 - 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)") + let currentDate = Date() + for filename in directoryContents { + guard !filename.hasPrefix(".") else { + continue + } + + let fileURL = oldFilesDirectory.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) + pruneCount += 1 + } catch { + print("Warning: failed to delete old update file \(oldFilesDirectory.lastPathComponent)/\(fileURL.lastPathComponent): \(error)") + } } } } + } catch { + // Nothing to log for failing to fetch prunedDirectory } - } catch { - // Nothing to log for failing to fetch prunedDirectory } - return prunedItemsCount + return (movedItemsCount, pruneCount) } func markDeltaAsIgnored(delta: DeltaUpdate, markerPath: URL) { diff --git a/generate_appcast/Unarchive.swift b/generate_appcast/Unarchive.swift index c09669e9..5e729a60 100644 --- a/generate_appcast/Unarchive.swift +++ b/generate_appcast/Unarchive.swift @@ -58,19 +58,18 @@ func unarchiveUpdates(archivesSourceDir: URL, archivesDestDir: URL, disableNeste var running = 0 for item in dir.filter({ !$0.hasPrefix(".") && !$0.hasSuffix(".delta") && !$0.hasSuffix(".xml") && !$0.hasSuffix(".html") }) { let itemPath = archivesSourceDir.appendingPathComponent(item) + var isDir: ObjCBool = false + if fileManager.fileExists(atPath: itemPath.path, isDirectory: &isDir) && isDir.boolValue { + continue + } + let archiveDestDir: URL - if let hash = itemPath.sha256String() { archiveDestDir = archivesDestDir.appendingPathComponent(hash) } else { archiveDestDir = archivesDestDir.appendingPathComponent(itemPath.lastPathComponent) } - var isDir: ObjCBool = false - if fileManager.fileExists(atPath: itemPath.path, isDirectory: &isDir) && isDir.boolValue { - continue - } - let addItem = { (validateBundle: Bool) in do { let item = try ArchiveItem(fromArchive: itemPath, unarchivedDir: archiveDestDir, validateBundle: validateBundle, disableNestedCodeCheck: disableNestedCodeCheck) diff --git a/generate_appcast/main.swift b/generate_appcast/main.swift index 507ef02c..9ff18ac8 100644 --- a/generate_appcast/main.swift +++ b/generate_appcast/main.swift @@ -52,7 +52,7 @@ 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 oldFilesDirectoryName = "old_updates" static let DEFAULT_MAX_VERSIONS_PER_BRANCH_IN_FEED = 3 static let DEFAULT_MAXIMUM_DELTAS = 5 @@ -87,7 +87,7 @@ 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. 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: ",")) }) + @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 current feed. Use this option if you need to insert only a specific new version or insert an old update in the feed at a different branch point (e.g. with a different minimum OS version or channel).", valueName: "versions"), transform: { Set($0.components(separatedBy: ",")) }) var versions: Set? @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")) @@ -117,6 +117,9 @@ struct GenerateAppcast: ParsableCommand { @Option(name: .long, help: ArgumentHelp("A comma delimited list of application sparkle:version's that will see newly generated updates as being informational only. An empty string argument will treat this update as informational coming from any application version. Prefix a version string with '<' to indicate (eg \"<2.5\") to indicate older versions than the one specified should treat the update as informational only. By default, updates are not informational only. --link must also be provided. Old applications need to be using Sparkle 2 to use this feature, and 2.1 or later to use the '<' upper bound feature.", valueName: "informational-update-versions"), transform: { $0.components(separatedBy: ",").filter({$0.count > 0}) }) var informationalUpdateVersions: [String]? + @Flag(name: .customLong("auto-prune-update-files"), help: ArgumentHelp("Automatically remove old update files in \(oldFilesDirectoryName) that haven't been touched in 2 weeks")) + var autoPruneUpdates: Bool = false + @Option(name: .customShort("o"), help: ArgumentHelp("Path to filename for the generated appcast (allowed when only one will be created).", valueName: "output-path"), transform: { URL(fileURLWithPath: $0) }) var outputPathURL: URL? @@ -144,7 +147,14 @@ 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 that are still needed are kept intact. Otherwise, a new appcast file will be generated and written. + Otherwise, a new appcast file will be generated and written. + + Old updates are automatically removed from the generated appcast feed and their update files are moved to \(oldFilesDirectoryName)/ + If --auto-prune-update-files is passed, old update files in this directory are deleted after 2 weeks. + You may want to exclude files from this directory from being uploaded. + + Use the --versions option if you need to insert an update that is older than the latest update in your feed, or + if you need to insert only a specific new version with certain parameters. .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. @@ -159,6 +169,7 @@ struct GenerateAppcast: ParsableCommand { MyApp 1.1.zip MyApp 1.1.html appcast.xml + \(oldFilesDirectoryName)/ EXAMPLES: \(programNamePath) ./my-app-release-zipfiles/ @@ -166,10 +177,8 @@ struct GenerateAppcast: ParsableCommand { For more advanced options that can be used for publishing updates, see https://sparkle-project.org/documentation/publishing/ for further documentation. - 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. - + Extracted archives that are needed are cached in \((cacheDirectory.path as NSString).abbreviatingWithTildeInPath) to avoid re-computation in subsequent runs. + Note that \(programName) does not support package-based (.pkg) updates. """) @@ -262,7 +271,7 @@ struct GenerateAppcast: ParsableCommand { do { 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) - let prunedDirectory = archivesSourceDir.appendingPathComponent(GenerateAppcast.prunedDirectoryName) + let oldFilesDirectory = archivesSourceDir.appendingPathComponent(GenerateAppcast.oldFilesDirectoryName) for (appcastFile, appcast) in appcastsByFeed { // If an output filename was specified, use it. @@ -282,9 +291,12 @@ struct GenerateAppcast: ParsableCommand { 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)") + let (moveCount, prunedCount) = moveOldUpdatesFromAppcast(archivesSourceDir: archivesSourceDir, oldFilesDirectory: oldFilesDirectory, cacheDirectory: GenerateAppcast.cacheDirectory, appcast: appcast, autoPruneUpdates: autoPruneUpdates) + if moveCount > 0 { + print("Moved \(moveCount) old update \(pluralizeWord(moveCount, "file")) to \(oldFilesDirectory.lastPathComponent)") + } + if prunedCount > 0 { + print("Pruned \(prunedCount) old update \(pluralizeWord(prunedCount, "file"))") } } } catch {