Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Latest.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
5039DE8522CA396F0088B39B /* UpdateQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5039DE8422CA396F0088B39B /* UpdateQueue.swift */; };
5039DE8722CA39C60088B39B /* UpdateOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5039DE8622CA39C60088B39B /* UpdateOperation.swift */; };
5039DE8B22CA39ED0088B39B /* StatefulOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5039DE8A22CA39ED0088B39B /* StatefulOperation.swift */; };
F3B2C3D4E5F60718293A4B5C /* HomebrewUpdateOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3B2C3D4E5F60718293A4B5D /* HomebrewUpdateOperation.swift */; };
5039DE8D22CAA2790088B39B /* MacAppStoreUpdateOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5039DE8C22CAA2790088B39B /* MacAppStoreUpdateOperation.swift */; };
5040D45C28DBB753009BF379 /* HomebrewCheckerOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5040D45A28DBB753009BF379 /* HomebrewCheckerOperation.swift */; };
5048574022C81DD000C52C48 /* CommerceKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5048573F22C81DCF00C52C48 /* CommerceKit.framework */; };
Expand Down Expand Up @@ -79,6 +80,7 @@
50E4EB092B17DFCE00A70A7D /* VersionParserTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50E4EB082B17DFCE00A70A7D /* VersionParserTest.swift */; };
50FEB87D2B1BE630006FB75D /* OSVersionTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50FEB87C2B1BE630006FB75D /* OSVersionTest.swift */; };
50FEB87F2B1BE67F006FB75D /* VersionSanitizationTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50FEB87E2B1BE67E006FB75D /* VersionSanitizationTest.swift */; };
F4B2C3D4E5F60718293A4B5C /* HomebrewUpdateOperationTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4B2C3D4E5F60718293A4B5D /* HomebrewUpdateOperationTest.swift */; };
50FEB8812B1D2402006FB75D /* ExcludedAppIdentifiers.plist in Resources */ = {isa = PBXBuildFile; fileRef = 50FEB8802B1D2402006FB75D /* ExcludedAppIdentifiers.plist */; };
/* End PBXBuildFile section */

Expand Down Expand Up @@ -166,6 +168,7 @@
5039DE8422CA396F0088B39B /* UpdateQueue.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateQueue.swift; sourceTree = "<group>"; };
5039DE8622CA39C60088B39B /* UpdateOperation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateOperation.swift; sourceTree = "<group>"; };
5039DE8A22CA39ED0088B39B /* StatefulOperation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatefulOperation.swift; sourceTree = "<group>"; };
F3B2C3D4E5F60718293A4B5D /* HomebrewUpdateOperation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomebrewUpdateOperation.swift; sourceTree = "<group>"; };
5039DE8C22CAA2790088B39B /* MacAppStoreUpdateOperation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MacAppStoreUpdateOperation.swift; sourceTree = "<group>"; };
5040D45A28DBB753009BF379 /* HomebrewCheckerOperation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HomebrewCheckerOperation.swift; sourceTree = "<group>"; };
5048573F22C81DCF00C52C48 /* CommerceKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CommerceKit.framework; path = ../../../../../../System/Library/PrivateFrameworks/CommerceKit.framework; sourceTree = "<group>"; };
Expand Down Expand Up @@ -332,6 +335,7 @@
50F542FC22D9C41D004B3F8D /* ISStoreClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ISStoreClient.h; sourceTree = "<group>"; };
50FEB87C2B1BE630006FB75D /* OSVersionTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSVersionTest.swift; sourceTree = "<group>"; };
50FEB87E2B1BE67E006FB75D /* VersionSanitizationTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VersionSanitizationTest.swift; sourceTree = "<group>"; };
F4B2C3D4E5F60718293A4B5D /* HomebrewUpdateOperationTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomebrewUpdateOperationTest.swift; sourceTree = "<group>"; };
50FEB8802B1D2402006FB75D /* ExcludedAppIdentifiers.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = ExcludedAppIdentifiers.plist; sourceTree = "<group>"; };
/* End PBXFileReference section */

Expand Down Expand Up @@ -417,6 +421,7 @@
5039DE8422CA396F0088B39B /* UpdateQueue.swift */,
5039DE8622CA39C60088B39B /* UpdateOperation.swift */,
5087CD2C22F6E06B0013354C /* SparkleUpdateOperation.swift */,
F3B2C3D4E5F60718293A4B5D /* HomebrewUpdateOperation.swift */,
5039DE8C22CAA2790088B39B /* MacAppStoreUpdateOperation.swift */,
);
path = Updater;
Expand Down Expand Up @@ -645,6 +650,7 @@
50C81D731FBADC9100324C2E /* VersionTest.swift */,
50E4EB082B17DFCE00A70A7D /* VersionParserTest.swift */,
50FEB87E2B1BE67E006FB75D /* VersionSanitizationTest.swift */,
F4B2C3D4E5F60718293A4B5D /* HomebrewUpdateOperationTest.swift */,
);
path = Tests;
sourceTree = "<group>";
Expand Down Expand Up @@ -951,6 +957,7 @@
50C9F10C234641E000FD1802 /* SparkleCheckerOperation.swift in Sources */,
50E4EB072B17DACB00A70A7D /* VersionParser.swift in Sources */,
50290E751E53EB6A00133E3D /* AppDelegate.swift in Sources */,
F3B2C3D4E5F60718293A4B5C /* HomebrewUpdateOperation.swift in Sources */,
5039DE8D22CAA2790088B39B /* MacAppStoreUpdateOperation.swift in Sources */,
507375572789AB0300F371D8 /* AppListSnapshot.swift in Sources */,
501EF8ED2B9A665A00F0D759 /* BundleCollector.swift in Sources */,
Expand Down Expand Up @@ -998,6 +1005,7 @@
50C81D741FBADC9100324C2E /* VersionTest.swift in Sources */,
50FEB87D2B1BE630006FB75D /* OSVersionTest.swift in Sources */,
50FEB87F2B1BE67F006FB75D /* VersionSanitizationTest.swift in Sources */,
F4B2C3D4E5F60718293A4B5C /* HomebrewUpdateOperationTest.swift in Sources */,
50E4EB092B17DFCE00A70A7D /* VersionParserTest.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,23 @@ class HomebrewCheckerOperation: StatefulOperation, UpdateCheckerOperation, @unch
return
}

repository.updateInfo(for: bundle) { bundle, version, minimumOSVersion in
repository.updateInfo(for: bundle) { bundle, version, minimumOSVersion, token in
defer { self.finish() }
guard let version else { return }
self.update = App.Update(app: bundle, remoteVersion: version, minimumOSVersion: minimumOSVersion, source: .homebrew, date: nil, releaseNotes: nil, updateAction: .external(label: bundle.name, block: { app in
app.open()
}))

// Update through Homebrew if it manages the cask. Otherwise just open the app, as before.
let action: App.Update.Action
if let token, HomebrewUpdateOperation.canUpdate(caskToken: token) {
action = .builtIn(block: { app in
UpdateQueue.shared.addOperation(HomebrewUpdateOperation(bundleIdentifier: app.bundleIdentifier, appIdentifier: app.identifier, caskToken: token))
})
} else {
action = .external(label: bundle.name, block: { app in
app.open()
})
}

self.update = App.Update(app: bundle, remoteVersion: version, minimumOSVersion: minimumOSVersion, source: .homebrew, date: nil, releaseNotes: nil, updateAction: action)
}
}

Expand Down
6 changes: 3 additions & 3 deletions Latest/Model/Update Repository/UpdateRepository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,14 @@ class UpdateRepository {
// MARK: - Accessors

/// Returns update information for the given bundle.
func updateInfo(for bundle: App.Bundle, handler: @escaping (_ bundle: App.Bundle, _ version: Version?, _ minimumOSVersion: OperatingSystemVersion?) -> Void) {
func updateInfo(for bundle: App.Bundle, handler: @escaping (_ bundle: App.Bundle, _ version: Version?, _ minimumOSVersion: OperatingSystemVersion?, _ token: String?) -> Void) {
let checkApp = {
guard let entry = self.entry(for: bundle) else {
handler(bundle, nil, nil)
handler(bundle, nil, nil, nil)
return
}

return handler(bundle, entry.version, entry.minimumOSVersion)
return handler(bundle, entry.version, entry.minimumOSVersion, entry.token)
}

/// Entries are still being fetched, add the request to the queue.
Expand Down
106 changes: 106 additions & 0 deletions Latest/Model/Updater/HomebrewUpdateOperation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
//
// HomebrewUpdateOperation.swift
// Latest
//

import Foundation

/// The operation updating apps that are managed by a Homebrew cask.
///
/// Only casks Homebrew already manages are updated. Apps that were installed in another way keep opening the app as before.
class HomebrewUpdateOperation: UpdateOperation, @unchecked Sendable {

/// The Homebrew cask token of the app.
private let caskToken: String

/// The running brew process, kept for cancellation.
private var process: Process?

init(bundleIdentifier: String, appIdentifier: App.Bundle.Identifier, caskToken: String) {
self.caskToken = caskToken
super.init(bundleIdentifier: bundleIdentifier, appIdentifier: appIdentifier)
}


// MARK: - Homebrew

/// Where Homebrew is installed: Apple silicon or Intel default prefixes.
private static let prefixes = ["/opt/homebrew", "/usr/local"]

/// The location of the brew executable, if Homebrew is installed.
static var brewURL: URL? {
prefixes.map { URL(fileURLWithPath: $0).appendingPathComponent("bin/brew") }
.first { FileManager.default.isExecutableFile(atPath: $0.path) }
}

/// Whether the token is a valid cask token and can safely be passed to brew.
static func isValid(caskToken token: String) -> Bool {
token.range(of: "^[a-z0-9][a-z0-9@._+-]*$", options: .regularExpression) != nil
}

/// Whether Homebrew already manages the cask. Homebrew keeps one folder per installed cask in its `Caskroom`.
static func isInstalled(caskToken token: String, in caskrooms: [URL] = prefixes.map { URL(fileURLWithPath: $0).appendingPathComponent("Caskroom") }) -> Bool {
guard isValid(caskToken: token) else { return false }
return caskrooms.contains { FileManager.default.fileExists(atPath: $0.appendingPathComponent(token).path) }
}

/// Whether Latest can update the app through Homebrew.
static func canUpdate(caskToken token: String) -> Bool {
brewURL != nil && isInstalled(caskToken: token)
}

/// The arguments for upgrading the cask. `--greedy` includes apps that update themselves, which Latest lists as well.
static func upgradeArguments(forCaskToken token: String) -> [String]? {
isValid(caskToken: token) ? ["upgrade", "--cask", "--greedy", token] : nil
}


// MARK: - Operation Overrides

override func execute() {
super.execute()

guard let brew = Self.brewURL, let arguments = Self.upgradeArguments(forCaskToken: caskToken) else {
finish(with: LatestError.custom(title: NSLocalizedString("HomebrewNotInstalledError", value: "Homebrew is not installed", comment: "Error title when an app should be updated through Homebrew, but Homebrew is missing."), description: nil))
return
}

progressState = .installing
let process = Process()
process.executableURL = brew
process.arguments = arguments

var environment = ProcessInfo.processInfo.environment
environment["HOMEBREW_NO_AUTO_UPDATE"] = "1"
environment["HOMEBREW_NO_INSTALL_CLEANUP"] = "1"
environment["NONINTERACTIVE"] = "1"
process.environment = environment

let pipe = Pipe()
process.standardOutput = pipe
process.standardError = pipe
self.process = process

do {
try process.run()
} catch {
finish(with: error)
return
}

let output = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
process.waitUntilExit()

if isCancelled || process.terminationStatus == 0 {
finish()
} else {
finish(with: LatestError.custom(title: NSLocalizedString("HomebrewUpdateFailedError", value: "Homebrew could not update this app", comment: "Error title when updating an app through Homebrew failed."), description: String(output.suffix(600))))
}
}

override func cancel() {
process?.terminate()
super.cancel()
}

}
46 changes: 46 additions & 0 deletions Tests/HomebrewUpdateOperationTest.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//
// HomebrewUpdateOperationTest.swift
// LatestTests
//

import XCTest
@testable import Latest

final class HomebrewUpdateOperationTest: XCTestCase {

private func caskroom(with tokens: [String]) throws -> URL {
let url = FileManager.default.temporaryDirectory.appendingPathComponent("Caskroom-\(UUID().uuidString)")
for token in tokens {
try FileManager.default.createDirectory(at: url.appendingPathComponent(token), withIntermediateDirectories: true)
}
addTeardownBlock { try? FileManager.default.removeItem(at: url) }
return url
}

func testRecognizesCasksThatHomebrewManages() throws {
let caskroom = try caskroom(with: ["firefox", "powershell@preview"])
XCTAssertTrue(HomebrewUpdateOperation.isInstalled(caskToken: "firefox", in: [caskroom]))
XCTAssertTrue(HomebrewUpdateOperation.isInstalled(caskToken: "powershell@preview", in: [caskroom]))
XCTAssertFalse(HomebrewUpdateOperation.isInstalled(caskToken: "zoom", in: [caskroom]), "Not installed through Homebrew")
}

func testChecksEveryCaskroom() throws {
let first = try caskroom(with: [])
let second = try caskroom(with: ["firefox"])
XCTAssertTrue(HomebrewUpdateOperation.isInstalled(caskToken: "firefox", in: [first, second]))
}

func testBuildsTheUpgradeCommand() {
XCTAssertEqual(HomebrewUpdateOperation.upgradeArguments(forCaskToken: "firefox"), ["upgrade", "--cask", "--greedy", "firefox"])
}

func testRejectsTokensThatCouldBeTakenForOptionsOrPaths() throws {
for token in ["", "--force", "-x", "../firefox", "a/b", "fire fox", "a;b", "Firefox"] {
XCTAssertFalse(HomebrewUpdateOperation.isValid(caskToken: token), "\(token) must not be passed to brew")
XCTAssertNil(HomebrewUpdateOperation.upgradeArguments(forCaskToken: token))
}
let caskroom = try caskroom(with: ["firefox"])
XCTAssertFalse(HomebrewUpdateOperation.isInstalled(caskToken: "../Caskroom/firefox", in: [caskroom]))
}

}