diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..115665c --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,19 @@ +name: Tests + +on: + push: + branches: [main] + pull_request: + +jobs: + test: + runs-on: macos-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v5 + - name: Toolchain + run: swift --version + - name: Offline tests + run: ./test.sh + - name: Release build + run: ./build.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index 038e4ff..7c99626 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,15 @@ # Changelog -## Unreleased +## 0.4.1 — 2026-11-13 - Development builds no longer show up in Spotlight or Launchpad next to the installed app. `./build.sh` now builds `dist.noindex/UpdateWorkbench.app` (Spotlight skips folders ending in `.noindex`) and unregisters that copy from Launch Services. `./test.sh` creates its fixture apps and disk images in a temporary `.noindex` folder, and `./make-release.sh` stages the DMG contents in one. - Direct installs download, extract and stage update copies in `.noindex` folders, so a half-finished update is never listed in Spotlight. +- Fixed version comparison. Versions were compared as text with numbers sorted numerically, so someone on a beta such as `1.0-beta.1` was never offered `1.0`, and `2.0.0` counted as newer than `2.0` (a "new" version that was the same one). Missing components now count as zero, pre-releases (`-beta.1`, `b2`, `rc1`, Preview, ...) come before their release, a trailing build such as `1.0 (45)` comes after it, and a leading `v` and `+build` metadata are ignored. The same order is used for feeds, GitHub and Electron releases, build numbers and minimum macOS versions. +- When GitHub's limit of 60 unauthenticated API requests an hour is reached, the message says so and gives the time it resets. +- Tests now run with `swift test` (Swift Testing) through a test target in `Package.swift`; `./test.sh` wraps it and passes extra arguments through. GitHub Actions runs the tests and a release build on every push to `main` and on pull requests. +- The version and build number are set once in `build.sh`; the app reads its version from `Info.plist`. +- The Sparkle, Electron and GitHub checks share one batching helper instead of three copies. +- Version 0.4.1 (build 7). ## 0.4.0 — 2026-11-12 diff --git a/Package.swift b/Package.swift index 801285a..b70d681 100644 --- a/Package.swift +++ b/Package.swift @@ -1,3 +1,12 @@ -// swift-tools-version: 5.10 +// swift-tools-version: 6.0 import PackageDescription -let package = Package(name: "UpdateWorkbench", platforms: [.macOS(.v14)], products: [.executable(name: "UpdateWorkbench", targets: ["UpdateWorkbench"])], targets: [.executableTarget(name: "UpdateWorkbench")]) +let package = Package( + name: "UpdateWorkbench", + platforms: [.macOS(.v14)], + products: [.executable(name: "UpdateWorkbench", targets: ["UpdateWorkbench"])], + targets: [ + .executableTarget(name: "UpdateWorkbench", swiftSettings: [.swiftLanguageMode(.v5)]), + // `swift test` (or ./test.sh) runs the offline suites against the app module with @testable import. + .testTarget(name: "UpdateWorkbenchTests", dependencies: ["UpdateWorkbench"], path: "Tests"), + ] +) diff --git a/README.md b/README.md index da16178..fb54a0e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Update Workbench is a native macOS app that finds and installs updates for your Requires macOS 14 or newer on Apple silicon. Check the download against `SHA256SUMS` with `shasum -a 256 -c SHA256SUMS`. -**Upgrading from 0.3.x:** quit Update Workbench, drag the new version into Applications and choose **Replace**. Settings, rules and approvals are kept. You may need the right-click **Open** step once more. +**Upgrading from an earlier version:** quit Update Workbench, drag the new version into Applications and choose **Replace**. Settings, rules and approvals are kept. You may need the right-click **Open** step once more. **App Store updates (optional):** install the free `mas` tool with **Homebrew → Install mas…** (or `brew install mas` in Terminal) and stay signed in to the App Store app. When mas needs your Mac password to install an App Store update, click **Finish in Terminal** and type the password there. Update Workbench never sees it. You can also click **Open App Store Updates** and update in the App Store app. @@ -20,12 +20,21 @@ Requires Xcode command-line tools. ```sh ./build.sh # builds dist.noindex/UpdateWorkbench.app (ad-hoc signed) -./test.sh # offline test suite +./test.sh # offline test suite (swift test); extra arguments go to swift test, e.g. --filter VersionOrderTests ./make-release.sh # DMG, ZIP and SHA256SUMS in release/ ``` +The version and build number are set once, at the top of `build.sh`. GitHub Actions runs `./test.sh` and `./build.sh` on every push to `main` and on pull requests. + Builds go to `dist.noindex/`. Spotlight skips folders whose names end in `.noindex`, so development builds, test fixtures and release staging never appear in Spotlight or Launchpad next to the copy in Applications. +## New in 0.4.1 + +- **Betas move on to the final release.** If you run a beta such as `1.0-beta.1`, the finished `1.0` is now offered. Before, it wasn't. +- **No more fake updates.** The same version written two ways (`2.0` and `2.0.0`) is no longer shown as an update. +- **Clearer GitHub limit message.** GitHub allows 60 checks an hour without an account. When that's reached, the app now says so and tells you when it resets. +- **Test copies stay out of Spotlight.** Development builds, test apps and half-finished updates are kept in folders Spotlight skips, so only the app in Applications shows up. + ## New in 0.4.0 - **Signer changes you can review.** If an update is signed by a different developer team, Update Workbench stops and shows both teams with their certificate details. You can approve the new team for that one app after confirming; approvals are listed with dates in Settings → Trust and can be revoked. Code signing and Gatekeeper still have to pass. @@ -79,6 +88,8 @@ To render every screen yourself in dark and light (fake data, no scanning, nothi dist.noindex/UpdateWorkbench.app/Contents/MacOS/UpdateWorkbench --render-snapshots /tmp/updateworkbench-snapshots ``` +Running the app from `dist.noindex/` registers that copy with Launch Services again. Run `./build.sh` afterwards, or `/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -u dist.noindex/UpdateWorkbench.app`, so it doesn't appear next to the installed app. + ## Available features - Inventory `/Applications`, `~/Applications`, and additional folders configured in Settings. diff --git a/Sources/UpdateWorkbench/App.swift b/Sources/UpdateWorkbench/App.swift index 2b792b1..cd74373 100644 --- a/Sources/UpdateWorkbench/App.swift +++ b/Sources/UpdateWorkbench/App.swift @@ -102,7 +102,7 @@ final class WorkbenchModel: ObservableObject { } } var ignoredItems: [UpdateItem] { items.filter { decision($0) != .show || isSnoozed($0) } } - var appVersion: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? AppIdentity.version } + var appVersion: String { AppIdentity.version } var suggestions: [UpdateItem] { items.filter { item in (item.provider == .manual || item.provider == .vendor || (item.provider == .electron && !item.canUpdateDirectly)) diff --git a/Sources/UpdateWorkbench/Core.swift b/Sources/UpdateWorkbench/Core.swift index bb9fab0..f3b0d33 100644 --- a/Sources/UpdateWorkbench/Core.swift +++ b/Sources/UpdateWorkbench/Core.swift @@ -249,100 +249,64 @@ actor Engine { diagnostics.append("App Store apps aren't checked because mas isn't installed. Choose Homebrew → Install mas… (or run `brew install mas`), then check again.") } // Keep requests bounded and preserve failures as unknown, never as up-to-date. - let feedIndices = items.indices.filter { items[$0].provider == .sparkle && items[$0].feedURL != nil } - for start in stride(from: 0, to: feedIndices.count, by: 6) { - let batch = feedIndices[start..( + _ checks: [(Int, Source, String, Bool)], + _ check: @escaping @Sendable (Source, String, Bool) async throws -> Value? + ) async -> [(Int, Value?, String?)] { + var results: [(Int, Value?, String?)] = [] + for start in stride(from: 0, to: checks.count, by: 6) { + await withTaskGroup(of: (Int, Value?, String?).self) { group in + for (index, source, version, prerelease) in checks[start.. UpdateOutcome { guard item.canUpdateDirectly else { throw UpdateError.unavailable("No verified direct update is available for \(item.name).") } if let bundleID = item.bundleID, diff --git a/Sources/UpdateWorkbench/GitHubBackend.swift b/Sources/UpdateWorkbench/GitHubBackend.swift index 451aac3..8187c42 100644 --- a/Sources/UpdateWorkbench/GitHubBackend.swift +++ b/Sources/UpdateWorkbench/GitHubBackend.swift @@ -79,7 +79,7 @@ enum GitHubBackend { defer { try? FileManager.default.removeItem(at: file) } guard let http = response as? HTTPURLResponse else { throw Failure(message: "GitHub did not return an HTTP response.") } guard http.statusCode == 200 else { - if http.statusCode == 403 || http.statusCode == 429 { throw Failure(message: "GitHub rate-limited this check. Try again later; private repositories are unsupported.") } + if http.statusCode == 403 || http.statusCode == 429 { throw Failure(message: rateLimitMessage(http)) } if http.statusCode == 404 { throw Failure(message: "No public latest release was found for \(repository). Check the repository setting.") } throw Failure(message: "GitHub release check returned HTTP \(http.statusCode).") } @@ -88,6 +88,19 @@ enum GitHubBackend { return try Data(contentsOf: file) } + /// GitHub allows 60 unauthenticated API requests an hour per IP address. Conditional requests + /// don't help: without a token, a `304 Not Modified` answer counts against the limit too. + static func rateLimitMessage(_ response: HTTPURLResponse) -> String { + guard response.value(forHTTPHeaderField: "x-ratelimit-remaining") == "0" || response.statusCode == 429 else { + return "GitHub refused this check (HTTP \(response.statusCode)). Private repositories are unsupported." + } + guard let reset = response.value(forHTTPHeaderField: "x-ratelimit-reset").flatMap(TimeInterval.init) else { + return "GitHub's limit of 60 checks an hour was reached. Try again later." + } + let time = Date(timeIntervalSince1970: reset).formatted(date: .omitted, time: .shortened) + return "GitHub's limit of 60 checks an hour was reached. It resets at \(time)." + } + static func parseRelease(_ data: Data, repository: String, installedVersion: String, architecture: String = SparkleBackend.hostArchitecture) throws -> GitHubRelease? { guard validRepository(repository), data.count <= GitHubResponseGuard.maximumBytes else { throw Failure(message: "Invalid GitHub repository or oversized release metadata.") } diff --git a/Sources/UpdateWorkbench/NetworkSettings.swift b/Sources/UpdateWorkbench/NetworkSettings.swift index d4ee043..d675bd3 100644 --- a/Sources/UpdateWorkbench/NetworkSettings.swift +++ b/Sources/UpdateWorkbench/NetworkSettings.swift @@ -192,7 +192,8 @@ enum HTTPFetcher { } enum AppIdentity { - static let version = "0.4.0" + /// Set once in build.sh, which writes it into Info.plist. + static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "development" static let userAgent = "UpdateWorkbench/\(version)" } diff --git a/Sources/UpdateWorkbench/SparkleBackend.swift b/Sources/UpdateWorkbench/SparkleBackend.swift index 1ef03cb..e39338d 100644 --- a/Sources/UpdateWorkbench/SparkleBackend.swift +++ b/Sources/UpdateWorkbench/SparkleBackend.swift @@ -56,7 +56,7 @@ enum SparkleBackend { } static func isNewer(_ candidate: String, than installed: String) -> Bool { - candidate.compare(installed, options: [.numeric, .caseInsensitive]) == .orderedDescending + VersionOrder.compare(candidate, installed) == .orderedDescending } static func check(feedURL: URL, installedVersion: String, allowPrerelease: Bool = false) async throws -> SparkleRelease? { @@ -196,12 +196,12 @@ enum SparkleBackend { throw Failure(message: "The downloaded app requires a newer version of macOS.") } } - guard release.version == newVersion || release.version == newBuild else { + guard VersionOrder.isSame(release.version, newVersion) || release.version == newBuild else { throw Failure(message: "The downloaded app version (\(newVersion)) does not match the selected update (\(release.version)).") } let oldVersion = oldInfo["CFBundleShortVersionString"] as? String ?? "" let oldBuild = oldInfo["CFBundleVersion"] as? String ?? "" - guard isNewer(newVersion, than: oldVersion) || (newVersion == oldVersion && isNewer(newBuild, than: oldBuild)) else { + guard isNewer(newVersion, than: oldVersion) || (VersionOrder.isSame(newVersion, oldVersion) && isNewer(newBuild, than: oldBuild)) else { throw Failure(message: "The downloaded app is not newer than the installed app.") } try verifier.verify(original) diff --git a/Sources/UpdateWorkbench/VersionOrder.swift b/Sources/UpdateWorkbench/VersionOrder.swift new file mode 100644 index 0000000..4d043d8 --- /dev/null +++ b/Sources/UpdateWorkbench/VersionOrder.swift @@ -0,0 +1,117 @@ +import Foundation + +/// Orders app, build and macOS version strings. +/// +/// Numeric components compare as numbers and missing ones count as zero, so `2.0` and `2.0.0` are the same +/// version. A pre-release (`1.0-beta.1`, `3.1b2`, `4.0rc1`, `5.0 Preview`) comes before its release; other +/// suffixes such as `1.0 (45)` come after it. A leading `v` and semver build metadata (`+sha.1`) are ignored. +enum VersionOrder { + static func compare(_ lhs: String, _ rhs: String) -> ComparisonResult { + guard let left = Parsed(lhs), let right = Parsed(rhs) else { + // Not a dotted number (for example "Unknown"): keep the plain text ordering. + return lhs.compare(rhs, options: [.numeric, .caseInsensitive]) + } + for index in 0.. Bool { compare(lhs, rhs) == .orderedSame } + + private enum Token: Equatable { + case number(Int) + case word(String) + } + + private struct Parsed { + enum Kind: Int, Comparable { + case prerelease, release, suffixed + static func < (lhs: Kind, rhs: Kind) -> Bool { lhs.rawValue < rhs.rawValue } + } + var release: [Int] + var kind: Kind + var suffix: [Token] + + init?(_ raw: String) { + var text = Substring(raw.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()) + if text.first == "v" { text = text.dropFirst() } + if let plus = text.firstIndex(of: "+") { text = text[.. [Token] { + var tokens: [Token] = [], current = "", isNumber = false + func flush() { + guard !current.isEmpty else { return } + tokens.append(isNumber ? Int(current).map(Token.number) ?? .word(current) : .word(current)) + current = "" + } + for character in text { + if character.isASCII, character.isNumber { + if !isNumber { flush() } + isNumber = true; current.append(character) + } else if character.isLetter { + if isNumber { flush() } + isNumber = false; current.append(character) + } else { flush() } + } + flush() + return tokens + } + } + + /// Pre-release words in ascending order; the same vocabulary as UpdateRules.isPrerelease. + private static let prereleaseRank: [String: Int] = [ + "dev": 0, "nightly": 0, "snapshot": 0, "canary": 0, "unstable": 0, "test": 0, + "alpha": 1, "a": 1, "ea": 1, "insider": 1, "insiders": 1, + "beta": 2, "b": 2, + "pre": 3, "preview": 3, + "rc": 4, + ] + + /// Semver precedence for the suffix: numbers numerically, words by pre-release rank then alphabetically, + /// numbers before words, and a shorter list first when it is a prefix of the other. + private static func compareSuffix(_ lhs: [Token], _ rhs: [Token]) -> ComparisonResult { + for (a, b) in zip(lhs, rhs) where a != b { + switch (a, b) { + case let (.number(x), .number(y)): return x < y ? .orderedAscending : .orderedDescending + case (.number, .word): return .orderedAscending + case (.word, .number): return .orderedDescending + case let (.word(x), .word(y)): + let rankX = prereleaseRank[x] ?? 3, rankY = prereleaseRank[y] ?? 3 + if rankX != rankY { return rankX < rankY ? .orderedAscending : .orderedDescending } + return x < y ? .orderedAscending : .orderedDescending + } + } + if lhs.count == rhs.count { return .orderedSame } + return lhs.count < rhs.count ? .orderedAscending : .orderedDescending + } +} diff --git a/Tests/ArchiveSafetyTests.swift b/Tests/ArchiveSafetyTests.swift index 98e96cf..2573cb3 100644 --- a/Tests/ArchiveSafetyTests.swift +++ b/Tests/ArchiveSafetyTests.swift @@ -1,4 +1,5 @@ import Foundation +@testable import UpdateWorkbench /// Symlink-aware ZIP validation: fixture archives are built in a temporary folder with /usr/bin/zip and ditto. enum ArchiveSafetyTests { diff --git a/Tests/BackendTests.swift b/Tests/BackendTests.swift index 49da7d7..a8ca916 100644 --- a/Tests/BackendTests.swift +++ b/Tests/BackendTests.swift @@ -1,6 +1,7 @@ import AppKit import CryptoKit import Foundation +@testable import UpdateWorkbench private struct TestFailure: Error, CustomStringConvertible { let description: String @@ -10,15 +11,8 @@ private func expect(_ condition: @autoclosure () -> Bool, _ message: String) thr if !condition() { throw TestFailure(description: message) } } -@main -struct BackendTests { - static func main() async throws { - try GitHubTests.run() - try await FeatureTests.run() - try PresentationTests.run() - try ArchiveSafetyTests.run() - try WorkflowTests.run() - try await DiskImageTests.run() +enum BackendTests { + static func run() async throws { try testHomebrewDestination() try testAppcasts() try testSignatures() diff --git a/Tests/DiskImageTests.swift b/Tests/DiskImageTests.swift index 62efb00..055c143 100644 --- a/Tests/DiskImageTests.swift +++ b/Tests/DiskImageTests.swift @@ -1,5 +1,6 @@ import CryptoKit import Foundation +@testable import UpdateWorkbench /// Full DMG install path with fixture disk images built by hdiutil in a temporary folder: /// good, wrong team, approved team, multiple apps, broken signature, version mismatch, license agreement, diff --git a/Tests/FeatureTests.swift b/Tests/FeatureTests.swift index 9891e01..f97ee11 100644 --- a/Tests/FeatureTests.swift +++ b/Tests/FeatureTests.swift @@ -2,6 +2,7 @@ import CFNetwork import CryptoKit import Foundation import Security +@testable import UpdateWorkbench /// Offline fixtures for Electron feeds, discovery, cask matching, management flows, permissions, /// notifications, proxy/Keychain and self-update. No network, brew, or real app changes. diff --git a/Tests/GitHubRateLimitTests.swift b/Tests/GitHubRateLimitTests.swift new file mode 100644 index 0000000..865e964 --- /dev/null +++ b/Tests/GitHubRateLimitTests.swift @@ -0,0 +1,19 @@ +import Foundation +import Testing +@testable import UpdateWorkbench + +struct GitHubRateLimitTests { + let latest = URL(string: "https://api.github.com/repos/example/app/releases/latest")! + + @Test func explainsTheRateLimit() throws { + func response(_ status: Int, _ headers: [String: String]) throws -> HTTPURLResponse { + try #require(HTTPURLResponse(url: latest, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)) + } + let reset = Date(timeIntervalSince1970: 1_800_000_000) + let limited = GitHubBackend.rateLimitMessage(try response(403, ["x-ratelimit-remaining": "0", "x-ratelimit-reset": "1800000000"])) + #expect(limited.contains("60 checks an hour")) + #expect(limited.contains(reset.formatted(date: .omitted, time: .shortened))) + #expect(GitHubBackend.rateLimitMessage(try response(429, [:])).contains("Try again later")) + #expect(GitHubBackend.rateLimitMessage(try response(403, ["x-ratelimit-remaining": "41"])).contains("refused")) + } +} diff --git a/Tests/GitHubTests.swift b/Tests/GitHubTests.swift index 756e9d7..5fa7c63 100644 --- a/Tests/GitHubTests.swift +++ b/Tests/GitHubTests.swift @@ -1,4 +1,5 @@ import Foundation +@testable import UpdateWorkbench /// Offline fixtures; invoke run() from the repository's backend test entry point. enum GitHubTests { diff --git a/Tests/PresentationTests.swift b/Tests/PresentationTests.swift index a71762d..3ebc3e4 100644 --- a/Tests/PresentationTests.swift +++ b/Tests/PresentationTests.swift @@ -1,4 +1,5 @@ import Foundation +@testable import UpdateWorkbench /// Offline checks for the UI presentation rules (status precedence, hero copy, appearance default, path abbreviation). enum PresentationTests { diff --git a/Tests/SecurityBackendTests.swift b/Tests/SecurityBackendTests.swift index 89a6ffb..e5fe53a 100644 --- a/Tests/SecurityBackendTests.swift +++ b/Tests/SecurityBackendTests.swift @@ -1,21 +1,23 @@ import Foundation +import Testing +@testable import UpdateWorkbench -@main struct SecurityTests { - static func main() async throws { +enum SecurityTests { + static func run() async throws { let report = SecurityBackend.report(path: "/tmp/fixture.app", observedAt: "fixture", metadata: .init(status: 0, text: "Executable=/private/secret\nIdentifier=example.app\nTeamIdentifier=TEAM\nAuthority=Developer ID Application: Example\nCodeDirectory v=20500 flags=0x10000(runtime)"), verification: .init(status: 0, text: ""), gatekeeper: .init(status: 3, text: "rejected")) - precondition(report.summary.contains("Code signature verifies")) - precondition(report.summary.contains("Gatekeeper did not accept (exit 3)")) - precondition(report.details.contains("TeamIdentifier=TEAM")) - precondition(!report.details.contains("Executable=/private/secret")) - precondition(report.details.contains("flags=0x10000(runtime)")) + #expect(report.summary.contains("Code signature verifies")) + #expect(report.summary.contains("Gatekeeper did not accept (exit 3)")) + #expect(report.details.contains("TeamIdentifier=TEAM")) + #expect(!report.details.contains("Executable=/private/secret")) + #expect(report.details.contains("flags=0x10000(runtime)")) let unavailable = SecurityBackend.report(path: "/tmp/fixture.app", observedAt: "fixture", metadata: .init(status: nil, text: "launch failed"), verification: .init(status: nil, text: "timed out"), gatekeeper: .init(status: nil, text: "unavailable")) - precondition(unavailable.summary.contains("Unavailable")) - precondition(unavailable.details.contains("timed out")) + #expect(unavailable.summary.contains("Unavailable")) + #expect(unavailable.details.contains("timed out")) let invalid = await SecurityBackend.inspect(path: "relative.app") - precondition(invalid.summary == "Security inspection unavailable") + #expect(invalid.summary == "Security inspection unavailable") let data = try JSONEncoder().encode(report) let decoded = try JSONDecoder().decode(SecurityReport.self, from: data) - precondition(decoded.summary == report.summary) + #expect(decoded.summary == report.summary) print("PASS: security result separation, identity filtering, unavailable states, invalid paths, Codable") } } diff --git a/Tests/Suites.swift b/Tests/Suites.swift new file mode 100644 index 0000000..b390fcf --- /dev/null +++ b/Tests/Suites.swift @@ -0,0 +1,15 @@ +import Testing + +/// The offline suites, one test each. They run one after another: several share fixture folders, +/// disk image mounts and UserDefaults keys. +@Suite(.serialized) +struct OfflineSuites { + @Test func gitHub() throws { try GitHubTests.run() } + @Test func features() async throws { try await FeatureTests.run() } + @Test func presentation() throws { try PresentationTests.run() } + @Test func archiveSafety() throws { try ArchiveSafetyTests.run() } + @Test func workflow() throws { try WorkflowTests.run() } + @Test func diskImages() async throws { try await DiskImageTests.run() } + @Test func backend() async throws { try await BackendTests.run() } + @Test func security() async throws { try await SecurityTests.run() } +} diff --git a/Tests/VersionOrderTests.swift b/Tests/VersionOrderTests.swift new file mode 100644 index 0000000..a9ecd27 --- /dev/null +++ b/Tests/VersionOrderTests.swift @@ -0,0 +1,60 @@ +import Foundation +import Testing +@testable import UpdateWorkbench + +struct VersionOrderTests { + @Test(arguments: [ + ("1.10", "1.9"), + ("1.0", "1.0-beta.1"), // the release is newer than its beta + ("1.0", "1.0b2"), + ("1.0", "1.0rc1"), + ("1.0", "1.0 Preview"), + ("1.0-rc.1", "1.0-beta.2"), + ("1.0-beta.2", "1.0-beta.1"), + ("1.0-beta.1", "1.0-beta"), + ("1.0-beta", "1.0-alpha"), + ("1.0.1-beta", "1.0"), + ("1.0 (45)", "1.0"), // a trailing build number counts after the release + ("1.0 (46)", "1.0 (45)"), + ("v2.1", "2.0"), + ("2026.1", "2025.12.3"), + ("27.2.1", "15.0"), + ("1234", "1233"), + ]) + func newer(_ newer: String, _ older: String) { + #expect(SparkleBackend.isNewer(newer, than: older), "\(newer) should be newer than \(older)") + #expect(!SparkleBackend.isNewer(older, than: newer), "\(older) should not be newer than \(newer)") + } + + @Test(arguments: [ + ("2.0", "2.0.0"), // trailing zeros are the same version + ("14", "14.0"), + ("v1.2.3", "1.2.3"), + ("1.2.3+sha.5114f85", "1.2.3"), // semver build metadata is ignored + ("1.0RC1", "1.0rc1"), + ("1.0rc1", "1.0-rc.1"), + ]) + func same(_ lhs: String, _ rhs: String) { + #expect(VersionOrder.isSame(lhs, rhs), "\(lhs) and \(rhs) should be the same version") + #expect(!SparkleBackend.isNewer(lhs, than: rhs) && !SparkleBackend.isNewer(rhs, than: lhs)) + } + + @Test func unparsableVersionsFallBackToTextOrder() { + #expect(!VersionOrder.isSame("Unknown", "1.0")) + #expect(VersionOrder.isSame("Unknown", "unknown")) + #expect(SparkleBackend.isNewer("99999999999999999999999.1", than: "99999999999999999999999.0")) + } + + /// Beta testers are offered the final release, and the same version written differently isn't an update. + @Test func appcastSelection() throws { + let appcast = """ + + + + """ + let data = Data(appcast.utf8) + #expect(try SparkleBackend.parseAppcast(data, installedVersion: "2.0-beta.3")?.version == "2.0.0") + #expect(try SparkleBackend.parseAppcast(data, installedVersion: "2.0") == nil) + #expect(try SparkleBackend.parseAppcast(data, installedVersion: "2.0.1") == nil) + } +} diff --git a/Tests/WorkflowTests.swift b/Tests/WorkflowTests.swift index da11dc8..70e1b4b 100644 --- a/Tests/WorkflowTests.swift +++ b/Tests/WorkflowTests.swift @@ -1,14 +1,17 @@ import Combine import Foundation +@testable import UpdateWorkbench -/// Folder for fixture apps and disk images. test.sh points UW_TEST_TMP at a `.noindex` folder so -/// Spotlight and Launch Services never list test apps; Foundation's temporaryDirectory ignores TMPDIR. +/// Folder for fixture apps and disk images, always a `.noindex` folder so Spotlight and Launch Services +/// never list test apps. test.sh sets UW_TEST_TMP; a plain `swift test` uses one under the temporary directory. enum TestTemp { static let root: URL = { if let path = ProcessInfo.processInfo.environment["UW_TEST_TMP"], !path.isEmpty { return URL(fileURLWithPath: path, isDirectory: true) } - return FileManager.default.temporaryDirectory + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("UpdateWorkbenchTests.noindex", isDirectory: true) + try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + return folder }() } diff --git a/build.sh b/build.sh index 0c8d760..3f3ec85 100755 --- a/build.sh +++ b/build.sh @@ -1,6 +1,9 @@ #!/bin/bash set -euo pipefail cd "$(dirname "$0")" +# The one place the version is set. The app reads it back from Info.plist at runtime. +VERSION=0.4.1 +BUILD=7 # The app is built in dist.noindex/: Spotlight skips folders ending in .noindex, so development # builds never show up in Spotlight or Launchpad next to the installed app. APP=dist.noindex/UpdateWorkbench.app @@ -18,7 +21,7 @@ export SWIFTPM_MODULECACHE_OVERRIDE="$PWD/.build-cache" swift build --configuration release -debug-info-format none --scratch-path "$PWD/.build" --disable-sandbox BIN_DIR="$(swift build --configuration release --scratch-path "$PWD/.build" --disable-sandbox --show-bin-path)" cp "$BIN_DIR/UpdateWorkbench" "$APP/Contents/MacOS/UpdateWorkbench" -cat > "$APP/Contents/Info.plist" <<'PLIST' +cat > "$APP/Contents/Info.plist" < @@ -27,8 +30,8 @@ cat > "$APP/Contents/Info.plist" <<'PLIST' CFBundleNameUpdate Workbench CFBundleDisplayNameUpdate Workbench CFBundlePackageTypeAPPL -CFBundleShortVersionString0.4.0 -CFBundleVersion6 +CFBundleShortVersionString$VERSION +CFBundleVersion$BUILD CFBundleIconFileAppIcon LSMinimumSystemVersion14.0 NSHighResolutionCapable diff --git a/docs/validation.md b/docs/validation.md index 114c975..a644b47 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -21,7 +21,8 @@ These notes record what has been built, tested and observed on the development M - 0.4.0: `mas` 7.0.0 was installed with Homebrew on the development Mac at the user's request. `mas outdated --json` (read-only) reported no pending App Store updates for the 26 App Store apps `mas list` found; App Store lookups were intermittent: about half of the runs, in any environment, ended after roughly 60 seconds with a lookup timeout, exit status 1 and no results. The app reports this as a temporary App Store connection problem, and the App Store items say the check could not finish, rather than claiming that mas is missing. No `mas update` was run. - 0.4.0: the new screens were rendered offscreen in dark and light and reviewed. The menu bar status item itself can't be captured offscreen; its panel was rendered. -- Unreleased: builds moved to `dist.noindex/`, and test fixtures and release staging moved to temporary `.noindex` folders. After a build and a full test run, `mdfind "kMDItemCFBundleIdentifier == 'local.updateworkbench.app'"` listed only the installed copy in `/Applications`. +- 0.4.1: builds moved to `dist.noindex/`, and test fixtures and release staging moved to temporary `.noindex` folders. After a build and a full test run, `mdfind "kMDItemCFBundleIdentifier == 'local.updateworkbench.app'"` listed only the installed copy in `/Applications`. +- 0.4.1: `swift test` runs the offline suites (wrapped in Swift Testing, run one after another) plus new tests for version ordering and the GitHub rate-limit message; all 13 tests passed. GitHub was checked live with `curl`: a conditional request answered `304 Not Modified` still lowered `x-ratelimit-remaining` without a token, so ETag caching would not ease the unauthenticated limit and wasn't added. A release build reported its version and build in `Info.plist` and in the rendered sidebar. ## Not validated end to end diff --git a/test.sh b/test.sh index 8657ecd..66037bd 100755 --- a/test.sh +++ b/test.sh @@ -1,4 +1,6 @@ #!/bin/sh +# Runs the offline test suites with `swift test`. Extra arguments are passed through, +# for example `./test.sh --filter VersionOrderTests`. set -eu cd "$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" test_root="$(mktemp -d "${TMPDIR:-/tmp}/updateworkbench-tests.XXXXXX")" @@ -7,44 +9,7 @@ trap 'rm -rf "$test_root"' EXIT HUP INT TERM test_root="$(cd "$test_root" && pwd)" # Fixture apps are created under TMPDIR; a .noindex folder keeps them out of Spotlight and Launch Services. test_work_dir="$test_root/work.noindex" -mkdir -p "$test_work_dir/module-cache" "$test_work_dir/tmp" +mkdir -p "$test_work_dir/tmp" export TMPDIR="$test_work_dir/tmp/" UW_TEST_TMP="$test_work_dir/tmp" -# All backend sources; App.swift and AppServices.swift contain the SwiftUI entry point and UserNotifications calls. -backend_sources="Sources/UpdateWorkbench/Core.swift -Sources/UpdateWorkbench/SparkleBackend.swift -Sources/UpdateWorkbench/ArchiveSafety.swift -Sources/UpdateWorkbench/DiskImage.swift -Sources/UpdateWorkbench/TrustedSigners.swift -Sources/UpdateWorkbench/UpdateHistory.swift -Sources/UpdateWorkbench/Rules.swift -Sources/UpdateWorkbench/ReleaseNotes.swift -Sources/UpdateWorkbench/AppStoreCLI.swift -Sources/UpdateWorkbench/GitHubBackend.swift -Sources/UpdateWorkbench/SecurityBackend.swift -Sources/UpdateWorkbench/NetworkSettings.swift -Sources/UpdateWorkbench/ElectronBackend.swift -Sources/UpdateWorkbench/Discovery.swift -Sources/UpdateWorkbench/Maintenance.swift -Sources/UpdateWorkbench/Presentation.swift" -# shellcheck disable=SC2086 -xcrun swiftc -swift-version 6 -parse-as-library \ - -module-cache-path "$test_work_dir/module-cache" \ - $backend_sources \ - Tests/GitHubTests.swift \ - Tests/FeatureTests.swift \ - Tests/BackendTests.swift \ - Tests/PresentationTests.swift \ - Tests/ArchiveSafetyTests.swift \ - Tests/WorkflowTests.swift \ - Tests/DiskImageTests.swift \ - -o "$test_work_dir/backend-tests" -"$test_work_dir/backend-tests" - -for fixture in SecurityBackendTests; do - # shellcheck disable=SC2086 - xcrun swiftc -swift-version 6 -parse-as-library \ - -module-cache-path "$test_work_dir/module-cache" \ - $backend_sources \ - "Tests/$fixture.swift" -o "$test_work_dir/$fixture" - "$test_work_dir/$fixture" -done +export CLANG_MODULE_CACHE_PATH="$PWD/.build-cache" SWIFTPM_MODULECACHE_OVERRIDE="$PWD/.build-cache" +swift test --scratch-path "$PWD/.build" --disable-sandbox "$@"