diff --git a/AGENTS.md b/AGENTS.md index 62646de..b5366ed 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,4 +53,6 @@ iTimer 是一个 macOS 菜单栏计时器,用 SwiftUI 写,Swift Package 管 swift test # 核心逻辑测试 ``` -界面自测在 `Sources/ITimer/SelfTest.swift`。`goal`、`workflow`、`record`、`drawer` 几个场景支持 background 模式:不激活 App,事件直接发给窗口,不占用前台和鼠标。 +界面自测在 `Sources/ITimer/SelfTest.swift`。`goal`、`workflow`、`record`、`drawer`、`update` 几个场景支持 background 模式:不激活 App,事件直接发给窗口,不占用前台和鼠标。 + +`update` 场景用环境变量 `ITIMER_UPDATE_FEED` 指向本地的 releases JSON(可以用 `file://`),会真的下载、校验并替换正在运行的应用包,所以只对复制出来的应用跑(例如 `open -n -g --env ITIMER_UPDATE_FEED=file:///tmp/feed/releases.json /tmp/copy/iTimer.app`)。`ITIMER_UPDATE_RELAUNCH_PROBE` 可以指定一个代替 iTimer 被重新打开的探针应用,避免新开的 iTimer 读到真实数据。 diff --git a/CHANGELOG.md b/CHANGELOG.md index 601f966..48a5e51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ ## [未发布] +## [1.12.0] - 2026-10-19 + +### 新增 + +- 软件更新:启动时和之后每天检查一次 GitHub 上有没有新版本,只读取版本信息;可以在「设置 › 软件更新」里关掉自动检查。 +- 可以随时在菜单栏「iTimer › 检查更新…」或「设置 › 软件更新」里手动检查更新。 +- 有新版本时,菜单栏面板底部出现「新版本 x.y.z」按钮,主窗口图标栏的设置图标亮一个小圆点;设置里列出新版本的更新内容,落后几个版本时一起列出。 +- 在设置里点「下载并安装」,下载这台 Mac 芯片对应的安装包,校验 SHA-256 后替换当前的 iTimer 并自动重新打开,正在计时的任务照常计时;下载中途可以取消。在 Apple 芯片上运行的 Intel 版会换成 Apple Silicon 版。 +- iTimer 所在的位置没有写入权限时,改为打开下载好的安装包,把 iTimer 拖到「应用程序」即可。 + ## [1.11.0] - 2026-10-19 ### 新增 @@ -211,7 +221,8 @@ - 在面板里暂停、完成任务时,面板不再塌掉或自己关上:面板开着时冻结菜单栏文字,并锁定面板高度。 -[未发布]: https://github.com/DueGin/iTimer/compare/v1.11.0...HEAD +[未发布]: https://github.com/DueGin/iTimer/compare/v1.12.0...HEAD +[1.12.0]: https://github.com/DueGin/iTimer/compare/v1.11.0...v1.12.0 [1.11.0]: https://github.com/DueGin/iTimer/compare/v1.10.5...v1.11.0 [1.10.5]: https://github.com/DueGin/iTimer/compare/v1.10.4...v1.10.5 [1.10.4]: https://github.com/DueGin/iTimer/compare/v1.10.3...v1.10.4 diff --git a/README.md b/README.md index f5f3331..dcd26a1 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,8 @@ 当前安装包使用临时签名,尚未经过 Apple Developer ID 签名和公证。首次打开如被 macOS 拦截,请在「系统设置 › 隐私与安全性」中选择「仍要打开」。 +装好之后,以后的版本可以直接在应用里更新:有新版本时,菜单栏面板底部会出现「新版本 x.y.z」按钮,在「设置 › 软件更新」里点「下载并安装」即可,详见下文「软件更新」。 + ## 定位 | | | @@ -104,7 +106,9 @@ **提醒**:进入脑裂时发通知,建议用「只做这个」收拢线程;单个任务连续计时 3 小时会提醒你是不是忘了暂停;工作流里完成一步时,告诉你哪些下一步已经自动开始、哪些可以开始了。这几种提醒都能在设置里关掉。 -**设置(⌘,)**:脑裂线、提醒开关、日历同步、登录时启动、打开数据文件所在位置。 +**软件更新**:启动时和之后每天查一次 GitHub Releases 上有没有新版本,只读取版本信息,可以在设置里关掉;也可以在菜单栏「iTimer › 检查更新…」或设置里手动检查。有新版本时,菜单栏面板底部出现「新版本 x.y.z」按钮,主窗口图标栏的设置图标亮一个小圆点。设置里列出新版本的更新内容(落后几个版本时一起列出),点「下载并安装」,iTimer 会下载这台 Mac 芯片对应的安装包,按 Release 附带的 SHA-256 校验,替换当前的 iTimer 并自动重新打开,正在计时的任务照常计时。如果 iTimer 所在的位置没有写入权限,会改为打开下载好的安装包,拖到「应用程序」即可。 + +**设置(⌘,)**:脑裂线、提醒开关、日历同步、登录时启动、打开数据文件所在位置、软件更新。 ## 设计原则 @@ -138,6 +142,8 @@ git push origin v1.8.3 [发版流水线](.github/workflows/release.yml) 会检查 tag 与应用版本号是否一致,以及 CHANGELOG 是否有对应版本的更新内容;在 Apple Silicon 和 Intel runner 上分别运行核心测试、构建应用并打包。两边都成功后,自动创建 GitHub Release,上传两个 DMG 和 `SHA256SUMS`,更新说明取自该版本的 CHANGELOG。 +应用内更新按 `iTimer-x.y.z-macos-<架构>.dmg` 这个文件名找安装包,用附件的 SHA-256(或 `SHA256SUMS`)校验,更新说明同样取自 Release 正文,所以不要手动改附件名或删掉 `SHA256SUMS`。 + 流水线使用 GitHub 自带的 `GITHUB_TOKEN`,发布 job 有 `contents: write` 权限,无需配置额外 Secret。上传附件时先创建草稿,全部上传成功再公开;失败后可在 Actions 中重新运行,继续上传草稿中的附件。已公开的 Release 不会被覆盖。 如果 tag 推送后没有出现运行记录,可在 Actions ›「构建与发布 iTimer」› Run workflow 中选择 `main`,填入已有的版本 tag(如 `v1.8.2`)。手动运行会检出该 tag 的代码,并执行相同的版本检查、双架构构建和发布流程。 diff --git a/Sources/ITimer/ITimerApp.swift b/Sources/ITimer/ITimerApp.swift index 544852b..8978ec7 100644 --- a/Sources/ITimer/ITimerApp.swift +++ b/Sources/ITimer/ITimerApp.swift @@ -14,6 +14,9 @@ struct ITimerApp: App { .windowResizability(.contentMinSize) .windowToolbarStyle(.unifiedCompact) .commands { + CommandGroup(after: .appInfo) { + UpdateCommands() + } CommandGroup(replacing: .newItem) { NewItemCommands(store: .shared) } @@ -54,6 +57,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { CalendarManager.shared.attach(to: TaskStore.shared) startClock() SelfTest.runIfRequested() + if DebugLaunchFile.current == nil { + Updater.shared.startAutomaticChecks() + } } startNudges() } diff --git a/Sources/ITimer/MainRail.swift b/Sources/ITimer/MainRail.swift index 650fa6c..3fd625d 100644 --- a/Sources/ITimer/MainRail.swift +++ b/Sources/ITimer/MainRail.swift @@ -20,9 +20,17 @@ struct MainRail: View { Spacer(minLength: 12) SettingsLink { icon("gearshape", selected: false) + .overlay(alignment: .topTrailing) { + if Updater.shared.offer != nil { + Circle() + .fill(Color.accentColor) + .frame(width: 7, height: 7) + .offset(x: -5, y: 5) + } + } } .buttonStyle(railStyle(selected: false)) - .help("设置(⌘,)") + .help(Updater.shared.offer.map { "设置(⌘,)· 新版本 \($0.version.description) 可以更新了" } ?? "设置(⌘,)") .accessibilityLabel("设置") .accessibilityIdentifier("rail-settings") } diff --git a/Sources/ITimer/MenuBarView.swift b/Sources/ITimer/MenuBarView.swift index 15c0e5f..0a4fbd0 100644 --- a/Sources/ITimer/MenuBarView.swift +++ b/Sources/ITimer/MenuBarView.swift @@ -888,6 +888,17 @@ struct MenuBarView: View { NSApp.activate(ignoringOtherApps: true) openSettings() } + if let offer = Updater.shared.offer { + Button { + NSApp.activate(ignoringOtherApps: true) + openSettings() + } label: { + Label("新版本 \(offer.version.description)", systemImage: "arrow.down.circle.fill") + } + .buttonStyle(PillButtonStyle(tint: .accentColor)) + .help("iTimer \(offer.version.description) 可以更新了,在设置里查看更新内容并安装") + .accessibilityIdentifier("update-badge") + } Spacer() footerButton("退出", systemImage: "power", id: "quit-app") { NSApp.terminate(nil) } } diff --git a/Sources/ITimer/SelfTest.swift b/Sources/ITimer/SelfTest.swift index 6ac71f1..d64f340 100644 --- a/Sources/ITimer/SelfTest.swift +++ b/Sources/ITimer/SelfTest.swift @@ -22,6 +22,7 @@ enum SelfTest { case "milestone": passed = await exerciseMilestoneExpansion() case "record": passed = await exerciseRecordTimes() case "drawer": passed = await exerciseDrawer() + case "update": passed = await exerciseUpdate() default: passed = await exercise() } note(passed ? "PASS" : "FAIL") @@ -725,6 +726,112 @@ enum SelfTest { } } +// MARK: - Software update + +extension SelfTest { + /// 设置 › 软件更新 against a local feed (`ITIMER_UPDATE_FEED`): finds the + /// newer release, shows it in 设置 and the panel footer, then downloads, + /// checks and swaps this very bundle. `ITIMER_UPDATE_RELAUNCH_PROBE` + /// names an app for the relaunch helper to open once this process exits + /// (not iTimer itself, which would open on the real data). + /// Window events only, so it also runs in background mode. + static func exerciseUpdate() async -> Bool { + let updater = Updater.shared + guard updater.feedOverridden else { + note("ITIMER_UPDATE_FEED is not set") + return false + } + // The app's defaults are the user's; put the check time back after. + let defaults = UserDefaults.standard + let savedChecked = defaults.object(forKey: Preferences.updateLastChecked) + defer { defaults.set(savedChecked, forKey: Preferences.updateLastChecked) } + + func present(_ identifier: String) -> Bool { find(identifier: identifier, depth: 40) != nil } + func press(_ identifier: String) -> Bool { + guard let element = find(identifier: identifier, depth: 40) else { + note("missing \(identifier)") + return false + } + return AXUIElementPerformAction(element, kAXPressAction as CFString) == .success + } + + let settings = NSWindow(contentRect: NSRect(x: 120, y: 80, width: 460, height: 760), styleMask: [.titled], backing: .buffered, defer: false) + settings.title = "iTimer 软件更新自检" + settings.isReleasedWhenClosed = false + settings.appearance = NSAppearance(named: .aqua) + settings.contentView = NSHostingView(rootView: SettingsView(store: .shared)) + await activateUnlessBackground() + bringForward(settings) + defer { settings.orderOut(nil) } + try? await Task.sleep(for: .milliseconds(600)) + + guard press("update-check"), + await wait(for: 10, label: "check", until: { updater.offer != nil || updater.outcome != nil }), + let offer = updater.offer else { + note("check found no update: \(String(describing: updater.outcome)) current=\(updater.currentVersion)") + return false + } + try? await Task.sleep(for: .milliseconds(300)) + guard present("update-offer"), present("update-notes"), present("update-install") else { + note("设置 does not show the offer, its notes and the install button") + return false + } + snapshot(settings, to: "/tmp/itimer-update-settings.png") + settings.appearance = NSAppearance(named: .darkAqua) + try? await Task.sleep(for: .milliseconds(150)) + snapshot(settings, to: "/tmp/itimer-update-settings-dark.png") + settings.appearance = NSAppearance(named: .aqua) + note("check offered \(offer.version) (\(offer.installer.name)), notes for \(offer.notes.map(\.version.description))") + + let panel = NSWindow(contentRect: NSRect(x: 600, y: 80, width: 380, height: 640), styleMask: [.titled], backing: .buffered, defer: false) + panel.title = "iTimer 面板更新自检" + panel.isReleasedWhenClosed = false + panel.appearance = NSAppearance(named: .aqua) + panel.contentView = NSHostingView(rootView: MenuBarView(store: .shared).background(.regularMaterial)) + bringForward(panel) + try? await Task.sleep(for: .milliseconds(600)) + guard present("update-badge") else { + panel.orderOut(nil) + note("the panel footer does not point at the update") + return false + } + snapshot(panel, to: "/tmp/itimer-update-panel.png") + panel.orderOut(nil) + note("panel footer shows the new version") + + // Swap the bundle but stay running; the relaunch is checked below. + updater.finishInstall = { _ in } + guard press("update-install"), + await wait(for: 60, label: "install", until: { updater.outcome != nil && !updater.isBusy }) else { + return false + } + guard updater.outcome == .installed(offer.version) else { + note("install ended with \(String(describing: updater.outcome))") + return false + } + try? await Task.sleep(for: .milliseconds(300)) + snapshot(settings, to: "/tmp/itimer-update-installed.png") + let info = NSDictionary(contentsOf: Bundle.main.bundleURL.appendingPathComponent("Contents/Info.plist")) + let installed = info?["CFBundleShortVersionString"] as? String + guard installed == offer.version.description else { + note("bundle on disk is \(installed ?? "unreadable"), expected \(offer.version)") + return false + } + note("downloaded, checked and swapped \(Bundle.main.bundleURL.path) to \(installed ?? "")") + + if let probe = ProcessInfo.processInfo.environment["ITIMER_UPDATE_RELAUNCH_PROBE"] { + do { + try Updater.spawnRelaunch(of: URL(fileURLWithPath: probe)) + } catch { + note("relaunch helper did not start: \(error)") + return false + } + note("relaunch helper waits to open \(probe)") + } + return true + } +} + // MARK: - Side drawer extension SelfTest { diff --git a/Sources/ITimer/SettingsView.swift b/Sources/ITimer/SettingsView.swift index 4b484f9..41c6be9 100644 --- a/Sources/ITimer/SettingsView.swift +++ b/Sources/ITimer/SettingsView.swift @@ -7,6 +7,8 @@ enum Preferences { static let brainSplitNudge = "itimer.nudge.brainSplit" static let longRunNudge = "itimer.nudge.longRun" static let workflowNudge = "itimer.nudge.workflow" + static let autoUpdateCheck = "itimer.update.auto" + static let updateLastChecked = "itimer.update.lastChecked" static func enabled(_ key: String) -> Bool { UserDefaults.standard.object(forKey: key) as? Bool ?? true @@ -76,6 +78,8 @@ struct SettingsView: View { .buttonStyle(PillButtonStyle(tint: .accentColor)) } } + + UpdateSection(updater: .shared) } .formStyle(.grouped) .frame(width: 460) diff --git a/Sources/ITimer/UpdateSection.swift b/Sources/ITimer/UpdateSection.swift new file mode 100644 index 0000000..668683b --- /dev/null +++ b/Sources/ITimer/UpdateSection.swift @@ -0,0 +1,253 @@ +import AppKit +import ITimerCore +import SwiftUI + +/// 设置 › 软件更新: this version, the daily check, and — when GitHub has a +/// newer release — what changed and the button that installs it. +struct UpdateSection: View { + var updater: Updater + @AppStorage(Preferences.autoUpdateCheck) private var autoCheck = true + + var body: some View { + Section { + LabeledContent("当前版本", value: "\(updater.currentVersion)(build \(updater.build))") + Toggle("自动检查更新", isOn: $autoCheck) + if let offer = updater.offer { + offerHeader(offer) + ReleaseNotesView(notes: offer.notes) + installRow + if let message = offerMessage { + Text(message.text) + .font(.caption) + .foregroundStyle(message.isError ? AnyShapeStyle(.red) : AnyShapeStyle(.secondary)) + .fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier("update-message") + } + } else { + statusRow + } + } header: { + Text("软件更新") + } footer: { + Text("每天查一次 GitHub 上的新版本,只读取版本信息。安装前会校验安装包的 SHA-256,装好后 iTimer 自动重新打开,计时不受影响。") + } + } + + // MARK: nothing to install + + private var statusRow: some View { + let status = self.status + return HStack(spacing: 10) { + VStack(alignment: .leading, spacing: 2) { + Text(status.title) + if let detail = status.detail { + Text(detail) + .font(.caption) + .foregroundStyle(status.isError ? AnyShapeStyle(.red) : AnyShapeStyle(.secondary)) + .fixedSize(horizontal: false, vertical: true) + } + } + .accessibilityElement(children: .combine) + .accessibilityIdentifier("update-status") + Spacer() + if updater.activity == .checking { + ProgressView() + .controlSize(.small) + } + Button("检查更新") { + Task { await updater.check() } + } + .buttonStyle(PillButtonStyle(tint: .accentColor)) + .disabled(updater.isBusy || updater.awaitsRelaunch) + .accessibilityIdentifier("update-check") + } + } + + private var status: (title: String, detail: String?, isError: Bool) { + let checked = updater.lastChecked.map { "上次检查:\($0.formatted(.relative(presentation: .named)))" } + if updater.activity == .checking { return ("正在检查…", checked, false) } + switch updater.outcome { + case .checkFailed(let reason)?: return ("检查更新失败", reason, true) + case .installed(let version)?: return ("已安装 \(version)", "退出 iTimer 再打开就是新版本。", false) + default: break + } + guard updater.lastChecked != nil else { return ("还没有检查过", nil, false) } + return ("已是最新版本", checked, false) + } + + // MARK: a newer release + + private func offerHeader(_ offer: UpdateOffer) -> some View { + HStack(alignment: .center, spacing: 10) { + Image(systemName: "arrow.down.circle.fill") + .font(.system(size: 22)) + .foregroundStyle(Color.accentColor) + VStack(alignment: .leading, spacing: 2) { + Text("发现新版本 \(offer.version.description)") + .font(.headline) + Text(detail(offer)) + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + Button { + NSWorkspace.shared.open(offer.pageURL) + } label: { + Label("发布页", systemImage: "arrow.up.right") + } + .buttonStyle(PillButtonStyle(tint: .accentColor)) + .help(offer.pageURL.absoluteString) + } + .accessibilityIdentifier("update-offer") + } + + private func detail(_ offer: UpdateOffer) -> String { + var parts: [String] = [] + if let published = offer.publishedAt { + parts.append("\(published.formatted(.dateTime.year().month().day())) 发布") + } + parts.append(Self.bytes(offer.installer.size)) + if offer.notes.count > 1 { + parts.append("包含 \(offer.notes.count) 个版本的更新") + } + return parts.joined(separator: " · ") + } + + @ViewBuilder + private var installRow: some View { + switch updater.activity { + case .downloading(let received, let total): + HStack(spacing: 10) { + ProgressView(value: Double(min(received, total)), total: Double(max(total, 1))) + Text("\(Self.bytes(received)) / \(Self.bytes(total))") + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + Button("取消") { updater.cancelInstall() } + .buttonStyle(PillButtonStyle(tint: .secondary)) + .accessibilityIdentifier("update-cancel") + } + .accessibilityIdentifier("update-progress") + case .installing: + HStack(spacing: 8) { + ProgressView() + .controlSize(.small) + Text("正在校验并安装…") + .foregroundStyle(.secondary) + } + .accessibilityIdentifier("update-installing") + case .idle, .checking: + HStack(spacing: 10) { + Button { + updater.install() + } label: { + Label("下载并安装", systemImage: "arrow.down") + } + .buttonStyle(ActionButtonStyle(prominent: true, tint: .accentColor)) + .disabled(updater.isBusy) + .accessibilityIdentifier("update-install") + Spacer() + Text("安装后 iTimer 会重新打开") + .font(.caption) + .foregroundStyle(.secondary) + } + } + } + + private var offerMessage: (text: String, isError: Bool)? { + switch updater.outcome { + case .installFailed(let reason)?: ("更新失败:\(reason)", true) + case .checkFailed(let reason)?: ("检查更新失败:\(reason)", true) + case .manual(let text)?: (text, false) + default: nil + } + } + + private static func bytes(_ count: Int64) -> String { + ByteCountFormatter.string(fromByteCount: count, countStyle: .file) + } +} + +/// What changed, newest version first, in a box that scrolls once it +/// passes about a dozen lines. +private struct ReleaseNotesView: View { + var notes: [ReleaseNotes] + @State private var contentHeight: CGFloat = 0 + private let maxHeight: CGFloat = 220 + + var body: some View { + let scrolls = contentHeight > maxHeight + ScrollView { + content + .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { contentHeight = $0 } + } + .scrollIndicators(scrolls ? .automatic : .never) + .scrollDisabled(!scrolls) + .frame(height: min(max(contentHeight, 24), maxHeight)) + .background(Color.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + .accessibilityIdentifier("update-notes") + } + + private var content: some View { + VStack(alignment: .leading, spacing: 10) { + ForEach(notes, id: \.version) { release in + VStack(alignment: .leading, spacing: 4) { + if notes.count > 1 { + Text(release.version.description) + .font(.callout.weight(.semibold)) + } + if release.blocks.isEmpty { + Text("这个版本没有写更新说明。") + .foregroundStyle(.secondary) + } + ForEach(Array(release.blocks.enumerated()), id: \.offset) { _, block in + blockView(block) + } + } + } + } + .font(.callout) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(10) + } + + @ViewBuilder + private func blockView(_ block: ReleaseNotes.Block) -> some View { + switch block { + case .heading(let text): + Text(text) + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + .padding(.top, 2) + case .item(let text): + HStack(alignment: .firstTextBaseline, spacing: 6) { + Text("•") + .foregroundStyle(.secondary) + Text(Self.inline(text)) + .fixedSize(horizontal: false, vertical: true) + } + case .text(let text): + Text(Self.inline(text)) + .fixedSize(horizontal: false, vertical: true) + } + } + + /// `代码` and **粗体** inside a line. + private static func inline(_ text: String) -> AttributedString { + let options = AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace) + return (try? AttributedString(markdown: text, options: options)) ?? AttributedString(text) + } +} + +/// iTimer › 检查更新…: opens 设置, where the answer shows. +struct UpdateCommands: View { + @Environment(\.openSettings) private var openSettings + + var body: some View { + Button("检查更新…") { + NSApp.activate(ignoringOtherApps: true) + openSettings() + Task { await Updater.shared.check() } + } + } +} diff --git a/Sources/ITimer/Updater.swift b/Sources/ITimer/Updater.swift new file mode 100644 index 0000000..6c6f2b1 --- /dev/null +++ b/Sources/ITimer/Updater.swift @@ -0,0 +1,354 @@ +import AppKit +import ITimerCore +import Observation + +/// Looks for a newer iTimer on GitHub Releases, downloads the DMG for this +/// Mac, checks its SHA-256, swaps the app bundle in place and reopens it. +@MainActor +@Observable +final class Updater { + static let shared = Updater() + + static let releasesPage = URL(string: "https://github.com/DueGin/iTimer/releases")! + private static let releasesAPI = URL(string: "https://api.github.com/repos/DueGin/iTimer/releases?per_page=20")! + /// Automatic checks: once at launch, then whenever this much has passed. + private static let checkInterval: TimeInterval = 24 * 3600 + + enum Activity: Equatable { + case idle + case checking + case downloading(received: Int64, total: Int64) + case installing + } + + /// How the last check or install ended, for 设置 to say. + enum Outcome: Equatable { + case upToDate + case checkFailed(String) + case installFailed(String) + /// Downloaded and checked, but this copy can't be replaced where it + /// is; the DMG was opened for a drag-install. + case manual(String) + /// In place; takes effect when iTimer opens again. + case installed(AppVersion) + } + + private(set) var offer: UpdateOffer? + private(set) var activity: Activity = .idle + private(set) var outcome: Outcome? + private(set) var lastChecked: Date? + + let currentVersion: AppVersion + let build: String + /// `ITIMER_UPDATE_FEED` points the updater at another releases JSON + /// (`file://` works) for testing; such a feed may serve `file://` assets. + let feedOverridden: Bool + private let feedURL: URL + + /// Runs once the new bundle is in place. Self-test swaps it out. + var finishInstall: @MainActor (URL) throws -> Void = { try Updater.relaunch($0) } + + private var installWork: Task? + private var schedule: Task? + + private let session: URLSession = { + let configuration = URLSessionConfiguration.ephemeral + configuration.requestCachePolicy = .reloadIgnoringLocalCacheData + configuration.timeoutIntervalForRequest = 30 + return URLSession(configuration: configuration) + }() + + private init() { + let info = Bundle.main.infoDictionary ?? [:] + currentVersion = (info["CFBundleShortVersionString"] as? String).flatMap(AppVersion.init) ?? AppVersion(0, 0, 0) + build = info["CFBundleVersion"] as? String ?? "?" + if let override = ProcessInfo.processInfo.environment["ITIMER_UPDATE_FEED"], let url = URL(string: override), !override.isEmpty { + feedURL = url + feedOverridden = true + } else { + feedURL = Self.releasesAPI + feedOverridden = false + } + lastChecked = UserDefaults.standard.object(forKey: Preferences.updateLastChecked) as? Date + } + + var isBusy: Bool { activity != .idle } + + /// A new version is already in place; this process still reports the + /// old one, so checking again would offer the same release. + var awaitsRelaunch: Bool { + if case .installed? = outcome { return true } + return false + } + + // MARK: checking + + /// Checks at launch and then daily, while 自动检查更新 is on. + func startAutomaticChecks() { + guard schedule == nil else { return } + schedule = Task { + // Let launch settle first. + try? await Task.sleep(for: .seconds(5)) + var first = true + while !Task.isCancelled { + let due = first || lastChecked.map { Date().timeIntervalSince($0) >= Self.checkInterval } ?? true + if due, Preferences.enabled(Preferences.autoUpdateCheck) { + await check(userInitiated: false) + } + first = false + try? await Task.sleep(for: .seconds(3600)) + } + } + } + + /// A background check keeps quiet when it fails: being offline is normal. + func check(userInitiated: Bool = true) async { + guard activity == .idle, !awaitsRelaunch else { return } + activity = .checking + if userInitiated { outcome = nil } + defer { activity = .idle } + do { + var request = URLRequest(url: feedURL) + request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept") + request.setValue("2022-11-28", forHTTPHeaderField: "X-GitHub-Api-Version") + request.setValue("iTimer/\(currentVersion)", forHTTPHeaderField: "User-Agent") + let (data, response) = try await session.data(for: request) + try Self.requireSuccess(response) + let releases = try GitHubRelease.list(from: data) + offer = UpdateCatalog.offer(in: releases, current: currentVersion, architecture: Self.architecture) + if offer == nil { + outcome = .upToDate + } else if case .upToDate? = outcome { + outcome = nil + } + lastChecked = Date() + UserDefaults.standard.set(lastChecked, forKey: Preferences.updateLastChecked) + } catch { + if userInitiated { outcome = .checkFailed(Self.describe(error)) } + } + } + + // MARK: installing + + func install() { + guard let offer, activity == .idle else { return } + outcome = nil + activity = .downloading(received: 0, total: offer.installer.size) + installWork = Task { + do { + try await install(offer) + } catch is CancellationError { + activity = .idle + } catch let error as URLError where error.code == .cancelled { + activity = .idle + } catch { + activity = .idle + outcome = .installFailed(Self.describe(error)) + } + } + } + + func cancelInstall() { + guard case .downloading = activity else { return } + installWork?.cancel() + } + + private func install(_ offer: UpdateOffer) async throws { + // The checksum first: without one there is no point downloading. + let expected = try await checksum(for: offer) + let dmg = try await download(offer.installer) + activity = .installing + let target = Bundle.main.bundleURL + let bundleID = Bundle.main.bundleIdentifier ?? "" + let problem = try await Task.detached { + guard try UpdateInstaller.sha256(of: dmg) == expected else { + try? FileManager.default.removeItem(at: dmg) + throw UpdateError("下载的安装包校验不通过,已删除,请重试。") + } + return UpdateInstaller.inPlaceProblem(for: target) + }.value + if let problem { + installByHand(dmg, because: problem) + return + } + let staged = try await Task.detached { + try UpdateInstaller.stage(dmg: dmg, version: offer.version, bundleID: bundleID, replacing: target) + }.value + do { + try await Task.detached { + try UpdateInstaller.swap(target, with: staged) + }.value + } catch { + try? FileManager.default.removeItem(at: staged.deletingLastPathComponent()) + installByHand(dmg, because: Self.describe(error)) + return + } + try? FileManager.default.removeItem(at: dmg) + self.offer = nil + activity = .idle + outcome = .installed(offer.version) + // If reopening fails, 设置 says to reopen by hand. + try? finishInstall(target) + } + + /// The DMG is fine but this copy can't be swapped: open it for a + /// drag-install, which asks for a password where needed. + private func installByHand(_ dmg: URL, because problem: String) { + NSWorkspace.shared.open(dmg) + activity = .idle + let reason = problem.hasSuffix("。") ? String(problem.dropLast()) : problem + outcome = .manual("\(reason),无法直接替换。已打开下载好的安装包,把 iTimer 拖到「应用程序」替换旧版本即可。") + } + + private func checksum(for offer: UpdateOffer) async throws -> String { + if let digest = Checksum.sha256(digest: offer.installer.digest) { return digest } + guard let sums = offer.checksums else { + throw UpdateError("这个版本没有提供校验值,无法确认安装包完整,请到发布页手动下载。") + } + try requireAllowed(sums.downloadURL) + let (data, response) = try await session.data(from: sums.downloadURL) + try Self.requireSuccess(response) + guard let hex = Checksum.sha256(sums: String(decoding: data, as: UTF8.self), name: offer.installer.name) else { + throw UpdateError("SHA256SUMS 里没有这个安装包,请到发布页手动下载。") + } + return hex + } + + /// Into Caches, replacing earlier downloads. Kept when the install + /// falls back to a drag-install. + private func download(_ asset: GitHubRelease.Asset) async throws -> URL { + try requireAllowed(asset.downloadURL) + let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let folder = caches.appendingPathComponent("\(Bundle.main.bundleIdentifier ?? "iTimer")/Updates", isDirectory: true) + try? FileManager.default.removeItem(at: folder) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + let fallbackTotal = asset.size + return try await FileDownload.run(asset.downloadURL, to: folder.appendingPathComponent(asset.name)) { received, expected in + Task { @MainActor in + let updater = Updater.shared + guard case .downloading = updater.activity else { return } + updater.activity = .downloading(received: received, total: expected > 0 ? expected : fallbackTotal) + } + } + } + + /// GitHub serves everything over HTTPS; only a test feed may hand out + /// local files. + private func requireAllowed(_ url: URL) throws { + guard url.scheme == "https" || (feedOverridden && url.isFileURL) else { + throw UpdateError("下载地址不安全:\(url.absoluteString)") + } + } + + /// Waits for this process to exit, then opens `app`, so the new copy + /// starts fresh rather than alongside the old one. + static func spawnRelaunch(of app: URL) throws { + let helper = Process() + helper.executableURL = URL(fileURLWithPath: "/bin/sh") + helper.arguments = [ + "-c", + "while /bin/kill -0 \"$0\" 2>/dev/null; do /bin/sleep 0.2; done; /usr/bin/open \"$1\"", + String(ProcessInfo.processInfo.processIdentifier), + app.path, + ] + try helper.run() + } + + static func relaunch(_ app: URL) throws { + try spawnRelaunch(of: app) + NSApp.terminate(nil) + } + + // MARK: helpers + + /// This Mac's chip rather than this build's: an Intel copy running + /// under Rosetta moves to the Apple Silicon DMG. + nonisolated static var architecture: String { + var translated: Int32 = 0 + var size = MemoryLayout.size + if sysctlbyname("sysctl.proc_translated", &translated, &size, nil, 0) == 0, translated == 1 { + return "arm64" + } + #if arch(arm64) + return "arm64" + #else + return "x86_64" + #endif + } + + /// Local files answer without a status code. + nonisolated static func requireSuccess(_ response: URLResponse?) throws { + guard let http = response as? HTTPURLResponse else { return } + switch http.statusCode { + case 200..<300: return + case 403, 429: throw UpdateError("GitHub 暂时限制了访问次数,过一会儿再试") + default: throw UpdateError("服务器返回 \(http.statusCode)") + } + } + + private static func describe(_ error: Error) -> String { + if let error = error as? UpdateError { return error.message } + if let error = error as? URLError { + switch error.code { + case .notConnectedToInternet, .networkConnectionLost: return "没有网络连接" + case .timedOut: return "连接超时" + case .cannotFindHost, .cannotConnectToHost, .dnsLookupFailed: return "连不上 GitHub" + default: break + } + } + if error is DecodingError { return "发布信息的格式无法识别" } + return error.localizedDescription + } +} + +/// One URLSession download with progress, as a single async call. +private final class FileDownload: NSObject, URLSessionDownloadDelegate, @unchecked Sendable { + // Delegate callbacks arrive one at a time on the session's queue; the + // continuation is set before the task is resumed. + private let destination: URL + private let progress: @Sendable (Int64, Int64) -> Void + private var continuation: CheckedContinuation? + private var moved: Result? + + private init(destination: URL, progress: @escaping @Sendable (Int64, Int64) -> Void) { + self.destination = destination + self.progress = progress + } + + static func run(_ url: URL, to destination: URL, progress: @escaping @Sendable (Int64, Int64) -> Void) async throws -> URL { + let delegate = FileDownload(destination: destination, progress: progress) + let configuration = URLSessionConfiguration.ephemeral + configuration.timeoutIntervalForRequest = 60 + let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + defer { session.finishTasksAndInvalidate() } + let task = session.downloadTask(with: url) + return try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + delegate.continuation = continuation + task.resume() + } + } onCancel: { + task.cancel() + } + } + + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + progress(totalBytesWritten, totalBytesExpectedToWrite) + } + + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + // The temporary file is deleted as soon as this returns. + moved = Result { + try Updater.requireSuccess(downloadTask.response) + try? FileManager.default.removeItem(at: destination) + try FileManager.default.moveItem(at: location, to: destination) + return destination + } + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + let result = error.map { .failure($0) } ?? moved ?? .failure(UpdateError("下载没有完成")) + continuation?.resume(with: result) + continuation = nil + } +} diff --git a/Sources/ITimerCore/Update.swift b/Sources/ITimerCore/Update.swift new file mode 100644 index 0000000..29c5865 --- /dev/null +++ b/Sources/ITimerCore/Update.swift @@ -0,0 +1,191 @@ +import Foundation + +/// An app version, `x.y.z`. Release tags carry a leading `v`; anything +/// after the numbers (a `-beta` suffix) is not a release. +public struct AppVersion: Comparable, Hashable, Sendable, CustomStringConvertible { + public let major: Int + public let minor: Int + public let patch: Int + + public init(_ major: Int, _ minor: Int, _ patch: Int) { + self.major = major + self.minor = minor + self.patch = patch + } + + /// "1.11.0", "v1.11.0"; a missing minor or patch counts as 0. + public init?(_ text: String) { + var text = Substring(text.trimmingCharacters(in: .whitespaces)) + if text.first == "v" || text.first == "V" { text = text.dropFirst() } + let parts = text.split(separator: ".", omittingEmptySubsequences: false) + guard (1...3).contains(parts.count) else { return nil } + var numbers: [Int] = [] + for part in parts { + guard !part.isEmpty, part.allSatisfy({ ("0"..."9").contains($0) }), let number = Int(part) else { return nil } + numbers.append(number) + } + while numbers.count < 3 { numbers.append(0) } + self.init(numbers[0], numbers[1], numbers[2]) + } + + public var description: String { "\(major).\(minor).\(patch)" } + + public static func < (lhs: AppVersion, rhs: AppVersion) -> Bool { + (lhs.major, lhs.minor, lhs.patch) < (rhs.major, rhs.minor, rhs.patch) + } +} + +/// One entry of GitHub's releases API, only the fields the updater reads. +public struct GitHubRelease: Decodable, Equatable, Sendable { + public struct Asset: Decodable, Equatable, Sendable { + public var name: String + public var size: Int64 + public var downloadURL: URL + /// `sha256:`. GitHub fills it for assets uploaded since 2025; + /// older ones only have the release's SHA256SUMS. + public var digest: String? + + private enum CodingKeys: String, CodingKey { + case name, size, digest + case downloadURL = "browser_download_url" + } + } + + public var tagName: String + public var name: String? + public var body: String? + public var pageURL: URL + public var draft: Bool + public var prerelease: Bool + public var publishedAt: Date? + public var assets: [Asset] + + private enum CodingKeys: String, CodingKey { + case name, body, draft, prerelease, assets + case tagName = "tag_name" + case pageURL = "html_url" + case publishedAt = "published_at" + } + + /// The array `GET /repos/{owner}/{repo}/releases` returns. + public static func list(from data: Data) throws -> [GitHubRelease] { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + return try decoder.decode([GitHubRelease].self, from: data) + } +} + +/// A newer release the running app can install. +public struct UpdateOffer: Equatable, Sendable { + public var version: AppVersion + public var pageURL: URL + public var publishedAt: Date? + /// The DMG for this Mac's architecture. + public var installer: GitHubRelease.Asset + /// The release's `SHA256SUMS`, for when the DMG carries no digest. + public var checksums: GitHubRelease.Asset? + /// What changed: one entry per version newer than the running one, + /// newest first. + public var notes: [ReleaseNotes] +} + +public enum UpdateCatalog { + /// Matches `scripts/build-dmg.sh`. + public static func installerName(version: AppVersion, architecture: String) -> String { + "iTimer-\(version)-macos-\(architecture).dmg" + } + + /// The newest published release above `current` that has a DMG for + /// `architecture`, or nil when there is nothing to install. + public static func offer(in releases: [GitHubRelease], current: AppVersion, architecture: String) -> UpdateOffer? { + let newer = releases + .filter { !$0.draft && !$0.prerelease } + .compactMap { release in AppVersion(release.tagName).map { (version: $0, release: release) } } + .filter { $0.version > current } + .sorted { $0.version > $1.version } + for (version, release) in newer { + let name = installerName(version: version, architecture: architecture) + guard let installer = release.assets.first(where: { $0.name == name }) else { continue } + return UpdateOffer( + version: version, + pageURL: release.pageURL, + publishedAt: release.publishedAt, + installer: installer, + checksums: release.assets.first { $0.name == "SHA256SUMS" }, + notes: newer.filter { $0.version <= version }.map { + ReleaseNotes(version: $0.version, markdown: $0.release.body ?? "") + } + ) + } + return nil + } +} + +public enum Checksum { + /// The hex out of GitHub's `sha256:`. + public static func sha256(digest: String?) -> String? { + guard let digest, digest.lowercased().hasPrefix("sha256:") else { return nil } + return normalized(String(digest.dropFirst("sha256:".count))) + } + + /// The line for `name` in `sha256sum` output (` `, or + /// ` *` in binary mode). + public static func sha256(sums: String, name: String) -> String? { + for line in sums.split(whereSeparator: \.isNewline) { + let fields = line.split(maxSplits: 1, whereSeparator: \.isWhitespace) + guard fields.count == 2 else { continue } + var file = fields[1].trimmingCharacters(in: .whitespaces) + if file.hasPrefix("*") { file.removeFirst() } + if file == name { return normalized(String(fields[0])) } + } + return nil + } + + private static func normalized(_ hex: String) -> String? { + let hex = hex.lowercased() + return hex.count == 64 && hex.allSatisfy(\.isHexDigit) ? hex : nil + } +} + +/// A release's notes as the app shows them: headings, list items and +/// plain lines, without the download instructions every release ends with. +public struct ReleaseNotes: Equatable, Sendable { + public enum Block: Equatable, Sendable { + case heading(String) + case item(String) + case text(String) + } + + public var version: AppVersion + public var blocks: [Block] + + public init(version: AppVersion, markdown: String) { + self.version = version + self.blocks = Self.blocks(from: markdown) + } + + /// The heading `scripts/prepare-release.py` appends to every release. + /// It is about picking a DMG, which the updater does by itself. + static let installHeading = "下载与安装" + + public static func blocks(from markdown: String) -> [Block] { + var blocks: [Block] = [] + for raw in markdown.components(separatedBy: .newlines) { + let line = raw.trimmingCharacters(in: .whitespaces) + if line.isEmpty { continue } + if line.hasPrefix("#") { + let title = line.drop { $0 == "#" }.trimmingCharacters(in: .whitespaces) + if title == installHeading { break } + if !title.isEmpty { blocks.append(.heading(title)) } + } else if line.hasPrefix("- ") || line.hasPrefix("* ") { + blocks.append(.item(line.dropFirst(2).trimmingCharacters(in: .whitespaces))) + } else if raw.first?.isWhitespace == true, case .item(let previous)? = blocks.last { + // A list item wrapped onto an indented line. + blocks[blocks.count - 1] = .item(previous + " " + line) + } else { + blocks.append(.text(line)) + } + } + return blocks + } +} diff --git a/Sources/ITimerCore/UpdateInstaller.swift b/Sources/ITimerCore/UpdateInstaller.swift new file mode 100644 index 0000000..0b0404b --- /dev/null +++ b/Sources/ITimerCore/UpdateInstaller.swift @@ -0,0 +1,133 @@ +import CryptoKit +import Foundation + +public struct UpdateError: LocalizedError, Equatable, Sendable { + public var message: String + + public init(_ message: String) { + self.message = message + } + + public var errorDescription: String? { message } +} + +/// The file-system half of an update: check the downloaded DMG, copy the +/// app out of it, and swap it for the running bundle. Everything here +/// blocks; call it off the main thread. +public enum UpdateInstaller { + public static func sha256(of file: URL) throws -> String { + let handle = try FileHandle(forReadingFrom: file) + defer { try? handle.close() } + var hasher = SHA256() + while let chunk = try handle.read(upToCount: 1 << 20), !chunk.isEmpty { + hasher.update(data: chunk) + } + return hasher.finalize().map { String(format: "%02x", $0) }.joined() + } + + /// Why `app` can't be replaced where it is, or nil when it can. + public static func inPlaceProblem(for app: URL) -> String? { + guard app.pathExtension == "app" else { return "iTimer 不是从应用包运行的" } + // Gatekeeper runs a quarantined app that was never moved from a + // read-only copy; replacing that copy would not stick. + if app.path.contains("/AppTranslocation/") { return "iTimer 还没有拖进「应用程序」" } + let folder = app.deletingLastPathComponent() + guard FileManager.default.isWritableFile(atPath: folder.path) else { return "没有写入「\(folder.path)」的权限" } + // Moving a folder to another parent rewrites its `..`, so the + // bundle itself must be writable too (another user may own it). + guard FileManager.default.isWritableFile(atPath: app.path) else { return "没有修改「\(app.path)」的权限" } + return nil + } + + /// Mounts `dmg` (its SHA-256 already checked), checks the app inside is + /// `bundleID` at `version` with an intact signature, and copies it onto + /// `target`'s volume, so the swap is a rename. Returns the copy. + public static func stage(dmg: URL, version: AppVersion, bundleID: String, replacing target: URL) throws -> URL { + let mount = try attach(dmg) + defer { detach(mount) } + let source = mount.appendingPathComponent("iTimer.app", isDirectory: true) + let infoURL = source.appendingPathComponent("Contents/Info.plist") + guard let data = try? Data(contentsOf: infoURL), + let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else { + throw UpdateError("安装包里没有找到 iTimer。") + } + guard info["CFBundleIdentifier"] as? String == bundleID else { + throw UpdateError("安装包里的应用不是 iTimer。") + } + guard (info["CFBundleShortVersionString"] as? String).flatMap(AppVersion.init) == version else { + throw UpdateError("安装包里的版本不是 \(version)。") + } + let folder = try FileManager.default.url( + for: .itemReplacementDirectory, + in: .userDomainMask, + appropriateFor: target, + create: true + ) + let staged = folder.appendingPathComponent(target.lastPathComponent, isDirectory: true) + try FileManager.default.copyItem(at: source, to: staged) + do { + try run("/usr/bin/codesign", ["--verify", "--deep", "--strict", staged.path], failure: "安装包里的应用签名不完整。") + } catch { + try? FileManager.default.removeItem(at: folder) + throw error + } + return staged + } + + /// Puts `staged` where `target` is. The old copy is moved aside first + /// and put back if the new one can't take its place. + public static func swap(_ target: URL, with staged: URL) throws { + let files = FileManager.default + let folder = staged.deletingLastPathComponent() + let previous = folder.appendingPathComponent("previous-\(target.lastPathComponent)", isDirectory: true) + do { + try files.moveItem(at: target, to: previous) + } catch { + throw UpdateError("无法移走旧版本:\(error.localizedDescription)") + } + do { + try files.moveItem(at: staged, to: target) + } catch { + try? files.moveItem(at: previous, to: target) + throw UpdateError("无法放入新版本:\(error.localizedDescription)") + } + try? files.removeItem(at: folder) + } + + /// Mounted out of sight. `-noverify` skips the image's own checksums + /// (seconds): the caller has already checked the whole file's SHA-256. + private static func attach(_ dmg: URL) throws -> URL { + let output = try run( + "/usr/bin/hdiutil", + ["attach", dmg.path, "-nobrowse", "-readonly", "-noautoopen", "-noverify", "-mountrandom", NSTemporaryDirectory(), "-plist"], + failure: "无法打开安装包。" + ) + guard let plist = try? PropertyListSerialization.propertyList(from: output, format: nil) as? [String: Any], + let entities = plist["system-entities"] as? [[String: Any]], + let mount = entities.lazy.compactMap({ $0["mount-point"] as? String }).first else { + throw UpdateError("无法打开安装包。") + } + return URL(fileURLWithPath: mount, isDirectory: true) + } + + private static func detach(_ mount: URL) { + if (try? run("/usr/bin/hdiutil", ["detach", mount.path, "-quiet"], failure: "")) == nil { + _ = try? run("/usr/bin/hdiutil", ["detach", mount.path, "-force", "-quiet"], failure: "") + } + } + + @discardableResult + private static func run(_ tool: String, _ arguments: [String], failure: String) throws -> Data { + let process = Process() + process.executableURL = URL(fileURLWithPath: tool) + process.arguments = arguments + let output = Pipe() + process.standardOutput = output + process.standardError = FileHandle.nullDevice + try process.run() + let data = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { throw UpdateError(failure) } + return data + } +} diff --git a/Support/Info.plist b/Support/Info.plist index 355828f..443037b 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -19,9 +19,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.11.0 + 1.12.0 CFBundleVersion - 22 + 23 LSMinimumSystemVersion 14.0 LSUIElement diff --git a/Tests/ITimerCoreTests/UpdateTests.swift b/Tests/ITimerCoreTests/UpdateTests.swift new file mode 100644 index 0000000..99a93db --- /dev/null +++ b/Tests/ITimerCoreTests/UpdateTests.swift @@ -0,0 +1,241 @@ +import XCTest +@testable import ITimerCore + +final class UpdateTests: XCTestCase { + private var directory: URL! + + override func setUpWithError() throws { + directory = FileManager.default.temporaryDirectory.appendingPathComponent("itimer-update-tests-\(UUID())") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + + override func tearDownWithError() throws { + try FileManager.default.removeItem(at: directory) + } + + func testVersionsParseTagsAndCompareNumerically() throws { + XCTAssertEqual(AppVersion("v1.11.0"), AppVersion(1, 11, 0)) + XCTAssertEqual(AppVersion(" 1.2 "), AppVersion(1, 2, 0)) + XCTAssertEqual(AppVersion("2"), AppVersion(2, 0, 0)) + XCTAssertEqual(AppVersion(1, 10, 5).description, "1.10.5") + XCTAssertLessThan(try XCTUnwrap(AppVersion("1.9.9")), try XCTUnwrap(AppVersion("1.10.0"))) + XCTAssertLessThan(try XCTUnwrap(AppVersion("1.10.5")), try XCTUnwrap(AppVersion("v1.11.0"))) + for bad in ["", "v", "1..2", "1.2.3.4", "1.2.0-beta", "+1.0.0", "1.-2.0", "一.二.三"] { + XCTAssertNil(AppVersion(bad), bad) + } + } + + func testOfferIsNewestPublishedReleaseWithThisArchitecturesDMG() throws { + let releases = try GitHubRelease.list(from: Data(Self.releasesJSON.utf8)) + XCTAssertEqual(releases.count, 6) + + let arm = try XCTUnwrap(UpdateCatalog.offer(in: releases, current: AppVersion(1, 11, 0), architecture: "arm64")) + XCTAssertEqual(arm.version, AppVersion(1, 12, 1)) + XCTAssertEqual(arm.installer.name, "iTimer-1.12.1-macos-arm64.dmg") + XCTAssertEqual(arm.installer.size, 2_900_000) + XCTAssertEqual(arm.pageURL.absoluteString, "https://github.com/DueGin/iTimer/releases/tag/v1.12.1") + XCTAssertEqual(arm.publishedAt, Date(timeIntervalSince1970: 1_792_400_000)) + XCTAssertNil(arm.checksums) + // Drafts and prereleases are skipped; notes cover every newer version. + XCTAssertEqual(arm.notes.map(\.version), [AppVersion(1, 12, 1), AppVersion(1, 12, 0), AppVersion(1, 11, 1)]) + + // 1.12.1 has no Intel DMG yet: Intel Macs are offered 1.12.0. + let intel = try XCTUnwrap(UpdateCatalog.offer(in: releases, current: AppVersion(1, 11, 0), architecture: "x86_64")) + XCTAssertEqual(intel.version, AppVersion(1, 12, 0)) + XCTAssertEqual(intel.installer.digest, nil) + XCTAssertEqual(intel.checksums?.name, "SHA256SUMS") + XCTAssertEqual(intel.notes.map(\.version), [AppVersion(1, 12, 0), AppVersion(1, 11, 1)]) + + XCTAssertNil(UpdateCatalog.offer(in: releases, current: AppVersion(1, 12, 1), architecture: "arm64")) + XCTAssertNil(UpdateCatalog.offer(in: releases, current: AppVersion(1, 12, 0), architecture: "x86_64")) + XCTAssertNil(UpdateCatalog.offer(in: releases, current: AppVersion(2, 0, 0), architecture: "arm64")) + } + + func testChecksumsComeFromDigestOrSHA256SUMS() { + let hex = String(repeating: "ab", count: 32) + XCTAssertEqual(Checksum.sha256(digest: "sha256:\(hex)"), hex) + XCTAssertEqual(Checksum.sha256(digest: "SHA256:\(hex.uppercased())"), hex) + XCTAssertNil(Checksum.sha256(digest: nil)) + XCTAssertNil(Checksum.sha256(digest: "md5:\(hex)")) + XCTAssertNil(Checksum.sha256(digest: "sha256:abc")) + + let other = String(repeating: "0", count: 64) + let sums = """ + \(other) iTimer-1.12.0-macos-arm64.dmg + \(hex.uppercased()) *iTimer-1.12.0-macos-x86_64.dmg + + """ + XCTAssertEqual(Checksum.sha256(sums: sums, name: "iTimer-1.12.0-macos-arm64.dmg"), other) + XCTAssertEqual(Checksum.sha256(sums: sums, name: "iTimer-1.12.0-macos-x86_64.dmg"), hex) + XCTAssertNil(Checksum.sha256(sums: sums, name: "iTimer-1.12.0-macos.dmg")) + XCTAssertNil(Checksum.sha256(sums: "zz iTimer.dmg", name: "iTimer.dmg")) + } + + func testReleaseNotesDropTheDownloadSection() { + let body = """ + ### 新增 + + - 软件更新:在设置里检查新版本。 + - 带 `代码` 的一条, + 换行接着写。 + + 说明文字。 + + ### 下载与安装 + + | Mac 芯片 | 安装包 | + |---|---| + """ + XCTAssertEqual(ReleaseNotes.blocks(from: body), [ + .heading("新增"), + .item("软件更新:在设置里检查新版本。"), + .item("带 `代码` 的一条, 换行接着写。"), + .text("说明文字。"), + ]) + XCTAssertEqual(ReleaseNotes.blocks(from: ""), []) + } + + func testSHA256OfAFile() throws { + let file = directory.appendingPathComponent("hello.txt") + try Data("hello\n".utf8).write(to: file) + XCTAssertEqual(try UpdateInstaller.sha256(of: file), "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03") + } + + func testInPlaceProblems() throws { + let app = directory.appendingPathComponent("iTimer.app") + try FileManager.default.createDirectory(at: app, withIntermediateDirectories: true) + XCTAssertNil(UpdateInstaller.inPlaceProblem(for: app)) + try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: app.path) + XCTAssertNotNil(UpdateInstaller.inPlaceProblem(for: app)) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: app.path) + XCTAssertNotNil(UpdateInstaller.inPlaceProblem(for: directory.appendingPathComponent("iTimer"))) + XCTAssertNotNil(UpdateInstaller.inPlaceProblem(for: URL(fileURLWithPath: "/private/var/folders/x/AppTranslocation/ABC/d/iTimer.app"))) + + let locked = directory.appendingPathComponent("locked") + try FileManager.default.createDirectory(at: locked, withIntermediateDirectories: true) + try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: locked.path) + defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: locked.path) } + XCTAssertNotNil(UpdateInstaller.inPlaceProblem(for: locked.appendingPathComponent("iTimer.app"))) + } + + /// The whole file-system path against a real DMG: mount, check, copy + /// out, swap; the old bundle goes away and the new one stays signed. + func testStageFromDMGThenSwapReplacesTheBundle() throws { + let installed = try makeApp(version: "1.11.0", in: directory.appendingPathComponent("Applications")) + let release = try makeApp(version: "1.12.0", in: directory.appendingPathComponent("release")) + let dmg = directory.appendingPathComponent("iTimer-1.12.0-macos-arm64.dmg") + try shell("/usr/bin/hdiutil", "create", "-volname", "iTimer 1.12.0", "-srcfolder", release.deletingLastPathComponent().path, "-fs", "HFS+", "-format", "UDZO", "-ov", dmg.path) + + XCTAssertThrowsError(try UpdateInstaller.stage(dmg: dmg, version: AppVersion(1, 12, 1), bundleID: Self.bundleID, replacing: installed)) { + XCTAssertEqual($0 as? UpdateError, UpdateError("安装包里的版本不是 1.12.1。")) + } + XCTAssertThrowsError(try UpdateInstaller.stage(dmg: dmg, version: AppVersion(1, 12, 0), bundleID: "com.example.other", replacing: installed)) + + let staged = try UpdateInstaller.stage(dmg: dmg, version: AppVersion(1, 12, 0), bundleID: Self.bundleID, replacing: installed) + XCTAssertEqual(try version(of: staged), "1.12.0") + try UpdateInstaller.swap(installed, with: staged) + XCTAssertEqual(try version(of: installed), "1.12.0") + XCTAssertFalse(FileManager.default.fileExists(atPath: staged.deletingLastPathComponent().path)) + try shell("/usr/bin/codesign", "--verify", "--deep", "--strict", installed.path) + // Unmounted afterwards. + let mounts = try shell("/usr/bin/hdiutil", "info") + XCTAssertFalse(mounts.contains(dmg.path)) + } + + func testSwapPutsTheOldCopyBackWhenTheNewOneCannotMoveIn() throws { + let installed = try makeApp(version: "1.11.0", in: directory.appendingPathComponent("Applications")) + let missing = directory.appendingPathComponent("staging/iTimer.app") + try FileManager.default.createDirectory(at: missing.deletingLastPathComponent(), withIntermediateDirectories: true) + XCTAssertThrowsError(try UpdateInstaller.swap(installed, with: missing)) + XCTAssertEqual(try version(of: installed), "1.11.0") + } + + // MARK: fixtures + + private static let bundleID = "app.duegin.itimer.tests" + + /// A minimal ad-hoc signed app bundle. + private func makeApp(version: String, in folder: URL) throws -> URL { + let app = folder.appendingPathComponent("iTimer.app") + let macOS = app.appendingPathComponent("Contents/MacOS") + try FileManager.default.createDirectory(at: macOS, withIntermediateDirectories: true) + let info: [String: Any] = [ + "CFBundleIdentifier": Self.bundleID, + "CFBundleExecutable": "iTimer", + "CFBundlePackageType": "APPL", + "CFBundleShortVersionString": version, + ] + try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0) + .write(to: app.appendingPathComponent("Contents/Info.plist")) + let executable = macOS.appendingPathComponent("iTimer") + try Data("#!/bin/sh\n".utf8).write(to: executable) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) + try shell("/usr/bin/codesign", "--force", "--sign", "-", app.path) + return app + } + + private func version(of app: URL) throws -> String? { + let data = try Data(contentsOf: app.appendingPathComponent("Contents/Info.plist")) + let info = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] + return info?["CFBundleShortVersionString"] as? String + } + + @discardableResult + private func shell(_ tool: String, _ arguments: String...) throws -> String { + let process = Process() + process.executableURL = URL(fileURLWithPath: tool) + process.arguments = arguments + let output = Pipe() + process.standardOutput = output + process.standardError = FileHandle.nullDevice + try process.run() + let data = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + XCTAssertEqual(process.terminationStatus, 0, "\(tool) \(arguments)") + return String(decoding: data, as: UTF8.self) + } + + /// Trimmed to the fields the updater reads, newest first like the API. + private static let releasesJSON = """ + [ + { + "tag_name": "v1.14.0", "name": "iTimer 1.14.0", "body": "草稿", "draft": true, "prerelease": false, + "html_url": "https://github.com/DueGin/iTimer/releases/tag/v1.14.0", "published_at": null, + "assets": [{"name": "iTimer-1.14.0-macos-arm64.dmg", "size": 1, "browser_download_url": "https://example.com/a.dmg", "digest": null}] + }, + { + "tag_name": "v1.13.0-beta", "name": "iTimer 1.13.0 beta", "body": "预览", "draft": false, "prerelease": false, + "html_url": "https://github.com/DueGin/iTimer/releases/tag/v1.13.0-beta", "published_at": "2026-11-01T00:00:00Z", + "assets": [{"name": "iTimer-1.13.0-macos-arm64.dmg", "size": 1, "browser_download_url": "https://example.com/b.dmg", "digest": null}] + }, + { + "tag_name": "v1.12.1", "name": "iTimer 1.12.1", "body": "### 修复\\n\\n- 修了一个问题。", "draft": false, "prerelease": false, + "html_url": "https://github.com/DueGin/iTimer/releases/tag/v1.12.1", "published_at": "2026-10-19T08:53:20Z", + "assets": [ + {"name": "iTimer-1.12.1-macos-arm64.dmg", "size": 2900000, + "browser_download_url": "https://github.com/DueGin/iTimer/releases/download/v1.12.1/iTimer-1.12.1-macos-arm64.dmg", + "digest": "sha256:50a4e8ff76707e3de88cf61fd3a2f1859ea82af1a5a1cb4e3fc20cc039de7714"} + ] + }, + { + "tag_name": "v1.12.0", "name": "iTimer 1.12.0", "body": "### 新增\\n\\n- 软件更新。", "draft": false, "prerelease": false, + "html_url": "https://github.com/DueGin/iTimer/releases/tag/v1.12.0", "published_at": "2026-10-19T00:00:00Z", + "assets": [ + {"name": "iTimer-1.12.0-macos-arm64.dmg", "size": 2800000, "browser_download_url": "https://example.com/c.dmg"}, + {"name": "iTimer-1.12.0-macos-x86_64.dmg", "size": 3000000, "browser_download_url": "https://example.com/d.dmg"}, + {"name": "SHA256SUMS", "size": 193, "browser_download_url": "https://example.com/SHA256SUMS"} + ] + }, + { + "tag_name": "v1.11.1", "name": "iTimer 1.11.1", "body": null, "draft": false, "prerelease": false, + "html_url": "https://github.com/DueGin/iTimer/releases/tag/v1.11.1", "published_at": "2026-10-18T00:00:00Z", + "assets": [] + }, + { + "tag_name": "v1.11.0", "name": "iTimer 1.11.0", "body": "当前版本", "draft": false, "prerelease": false, + "html_url": "https://github.com/DueGin/iTimer/releases/tag/v1.11.0", "published_at": "2026-10-17T00:00:00Z", + "assets": [{"name": "iTimer-1.11.0-macos-arm64.dmg", "size": 1, "browser_download_url": "https://example.com/e.dmg"}] + } + ] + """ +} diff --git a/docs/FEATURES.md b/docs/FEATURES.md index cbba4a8..32ce8f3 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -1,6 +1,6 @@ # iTimer 功能清单 -当前版本 **1.11.0**(build 22)· 更新于 2026-10-19 +当前版本 **1.12.0**(build 23)· 更新于 2026-10-19 这份清单列出 iTimer 现在有的功能,一行一个,写明它做什么、从哪个版本开始有。改动功能的提交要同时更新这里,规则见 [AGENTS.md](../AGENTS.md)。每个版本具体改了什么见 [CHANGELOG](../CHANGELOG.md),面向用户的完整用法见 [README](../README.md)。 @@ -52,7 +52,7 @@ | 右侧抽屉 | 任务详情和新建日程在右侧抽屉里打开:主窗口里是列表右边的一栏,列表照常可用;面板里从右侧滑出盖住列表,点左侧露出的列表关闭;都可以点 × 或按 Esc 关闭 | 1.11.0 | | 任务详情 | 顶部是状态(未开始、计时中、已暂停、已完成及时长),下面依次是日程(名称、日期、时间、预计、提醒、标签,停下来自动保存)、子任务、备注和进展;子任务的详情可以点回父任务;已完成的任务只能改名称和标签 | 1.11.0 | | 今日完成 | 做完的事留在列表里,可以打开任务详情、修改计时时间或一键「再来一段」 | 1.3.2 | -| 底部按钮 | 打开 iTimer、设置、退出 | 1.0 | +| 底部按钮 | 打开 iTimer、设置、退出;有新版本时多一个「新版本 x.y.z」按钮,点了打开设置 | 1.0(新版本按钮 1.12.0 起) | ## 4. 日程与日程提醒 @@ -88,7 +88,7 @@ | 功能 | 说明 | 版本 | |---|---|---| -| 图标栏 | 最左边常驻:任务 ⌘1、目标 ⌘2、工作流 ⌘3、分析 ⌘4,底部是设置;任务有在计时亮小圆点,目标显示待确认的里程碑数,独立工作流有步骤在计时亮小圆点 | 1.7.0 | +| 图标栏 | 最左边常驻:任务 ⌘1、目标 ⌘2、工作流 ⌘3、分析 ⌘4,底部是设置;任务有在计时亮小圆点,目标显示待确认的里程碑数,独立工作流有步骤在计时亮小圆点,有新版本时设置亮小圆点 | 1.7.0(更新圆点 1.12.0 起) | | 列表栏 | 任务、目标、工作流三个模块在图标栏右边有一列列表,⌃⌘S 收起或展开,收起后只剩图标栏;分析模块没有列表 | 1.7.0 | | 目标列表搜索 | 在列表顶部按目标名或里程碑名搜索;目标名匹配时显示全部里程碑,里程碑名匹配时显示它和所属目标;搜索时临时展开,清除后恢复原来的折叠状态,右侧画布保留 | 1.10.0 | | 任务清单 | 全部、到点待开始(有任务到点时才出现)、进行中、已暂停、接下来、时间待定、今日完成,下面按标签列出,每项带任务数;点一项,右边只显示这一类 | 1.7.0 | @@ -169,7 +169,7 @@ | 功能 | 说明 | 版本 | |---|---|---| -| 设置窗口(⌘,) | 脑裂线、提醒开关、日历同步、登录时启动、在 Finder 中显示数据文件 | 1.3.2 | +| 设置窗口(⌘,) | 脑裂线、提醒开关、日历同步、登录时启动、在 Finder 中显示数据文件、软件更新 | 1.3.2(软件更新 1.12.0 起) | | 日历同步 | 单向写入名为「iTimer」的系统日历,暂停、完成、改名、修改计时时间都会同步;每段实际计时一个事件,暂停的时间留空,间隔不到 1 分钟的暂停并入前一段;没开始的日程按计划时间占位,时间待定的不写;没有权限时给出去系统设置的链接 | 1.0(1.5.0 起按计时段拆分) | | 登录时启动 | 系统登录项,可在设置里开关 | 1.3.2 | @@ -179,7 +179,7 @@ | 功能 | 说明 | 版本 | |---|---|---| -| 本地存储 | 所有数据存在 `~/Library/Application Support/iTimer/state.json`,只在本机,不联网 | 1.0 | +| 本地存储 | 所有数据存在 `~/Library/Application Support/iTimer/state.json`,只在本机,不上传;联网只为检查更新,只读取 GitHub 上的版本信息 | 1.0 | | 旧数据兼容 | 当前数据版本是 3,旧版本的文件照常打开:旧的单个日历事件 ID 自动迁移,已移除的分类和任务集合加载时忽略,加载时剪掉不存在的工作流,一个工作流只留在一个目标里 | 1.0(数据版本 3 是 1.7.0 起) | ## 13. 下载与安装 @@ -191,6 +191,18 @@ | 分架构安装包 | GitHub Release 提供 Apple Silicon(arm64)和 Intel(x86_64)两个 DMG,打开后将 iTimer 拖入 Applications;要求 macOS 14 或更新版本 | 1.8.0 | | 下载校验 | 每个 Release 附带 SHA256SUMS,可核对两个安装包的 SHA-256 校验值 | 1.8.0 | +## 14. 软件更新 + +代码:`Sources/ITimer/Updater.swift`、`UpdateSection.swift`、`Sources/ITimerCore/Update.swift`、`UpdateInstaller.swift` + +| 功能 | 说明 | 版本 | +|---|---|---| +| 检查更新 | 读取 GitHub Releases 上已发布的版本(跳过草稿和预发布),比当前版本新、而且有这台 Mac 芯片对应安装包的才算新版本;启动时和之后每 24 小时自动检查一次,可在设置里关掉,自动检查失败不提示;也可以在菜单栏「iTimer › 检查更新…」或「设置 › 软件更新」手动检查 | 1.12.0 | +| 新版本提示 | 菜单栏面板底部出现「新版本 x.y.z」按钮,主窗口图标栏的设置图标亮小圆点,点了打开设置 | 1.12.0 | +| 更新内容 | 设置里显示新版本的发布日期、安装包大小和更新内容,落后几个版本时按版本从新到旧一起列出,不显示 Release 末尾的「下载与安装」说明;「发布页」打开 GitHub 上这个版本的页面 | 1.12.0 | +| 下载并安装 | 下载这台 Mac 芯片对应的 DMG(在 Apple 芯片上运行的 Intel 版换成 Apple Silicon 版),下载中可以取消;按 Release 附件的 SHA-256 校验,校验不过就删掉不装;确认安装包里是 iTimer、版本一致、签名完整后替换当前应用并自动重新打开,正在计时的任务照常计时 | 1.12.0 | +| 手动安装兜底 | 当前位置没有写入权限、iTimer 还没拖进「应用程序」或替换失败时,打开下载好的安装包,拖到「应用程序」即可 | 1.12.0 | + ## 已移除 | 功能 | 加入 | 移除 | 说明 | diff --git a/scripts/prepare-release.py b/scripts/prepare-release.py index 35bd640..e6d4d9b 100644 --- a/scripts/prepare-release.py +++ b/scripts/prepare-release.py @@ -32,6 +32,7 @@ def main(): if section is None or not section.group(1).strip(): parser.error(f"CHANGELOG.md 缺少 {version} 的更新内容,请先整理该版本的更新日志") + # 应用内更新显示更新内容时,从「### 下载与安装」起整段不显示(ReleaseNotes),改这个标题要同步。 notes = f"""{section.group(1).strip()} ### 下载与安装