From 42aee562f1fd7cfb247f500f491245fb3023abc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hannah=20Pascal-No=C3=ABl?= Date: Tue, 27 Oct 2026 21:52:27 +0000 Subject: [PATCH] Add version badges to installed Xcode icons Adds `xcodes icon [version] [--remove]` and `xcodes install --badge-icon`, which draw the version onto a custom Finder icon so several Xcodes can be told apart in the Dock. --- README.md | 14 + Sources/XcodesKit/Environment.swift | 33 ++- Sources/XcodesKit/IconBadge.swift | 298 ++++++++++++++++++++ Sources/XcodesKit/Version+Xcode.swift | 17 ++ Sources/XcodesKit/XcodeInstaller.swift | 66 ++++- Sources/xcodes/App.swift | 55 +++- Tests/XcodesKitTests/Environment+Mock.swift | 12 +- Tests/XcodesKitTests/IconBadgeTests.swift | 143 ++++++++++ 8 files changed, 633 insertions(+), 5 deletions(-) create mode 100644 Sources/XcodesKit/IconBadge.swift create mode 100644 Tests/XcodesKitTests/IconBadgeTests.swift diff --git a/README.md b/README.md index eb63e82c..a1a41dac 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,7 @@ Read [the proposal](/XCODE_VERSION.md) of `.xcode-version`. - `download `: Download a specific version of Xcode - `install `: Download and install a specific version of Xcode - `installed`: List the versions of Xcode that are installed +- `icon`: Draw the version onto the icon of installed Xcodes, like "27.2" (see below) - `list`: List all versions of Xcode that are available to install - `select`: Change the selected Xcode - `uninstall`: Uninstall a specific version of Xcode @@ -149,6 +150,19 @@ Read [the proposal](/XCODE_VERSION.md) of `.xcode-version`. - `version`: Print the version number of xcodes itself - `signout`: Clears the stored username and password +### Version badges on Xcode icons + +To tell several installed Xcodes apart in the Dock, `xcodes icon` draws each Xcode's version onto its icon. The pill is green for releases and purple for prereleases, which also get a suffix such as "27.2b2" (beta 2) or "27.2rc" (release candidate): + +```sh +xcodes icon # every Xcode in /Applications +xcodes icon 27.2 # just one +xcodes icon --remove # restore the original icons +xcodes install --latest --badge-icon +``` + +The badge is a custom Finder icon stored beside the app's `Contents` folder, so Xcode's code signature isn't modified and `spctl`/`codesign --verify` still pass. `codesign --verify --strict` does report the Finder info it adds, so use `xcodes icon --remove` if you run strict checks. Dock tiles of already-running Xcodes update the next time they launch; run `killall Dock` if a pinned tile looks stale. + ### Experimental Unxip - for faster unxipping Thanks to the amazing work by [saagarjhi](https://github.com/saagarjha/unxip) - Xcodes now includes the ability to unxip up to 70% faster on some systems. diff --git a/Sources/XcodesKit/Environment.swift b/Sources/XcodesKit/Environment.swift index 3b5a637b..f2d3371b 100644 --- a/Sources/XcodesKit/Environment.swift +++ b/Sources/XcodesKit/Environment.swift @@ -18,6 +18,7 @@ public struct Environment: Sendable { public var network = Network() public var logging = Logging() public var keychain = Keychain() + public var icons = Icons() public init() { self.shell = Shell() @@ -25,14 +26,16 @@ public struct Environment: Sendable { self.network = Network() self.logging = Logging() self.keychain = Keychain() + self.icons = Icons() } - public init(shell: Shell, files: Files, network: Network, logging: Logging, keychain: Keychain) { + public init(shell: Shell, files: Files, network: Network, logging: Logging, keychain: Keychain, icons: Icons) { self.shell = shell self.files = files self.network = network self.logging = logging self.keychain = keychain + self.icons = icons } } @@ -407,3 +410,31 @@ public struct Keychain: Sendable { try remove(key) } } + +public struct Icons: Sendable { + public var applyBadge: @Sendable (IconBadge, Path) throws -> Void = { badge, path in + #if canImport(AppKit) + try badge.setCustomIcon(of: path) + #else + throw IconBadgeUnsupportedError() + #endif + } + public func applyBadge(_ badge: IconBadge, to path: Path) throws { + try applyBadge(badge, path) + } + + public var removeBadge: @Sendable (Path) throws -> Void = { path in + #if canImport(AppKit) + try IconBadge.removeCustomIcon(of: path) + #else + throw IconBadgeUnsupportedError() + #endif + } + public func removeBadge(from path: Path) throws { + try removeBadge(path) + } +} + +struct IconBadgeUnsupportedError: LocalizedError { + var errorDescription: String? { "Changing icons is only supported on macOS." } +} diff --git a/Sources/XcodesKit/IconBadge.swift b/Sources/XcodesKit/IconBadge.swift new file mode 100644 index 00000000..ea78a9de --- /dev/null +++ b/Sources/XcodesKit/IconBadge.swift @@ -0,0 +1,298 @@ +import Foundation +@preconcurrency import Version + +/// A badge showing an Xcode's version, drawn over the Xcode's own icon. +public struct IconBadge: Equatable, Sendable { + /// The main text in the badge: the version number. + let label: String + /// The secondary text in the badge: the prerelease label, if any. + let suffix: String + /// Whether the badge is drawn in the prerelease color instead of the release color. + let isPrerelease: Bool + + /// The badge's whole text: the label followed by the suffix. + var text: String { + label + suffix + } + + public init(version: Version) { + var label = "\(version.major).\(version.minor)" + if version.patch != 0 { + label += ".\(version.patch)" + } + self.label = label + self.suffix = version.compactPrereleaseIdentifier + self.isPrerelease = !version.prereleaseIdentifiers.isEmpty + } +} + +#if canImport(AppKit) +import AppKit +@preconcurrency import Path + +public enum IconBadgeError: LocalizedError, Equatable { + case notWritable(Path) + case failedToSetIcon(Path) + case failedToRenderIcon + + public var errorDescription: String? { + switch self { + case .notWritable(let path): + return """ + \(path.string) can't be modified, so its icon can't be changed. + If it's owned by you, your terminal may need "App Management" access: System Settings > Privacy & Security > App Management. + """ + case .failedToSetIcon(let path): + return """ + Failed to set a custom icon on \(path.string). + If it's owned by you, your terminal may need "App Management" access: System Settings > Privacy & Security > App Management. + """ + case .failedToRenderIcon: + return "Failed to draw the badge onto the icon, so the icon was left as it was." + } + } +} + +/// Applying a badge as a custom Finder icon. +/// +/// A custom icon is stored next to the bundle's `Contents` directory (an `Icon\r` file plus a Finder info flag), so +/// Xcode's sealed code signature isn't touched and `codesign --verify` / `spctl --assess` keep passing. Only +/// `codesign --verify --strict` objects to the Finder info. +extension IconBadge { + /// The icon art is shrunk a little so the pill doesn't cover too much of the hammer. + static let artScale: CGFloat = 0.9 + /// The gap between the top of the icon art and the top of the icon, relative to the icon's size. + static let artTopInset: CGFloat = 0.02 + /// The widest the pill may get, relative to the icon's size. + static let maxPillWidth: CGFloat = 0.92 + /// The gap between the bottom of the pill and the bottom of the icon, relative to the icon's size. + static let pillBottomInset: CGFloat = 0.035 + /// The diameter of the pill when it has no text, relative to the icon's size. + static let emptyPillDiameter: CGFloat = 0.2 + /// The pill's drop shadow, relative to the icon's size. + static let shadowOffset: CGFloat = 0.005 + static let shadowBlur: CGFloat = 0.02 + static let shadowAlpha: CGFloat = 0.4 + /// The faint highlight along the pill's edge: its width and inset relative to the icon's size, and its opacity. + static let highlightWidth: CGFloat = 0.004 + static let highlightAlpha: CGFloat = 0.25 + /// Below this pixel size the label can't be read, so only the colored pill is drawn. + static let minimumTextSize: CGFloat = 48 + /// The label's font size relative to the icon's size. + static let labelFontScale: CGFloat = 0.22 + /// How much a label that doesn't fit is shrunk by on each attempt. + static let labelShrinkFactor: CGFloat = 0.96 + /// The padding around the label's glyphs on every side, relative to the version's cap height. + static let paddingScale: CGFloat = 0.6 + /// The prerelease suffix's font size relative to the version's. + static let suffixFontScale: CGFloat = 0.78 + /// Smallest label font, in pixels, that is still worth drawing; smaller labels fall back to a bare pill. + static let minimumFontSize: CGFloat = 7 + /// Icon bitmaps as (point size, pixel size) pairs: each point size at 1x and 2x, as in an .icns. + static let representations: [(points: Int, pixels: Int)] = [ + (16, 16), (16, 32), + (32, 32), (32, 64), + (128, 128), (128, 256), + (256, 256), (256, 512), + (512, 512), (512, 1024), + ] + + private var fillColor: NSColor { + isPrerelease + ? NSColor(srgbRed: 0.72, green: 0.36, blue: 0.98, alpha: 1) + : NSColor(srgbRed: 0.08, green: 0.61, blue: 0.27, alpha: 1) + } + + /// Draws the badge over the stock icon of the app at `path`, and sets the result as its custom icon. + public func setCustomIcon(of path: Path) throws { + try Self.requireWritable(path) + let base = try Self.stockIcon(of: path) + // Drawn before anything is changed, so a failure can't leave the app with a worse icon than it started with. + let image = try makeImage(base: base) + try Self.setIcon(image, of: path) + } + + /// Restores the stock icon of the app at `path`. + public static func removeCustomIcon(of path: Path) throws { + try requireWritable(path) + try setIcon(nil, of: path) + } + + /// An icon with a bitmap at every standard size, each drawn natively so the text stays crisp. + func makeImage(base: NSImage) throws -> NSImage { + let image = NSImage(size: NSSize(width: 512, height: 512)) + for (points, pixels) in Self.representations { + image.addRepresentation(try makeRepresentation(base: base, pixels: pixels, points: points)) + } + return image + } + + func makeRepresentation(base: NSImage, pixels: Int, points: Int? = nil) throws -> NSBitmapImageRep { + let size = CGFloat(pixels) + guard let representation = NSBitmapImageRep( + bitmapDataPlanes: nil, + pixelsWide: pixels, + pixelsHigh: pixels, + bitsPerSample: 8, + samplesPerPixel: 4, + hasAlpha: true, + isPlanar: false, + colorSpaceName: .deviceRGB, + bytesPerRow: 0, + bitsPerPixel: 0 + ), let graphicsContext = NSGraphicsContext(bitmapImageRep: representation) else { + throw IconBadgeError.failedToRenderIcon + } + NSGraphicsContext.saveGraphicsState() + defer { NSGraphicsContext.restoreGraphicsState() } + NSGraphicsContext.current = graphicsContext + graphicsContext.imageInterpolation = .high + + // The original icon, centered horizontally and nudged up, leaving room for the pill underneath. + let artSize = size * Self.artScale + let artRect = NSRect(x: (size - artSize) / 2, y: size - artSize - size * Self.artTopInset, width: artSize, height: artSize) + base.draw(in: artRect, from: .zero, operation: .sourceOver, fraction: 1) + + drawPill(in: graphicsContext.cgContext, size: size) + + // The point size is applied after drawing: it changes the context's scale, and everything above is in pixels. + let pointSize = CGFloat(points ?? pixels) + representation.size = NSSize(width: pointSize, height: pointSize) + return representation + } + + private static func stockIcon(of path: Path) throws -> NSImage { + // The asset catalog holds the full resolution icon. Asking Launch Services right after clearing a custom + // icon can instead return a placeholder at the larger sizes, so that is only the fallback. + if let bundle = Bundle(path: path.string), + let iconName = bundle.object(forInfoDictionaryKey: "CFBundleIconName") as? String, + let image = bundle.image(forResource: NSImage.Name(iconName)) { + return image + } + if hasCustomIcon(path) { + try setIcon(nil, of: path) + } + return NSWorkspace.shared.icon(forFile: path.string) + } + + private static func setIcon(_ image: NSImage?, of path: Path) throws { + let didSetIcon = NSWorkspace.shared.setIcon(image, forFile: path.string, options: []) + guard didSetIcon else { + throw IconBadgeError.failedToSetIcon(path) + } + } + + private static func hasCustomIcon(_ path: Path) -> Bool { + var value: AnyObject? + try? (path.url as NSURL).getResourceValue(&value, forKey: URLResourceKey("NSURLHasCustomIconKey")) + return (value as? NSNumber)?.boolValue ?? true + } + + private static func requireWritable(_ path: Path) throws { + guard FileManager.default.isWritableFile(atPath: path.string) else { + throw IconBadgeError.notWritable(path) + } + } + + private func drawPill(in context: CGContext, size: CGFloat) { + var showsText = size >= Self.minimumTextSize + + let maxWidth = size * Self.maxPillWidth + var fontSize = size * Self.labelFontScale + var attributedText = attributedLabel(fontSize: fontSize) + var inkWidth = Self.inkBounds(of: attributedText).width + // Shrink long labels until they fit. + while showsText, inkWidth + 2 * Self.padding(for: fontSize) > maxWidth { + fontSize *= Self.labelShrinkFactor + if fontSize < Self.minimumFontSize { + showsText = false + break + } + attributedText = attributedLabel(fontSize: fontSize) + inkWidth = Self.inkBounds(of: attributedText).width + } + + let pillWidth: CGFloat + let pillHeight: CGFloat + if showsText { + // The same padding all around the text: digits are cap-height tall and have no descenders, so the pill is + // sized from the cap height and the glyphs' ink, not from the line box and advance widths, which add extra space. + pillWidth = inkWidth + 2 * Self.padding(for: fontSize) + pillHeight = Self.labelFont(size: fontSize).capHeight + 2 * Self.padding(for: fontSize) + } else { + pillWidth = size * Self.emptyPillDiameter + pillHeight = pillWidth + } + let pillRect = CGRect(x: (size - pillWidth) / 2, y: size * Self.pillBottomInset, width: pillWidth, height: pillHeight) + let radius = pillHeight / 2 + + // The pill and its drop shadow. + context.saveGState() + context.setShadow( + offset: CGSize(width: 0, height: -size * Self.shadowOffset), + blur: size * Self.shadowBlur, + color: NSColor.black.withAlphaComponent(Self.shadowAlpha).cgColor + ) + context.setFillColor(fillColor.cgColor) + context.addPath(CGPath(roundedRect: pillRect, cornerWidth: radius, cornerHeight: radius, transform: nil)) + context.fillPath() + context.restoreGState() + + // A faint inner highlight keeps the pill's edge defined against bright icon art. + context.saveGState() + context.setStrokeColor(NSColor.white.withAlphaComponent(Self.highlightAlpha).cgColor) + context.setLineWidth(max(1, size * Self.highlightWidth)) + let inset = size * Self.highlightWidth + context.addPath(CGPath(roundedRect: pillRect.insetBy(dx: inset, dy: inset), cornerWidth: radius, cornerHeight: radius, transform: nil)) + context.strokePath() + context.restoreGState() + + if showsText { + let font = Self.labelFont(size: fontSize) + let baseline = pillRect.midY - font.capHeight / 2 + let ink = Self.inkBounds(of: attributedText) + attributedText.draw(at: CGPoint(x: pillRect.midX - ink.midX, y: baseline + font.descender)) + } + } + + /// The badge's label in a heavy weight, followed by its suffix smaller and lighter. + private func attributedLabel(fontSize: CGFloat) -> NSAttributedString { + let result = NSMutableAttributedString( + string: label, + attributes: [.font: Self.labelFont(size: fontSize), .foregroundColor: NSColor.white] + ) + if !suffix.isEmpty { + result.append(NSAttributedString( + string: suffix, + attributes: [ + .font: Self.roundedFont(size: fontSize * Self.suffixFontScale, weight: .medium), + .foregroundColor: NSColor.white, + .kern: 0, + ] + )) + } + return result + } + + private static func padding(for fontSize: CGFloat) -> CGFloat { + labelFont(size: fontSize).capHeight * paddingScale + } + + /// The bounds of the glyphs actually drawn, relative to the text's origin. + private static func inkBounds(of text: NSAttributedString) -> CGRect { + CTLineGetBoundsWithOptions(CTLineCreateWithAttributedString(text), .useGlyphPathBounds) + } + + private static func labelFont(size: CGFloat) -> NSFont { + roundedFont(size: size, weight: .heavy) + } + + private static func roundedFont(size: CGFloat, weight: NSFont.Weight) -> NSFont { + let base = NSFont.systemFont(ofSize: size, weight: weight) + guard let descriptor = base.fontDescriptor.withDesign(.rounded), let rounded = NSFont(descriptor: descriptor, size: size) else { + return base + } + return rounded + } +} +#endif diff --git a/Sources/XcodesKit/Version+Xcode.swift b/Sources/XcodesKit/Version+Xcode.swift index 41804b69..20c1639f 100644 --- a/Sources/XcodesKit/Version+Xcode.swift +++ b/Sources/XcodesKit/Version+Xcode.swift @@ -11,4 +11,21 @@ public extension Version { ) .version(inDirectory: inDirectory) } + + /// The prerelease identifiers on one line, with the well-known names abbreviated: "Release Candidate 2" becomes "rc2". + internal var compactPrereleaseIdentifier: String { + var suffix = prereleaseIdentifiers.joined(separator: " ") + for (name, abbreviation) in Self.prereleaseAbbreviations { + suffix = suffix.replacingOccurrences(of: name, with: abbreviation, options: [.caseInsensitive]) + } + return suffix.filter { !$0.isWhitespace } + } + + private static let prereleaseAbbreviations = [ + ("developer preview", "dp"), + ("release candidate", "rc"), + ("gold master", "gm"), + ("beta", "b"), + ("seed", "s"), + ] } diff --git a/Sources/XcodesKit/XcodeInstaller.swift b/Sources/XcodesKit/XcodeInstaller.swift index f829d219..38f9c4a5 100644 --- a/Sources/XcodesKit/XcodeInstaller.swift +++ b/Sources/XcodesKit/XcodeInstaller.swift @@ -26,6 +26,7 @@ public final class XcodeInstaller: Sendable { case versionAlreadyInstalled(InstalledXcode) case invalidVersion(String) case versionNotInstalled(Version) + case failedToUpdateIcons(count: Int) case unauthorized public var errorDescription: String? { @@ -73,6 +74,8 @@ public final class XcodeInstaller: Sendable { return "\(version) is not a valid version number." case let .versionNotInstalled(version): return "\(version.appleDescription) is not installed." + case let .failedToUpdateIcons(count): + return "Failed to update the icon of \(count) Xcode\(count == 1 ? "" : "s")." case .unauthorized: return """ Received 403: Unauthorized. This can happen when either: @@ -182,7 +185,7 @@ public final class XcodeInstaller: Sendable { } } - public func install(_ installationType: InstallationType, dataSource: DataSource, downloader: Downloader, destination: Path, experimentalUnxip: Bool = false, emptyTrash: Bool, noSuperuser: Bool) async throws -> InstalledXcode { + public func install(_ installationType: InstallationType, dataSource: DataSource, downloader: Downloader, destination: Path, experimentalUnxip: Bool = false, emptyTrash: Bool, noSuperuser: Bool, badgeIcon: Bool = false) async throws -> InstalledXcode { let xcode = try await xcodeInstallRetryService.install( shouldRetryAfterDamagedArchive: installationType.shouldRetryAfterDamagedArchive, attempt: { _ in @@ -194,10 +197,71 @@ public final class XcodeInstaller: Sendable { Current.logging.log("Removing damaged XIP and re-attempting installation.\n") } ) + if badgeIcon { + // Cosmetic, so a failure here must never fail an otherwise successful installation. + do { + try applyBadge(to: xcode) + } catch { + Current.logging.log("Couldn't add the version to the icon: \(error.legibleLocalizedDescription)".yellow) + } + } Current.logging.log("\nXcode \(xcode.version.descriptionWithoutBuildMetadata) has been installed to \(xcode.path.string)".green) return xcode } + /// Draws each matching Xcode's version onto its icon. A `nil` `versionString` matches every Xcode in `directory`. + public func addIconBadges(ofVersion versionString: String?, directory: Path) throws { + try updateIcons(ofVersion: versionString, directory: directory) { xcode in + let badge = try applyBadge(to: xcode) + return "Added \"\(badge.text)\" to the icon of \(xcode.path.string)" + } + } + + /// Restores the stock icon of each matching Xcode. A `nil` `versionString` matches every Xcode in `directory`. + public func removeIconBadges(ofVersion versionString: String?, directory: Path) throws { + try updateIcons(ofVersion: versionString, directory: directory) { xcode in + try Current.icons.removeBadge(from: xcode.path) + return "Removed the custom icon from \(xcode.path.string)" + } + } + + /// Runs `update` on each matching Xcode, logging what it returns. Every Xcode is tried even if one fails. + private func updateIcons(ofVersion versionString: String?, directory: Path, _ update: (InstalledXcode) throws -> String) throws { + var failures = 0 + for xcode in try installedXcodes(matching: versionString, in: directory) { + do { + Current.logging.log(try update(xcode)) + } catch { + failures += 1 + Current.logging.log("\(xcode.path.string): \(error.legibleLocalizedDescription)".red) + } + } + if failures > 0 { + throw Error.failedToUpdateIcons(count: failures) + } + } + + private func installedXcodes(matching versionString: String?, in directory: Path) throws -> [InstalledXcode] { + let installedXcodes = Current.files.installedXcodes(directory) + guard let versionString else { + return installedXcodes.sorted { $0.version < $1.version } + } + guard let version = Version(xcodeVersion: versionString) else { + throw Error.invalidVersion(versionString) + } + guard let installedXcode = installedXcodes.first(withVersion: version) else { + throw Error.versionNotInstalled(version) + } + return [installedXcode] + } + + @discardableResult + private func applyBadge(to xcode: InstalledXcode) throws -> IconBadge { + let badge = IconBadge(version: xcode.version) + try Current.icons.applyBadge(badge, to: xcode.path) + return badge + } + private var xcodeInstallRetryService: XcodeInstallRetryService { XcodeInstallRetryService( damagedArchiveURL: { error in diff --git a/Sources/xcodes/App.swift b/Sources/xcodes/App.swift index 36ee7e5e..5156ba63 100644 --- a/Sources/xcodes/App.swift +++ b/Sources/xcodes/App.swift @@ -66,7 +66,7 @@ struct Xcodes: AsyncParsableCommand { static let configuration = CommandConfiguration( abstract: "Manage the Xcodes installed on your Mac", shouldDisplay: true, - subcommands: [Download.self, Install.self, Installed.self, List.self, Runtimes.self, Select.self, Uninstall.self, Update.self, Version.self, Signout.self] + subcommands: [Download.self, Icon.self, Install.self, Installed.self, List.self, Runtimes.self, Select.self, Uninstall.self, Update.self, Version.self, Signout.self] ) private struct Services { @@ -193,6 +193,54 @@ struct Xcodes: AsyncParsableCommand { } } + struct Icon: AsyncParsableCommand { + static let configuration = CommandConfiguration( + abstract: "Draw the version onto the icon of installed Xcodes", + discussion: """ + Gives each Xcode a custom icon badged with its version and channel (green for release, purple for prerelease), so several Xcodes are easy to tell apart in the Dock and Finder. Run without a version to update every Xcode in the directory. + + The custom icon is stored beside the app's Contents folder, so Xcode's code signature stays valid. The only tool that notices is `codesign --verify --strict`. Use --remove to restore the original icon. + + EXAMPLES: + xcodes icon # sets icons for all installed Xcodes + xcodes icon 27.2 + xcodes icon --remove + """ + ) + + @Argument(help: "The version to update. Defaults to all installed versions.", + completion: .custom { _ in Current.files.installedXcodes(getDirectory(possibleDirectory: nil)).sorted { $0.version < $1.version }.map { $0.version.appleDescription } }) + var version: [String] = [] + + @Flag(help: "Restore the original icon.") + var remove: Bool = false + + @OptionGroup + var globalDirectory: GlobalDirectoryOption + + @OptionGroup + var globalColor: GlobalColorOption + + func run() async throws { + configureRainbow(enabled: globalColor.color) + + let directory = getDirectory(possibleDirectory: globalDirectory.directory) + let services = Xcodes.makeServices() + + do { + let versionString = version.isEmpty ? nil : version.joined(separator: " ") + if remove { + try services.xcodeInstaller.removeIconBadges(ofVersion: versionString, directory: directory) + } else { + try services.xcodeInstaller.addIconBadges(ofVersion: versionString, directory: directory) + } + Icon.exit() + } catch { + Icon.exit(withLegibleError: error) + } + } + } + struct Install: AsyncParsableCommand { static let configuration = CommandConfiguration( abstract: "Download and install a specific version of Xcode", @@ -249,6 +297,9 @@ struct Xcodes: AsyncParsableCommand { @Flag(help: "Completely delete Xcode .xip after installation, instead of keeping it on the user's Trash.") var emptyTrash: Bool = false + @Flag(help: "Draw the version onto the installed Xcode's icon, to tell Xcodes apart in the Dock. See `xcodes icon`.") + var badgeIcon: Bool = false + @Option(help: "The directory to install Xcode into. Defaults to /Applications.", completion: .directory) var directory: String? @@ -310,7 +361,7 @@ struct Xcodes: AsyncParsableCommand { _ = try await services.xcodeList.updateAvailableXcodes(dataSource: globalDataSource.dataSource) } - let xcode = try await services.xcodeInstaller.install(installation, dataSource: globalDataSource.dataSource, downloader: downloader, destination: destination, experimentalUnxip: experimentalUnxip, emptyTrash: emptyTrash, noSuperuser: noSuperuser) + let xcode = try await services.xcodeInstaller.install(installation, dataSource: globalDataSource.dataSource, downloader: downloader, destination: destination, experimentalUnxip: experimentalUnxip, emptyTrash: emptyTrash, noSuperuser: noSuperuser, badgeIcon: badgeIcon) if select { try await selectXcodeAsync(shouldPrint: print, pathOrVersion: xcode.path.string, directory: destination, fallbackToInteractive: false) } diff --git a/Tests/XcodesKitTests/Environment+Mock.swift b/Tests/XcodesKitTests/Environment+Mock.swift index 5d38145a..7e3c7869 100644 --- a/Tests/XcodesKitTests/Environment+Mock.swift +++ b/Tests/XcodesKitTests/Environment+Mock.swift @@ -15,7 +15,8 @@ extension Environment { files: .mock, network: .mock, logging: .mock, - keychain: .mock + keychain: .mock, + icons: .mock ) } } @@ -132,3 +133,12 @@ extension Keychain { ) } } + +extension Icons { + static var mock: Icons { + Icons( + applyBadge: { _, _ in }, + removeBadge: { _ in } + ) + } +} diff --git a/Tests/XcodesKitTests/IconBadgeTests.swift b/Tests/XcodesKitTests/IconBadgeTests.swift new file mode 100644 index 00000000..61342e22 --- /dev/null +++ b/Tests/XcodesKitTests/IconBadgeTests.swift @@ -0,0 +1,143 @@ +import Path +import Version +import XCTest +import XcodesKit +@testable import XcodesCLIKit + +#if canImport(AppKit) +import AppKit +#endif + +final class IconBadgeTests: XCTestCase { + private func badge(_ version: Version) -> IconBadge { IconBadge(version: version) } + + private let beta2 = Version(27, 0, 0, prereleaseIdentifiers: ["Beta", "2"]) + + func test_release() { + XCTAssertEqual(badge(Version("27.0.0+25A100")!).label, "27.0") + XCTAssertEqual(badge(Version("26.0.1")!).label, "26.0.1") + XCTAssertEqual(badge(Version("26.0.1")!).suffix, "") + XCTAssertFalse(badge(Version("26.0.1")!).isPrerelease) + } + + func test_prerelease() { + XCTAssertEqual(badge(beta2).label, "27.0") + XCTAssertEqual(badge(beta2).suffix, "b2") + XCTAssertTrue(badge(beta2).isPrerelease) + } + + func test_prereleaseSuffix_abbreviatesKnownNames() { + let expected: [(Version, String)] = [ + (Version("26.4.0-Beta")!, "b"), + (Version("26.4.0-Beta.2")!, "b2"), + (Version(xcodeVersion: "26.4 Beta 3")!, "b3"), + (Version(26, 4, 0, prereleaseIdentifiers: ["beta"]), "b"), + (Version("27.2.0-Release.Candidate")!, "rc"), + (Version("27.2.0-Release.Candidate.2")!, "rc2"), + (Version(xcodeVersion: "27.1 Release Candidate")!, "rc"), + (Version("27.0.0-Gold.Master")!, "gm"), + (Version("27.0.0-Developer.Preview.2")!, "dp2"), + ] + for (version, suffix) in expected { + XCTAssertEqual(badge(version).suffix, suffix, "\(version)") + XCTAssertTrue(badge(version).isPrerelease, "\(version)") + } + } + + func test_prereleaseSuffix_keepsUnknownNames() { + XCTAssertEqual(badge(Version("27.0.0-2")!).suffix, "2") + XCTAssertEqual(badge(Version("27.0.0-Nightly")!).suffix, "Nightly") + } + + #if canImport(AppKit) + private func baseIcon(size: CGFloat, color: NSColor? = nil) -> NSImage { + NSImage(size: NSSize(width: size, height: size), flipped: false) { rect in + if let color { + color.setFill() + rect.fill() + } + return true + } + } + + func test_render_producesBitmapAtEverySize() throws { + let image = try badge(beta2).makeImage(base: baseIcon(size: 256, color: .systemBlue)) + let reps = image.representations.map { (points: Int($0.size.width), pixels: $0.pixelsWide) } + XCTAssertEqual(reps.count, IconBadge.representations.count) + for (rep, expected) in zip(reps, IconBadge.representations) { + XCTAssertEqual(rep.points, expected.points) + XCTAssertEqual(rep.pixels, expected.pixels) + } + // Every point size has a 1x and a 2x bitmap + for points in Set(reps.map(\.points)) { + XCTAssertEqual(reps.filter { $0.points == points }.map(\.pixels).sorted(), [points, points * 2]) + } + } + #endif +} + +final class UpdateIconsTests: XCTestCase { + var installer: XcodeInstaller! + let applied = LockedBox<[(String, String)]>([]) + let removed = LockedBox<[String]>([]) + let logged = LockedBox<[String]>([]) + + let rc = InstalledXcode(path: Path("/Applications/Xcode-27.2.0-Release.Candidate.app")!, version: Version("27.2.0-Release.Candidate")!) + let release = InstalledXcode(path: Path("/Applications/Xcode-27.0.0.app")!, version: Version("27.0.0")!) + + override func setUp() { + Current = .mock + syncXcodesKitMocks() + let installed = [rc, release] + Current.files.installedXcodes = { _ in installed } + Current.logging.log = { [logged] line in logged.update { $0.append(line) } } + Current.icons.applyBadge = { [applied] badge, path in applied.update { $0.append((badge.label, path.string)) } } + Current.icons.removeBadge = { [removed] path in removed.update { $0.append(path.string) } } + installer = XcodeInstaller(xcodeList: XcodeList(), sessionService: AppleSessionService(configuration: Configuration())) + } + + func test_noVersion_badgesEveryXcode() throws { + try installer.addIconBadges(ofVersion: nil, directory: Path("/Applications")!) + XCTAssertEqual(applied.value.map(\.0), ["27.0", "27.2"]) + XCTAssertEqual(applied.value.map(\.1), [release.path.string, rc.path.string]) + } + + func test_version_badgesOnlyThatXcode() throws { + try installer.addIconBadges(ofVersion: "27.2 Release Candidate", directory: Path("/Applications")!) + XCTAssertEqual(applied.value.map(\.0), ["27.2"]) + } + + func test_remove_restoresIcons() throws { + try installer.removeIconBadges(ofVersion: "27.0", directory: Path("/Applications")!) + XCTAssertEqual(removed.value, [release.path.string]) + XCTAssertTrue(applied.value.isEmpty) + } + + func test_unknownVersion_throws() { + XCTAssertThrowsError(try installer.addIconBadges(ofVersion: "1.0", directory: Path("/Applications")!)) { + XCTAssertEqual($0 as? XcodeInstaller.Error, .versionNotInstalled(Version("1.0.0")!)) + } + XCTAssertThrowsError(try installer.addIconBadges(ofVersion: "nope", directory: Path("/Applications")!)) { + XCTAssertEqual($0 as? XcodeInstaller.Error, .invalidVersion("nope")) + } + } + + func test_betaLogLineIncludesTheSuffix() throws { + let beta = InstalledXcode(path: Path("/Applications/Xcode-27.0.0-Beta.2.app")!, version: Version("27.0.0-Beta.2")!) + Current.files.installedXcodes = { _ in [beta] } + try installer.addIconBadges(ofVersion: nil, directory: Path("/Applications")!) + XCTAssertTrue(logged.value.contains { $0.contains("\"27.0b2\"") }, "\(logged.value)") + } + + func test_failures_areReportedAfterTryingEveryXcode() { + struct Boom: Error {} + Current.icons.applyBadge = { [applied] badge, path in + if badge.label == "27.0" { throw Boom() } + applied.update { $0.append((badge.label, path.string)) } + } + XCTAssertThrowsError(try installer.addIconBadges(ofVersion: nil, directory: Path("/Applications")!)) { + XCTAssertEqual($0 as? XcodeInstaller.Error, .failedToUpdateIcons(count: 1)) + } + XCTAssertEqual(applied.value.map(\.0), ["27.2"]) + } +}