|
| 1 | +import ArgumentParser |
| 2 | +import CryptoKit |
| 3 | +import Foundation |
| 4 | + |
| 5 | +#if canImport(FoundationNetworking) |
| 6 | + import FoundationNetworking |
| 7 | +#endif |
| 8 | + |
| 9 | +// Helper to write to stderr |
| 10 | +var standardError = FileHandle.standardError |
| 11 | + |
| 12 | +extension FileHandle: @retroactive TextOutputStream { |
| 13 | + public func write(_ string: String) { |
| 14 | + guard let data = string.data(using: .utf8) else { return } |
| 15 | + self.write(data) |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +struct Release: Codable { |
| 20 | + let name: String |
| 21 | + let tag: String |
| 22 | + let xcode: String? |
| 23 | + let xcode_release: Bool? |
| 24 | + let date: String? |
| 25 | + let platforms: [Platform] |
| 26 | + |
| 27 | + struct Platform: Codable { |
| 28 | + let name: String |
| 29 | + let platform: String |
| 30 | + let docker: String? |
| 31 | + let dir: String? |
| 32 | + let checksum: String? |
| 33 | + let archs: [String] |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +typealias ReleasesResponse = [Release] |
| 38 | + |
| 39 | +func fetchReleases() throws -> ReleasesResponse { |
| 40 | + let url = URL(string: "https://www.swift.org/api/v1/install/releases.json")! |
| 41 | + let semaphore = DispatchSemaphore(value: 0) |
| 42 | + var result: Result<Data, Error>? |
| 43 | + |
| 44 | + let task = URLSession.shared.dataTask(with: url) { data, response, error in |
| 45 | + if let error = error { |
| 46 | + result = .failure(error) |
| 47 | + } else if let httpResponse = response as? HTTPURLResponse { |
| 48 | + if httpResponse.statusCode != 200 { |
| 49 | + let error = NSError( |
| 50 | + domain: "SwiftReleaseDownloader", |
| 51 | + code: httpResponse.statusCode, |
| 52 | + userInfo: [NSLocalizedDescriptionKey: "HTTP error \(httpResponse.statusCode)"] |
| 53 | + ) |
| 54 | + result = .failure(error) |
| 55 | + } else if let data = data { |
| 56 | + result = .success(data) |
| 57 | + } else { |
| 58 | + result = .failure( |
| 59 | + NSError( |
| 60 | + domain: "SwiftReleaseDownloader", code: -1, |
| 61 | + userInfo: [NSLocalizedDescriptionKey: "No data received"])) |
| 62 | + } |
| 63 | + } else if let data = data { |
| 64 | + result = .success(data) |
| 65 | + } else { |
| 66 | + result = .failure( |
| 67 | + NSError( |
| 68 | + domain: "SwiftReleaseDownloader", code: -1, |
| 69 | + userInfo: [NSLocalizedDescriptionKey: "No data received"])) |
| 70 | + } |
| 71 | + semaphore.signal() |
| 72 | + } |
| 73 | + task.resume() |
| 74 | + semaphore.wait() |
| 75 | + |
| 76 | + let data = try result!.get() |
| 77 | + let decoder = JSONDecoder() |
| 78 | + return try decoder.decode(ReleasesResponse.self, from: data) |
| 79 | +} |
| 80 | + |
| 81 | +func downloadFile(url: URL, cacheDir: String?) throws -> Data { |
| 82 | + // Check cache first if cache directory is provided |
| 83 | + if let cacheDir = cacheDir { |
| 84 | + let filename = url.lastPathComponent |
| 85 | + let cachePath = (cacheDir as NSString).appendingPathComponent(filename) |
| 86 | + |
| 87 | + if FileManager.default.fileExists(atPath: cachePath) { |
| 88 | + print("Found \(filename) in \(cacheDir). Skipping", to: &standardError) |
| 89 | + return try Data(contentsOf: URL(fileURLWithPath: cachePath)) |
| 90 | + } |
| 91 | + } |
| 92 | + print("Downloading \(url)...", to: &standardError) |
| 93 | + |
| 94 | + let semaphore = DispatchSemaphore(value: 0) |
| 95 | + var result: Result<Data, Error>? |
| 96 | + |
| 97 | + let task = URLSession.shared.dataTask(with: url) { data, response, error in |
| 98 | + if let error = error { |
| 99 | + result = .failure(error) |
| 100 | + } else if let httpResponse = response as? HTTPURLResponse { |
| 101 | + if httpResponse.statusCode != 200 { |
| 102 | + let error = NSError( |
| 103 | + domain: "SwiftReleaseDownloader", |
| 104 | + code: httpResponse.statusCode, |
| 105 | + userInfo: [ |
| 106 | + NSLocalizedDescriptionKey: |
| 107 | + "HTTP error \(httpResponse.statusCode) for \(url.absoluteString)" |
| 108 | + ] |
| 109 | + ) |
| 110 | + result = .failure(error) |
| 111 | + } else if let data = data { |
| 112 | + result = .success(data) |
| 113 | + } else { |
| 114 | + result = .failure( |
| 115 | + NSError( |
| 116 | + domain: "SwiftReleaseDownloader", code: -1, |
| 117 | + userInfo: [NSLocalizedDescriptionKey: "No data received"])) |
| 118 | + } |
| 119 | + } else if let data = data { |
| 120 | + result = .success(data) |
| 121 | + } else { |
| 122 | + result = .failure( |
| 123 | + NSError( |
| 124 | + domain: "SwiftReleaseDownloader", code: -1, |
| 125 | + userInfo: [NSLocalizedDescriptionKey: "No data received"])) |
| 126 | + } |
| 127 | + semaphore.signal() |
| 128 | + } |
| 129 | + task.resume() |
| 130 | + semaphore.wait() |
| 131 | + |
| 132 | + let data = try result!.get() |
| 133 | + |
| 134 | + // Save to cache if cache directory is provided |
| 135 | + if let cacheDir = cacheDir { |
| 136 | + let filename = url.lastPathComponent |
| 137 | + let cachePath = (cacheDir as NSString).appendingPathComponent(filename) |
| 138 | + |
| 139 | + // Create cache directory if it doesn't exist |
| 140 | + try FileManager.default.createDirectory( |
| 141 | + atPath: cacheDir, withIntermediateDirectories: true, attributes: nil) |
| 142 | + |
| 143 | + // Write data to cache |
| 144 | + try data.write(to: URL(fileURLWithPath: cachePath)) |
| 145 | + print(" Cached to: \(cachePath)", to: &standardError) |
| 146 | + } |
| 147 | + |
| 148 | + return data |
| 149 | +} |
| 150 | + |
| 151 | +func sha256(data: Data) -> String { |
| 152 | + let hash = SHA256.hash(data: data) |
| 153 | + return hash.compactMap { String(format: "%02x", $0) }.joined() |
| 154 | +} |
| 155 | + |
| 156 | +func getDownloadURL(tag: String, platformName: String) -> String { |
| 157 | + let version = tag |
| 158 | + let category = tag.lowercased() |
| 159 | + let filename: String |
| 160 | + |
| 161 | + let platformDir = platformName.replacingOccurrences(of: ".", with: "") |
| 162 | + if platformName == "xcode" { |
| 163 | + filename = "\(version)-osx.pkg" |
| 164 | + } else { |
| 165 | + filename = "\(version)-\(platformName).tar.gz" |
| 166 | + } |
| 167 | + |
| 168 | + return "https://download.swift.org/\(category)/\(platformDir)/\(version)/\(filename)" |
| 169 | +} |
| 170 | + |
| 171 | +@main |
| 172 | +struct SwiftReleases: ParsableCommand { |
| 173 | + static let configuration = CommandConfiguration( |
| 174 | + commandName: "swift-releases", |
| 175 | + abstract: "A utility for working with Swift releases", |
| 176 | + subcommands: [List.self], |
| 177 | + defaultSubcommand: List.self |
| 178 | + ) |
| 179 | +} |
| 180 | + |
| 181 | +extension SwiftReleases { |
| 182 | + struct List: ParsableCommand { |
| 183 | + static let configuration = CommandConfiguration( |
| 184 | + abstract: "Download Swift release archives and print their SHA256 hashes" |
| 185 | + ) |
| 186 | + |
| 187 | + @Argument(help: "The Swift version to download (e.g., 6.0.3)") |
| 188 | + var version: String |
| 189 | + |
| 190 | + @Option(help: "Directory to cache downloaded archives") |
| 191 | + var cache: String? |
| 192 | + |
| 193 | + func run() throws { |
| 194 | + let releases = try fetchReleases() |
| 195 | + |
| 196 | + guard let release = releases.first(where: { $0.name == version }) else { |
| 197 | + print("Error: Version '\(version)' not found", to: &standardError) |
| 198 | + print("Available versions:", to: &standardError) |
| 199 | + for rel in releases.reversed().prefix(20) { |
| 200 | + print(" - \(rel.name)", to: &standardError) |
| 201 | + } |
| 202 | + if releases.count > 20 { |
| 203 | + print(" ... and \(releases.count - 20) more", to: &standardError) |
| 204 | + } |
| 205 | + throw ExitCode.failure |
| 206 | + } |
| 207 | + |
| 208 | + // Dictionary to store platform -> sha256 mappings |
| 209 | + var checksums: [String: String] = [:] |
| 210 | + |
| 211 | + // Only Linux & MacOS toolchains are supported for now. |
| 212 | + // Supported Linux toolchains for a given version are in the response, |
| 213 | + // but MacOS toolchains aren't. They're just assumed to be there. So we |
| 214 | + // must add them manually. |
| 215 | + let platforms = |
| 216 | + release.platforms.filter { |
| 217 | + $0.platform == "Linux" |
| 218 | + } + [ |
| 219 | + Release.Platform( |
| 220 | + name: "osx", |
| 221 | + platform: "osx", |
| 222 | + docker: nil, |
| 223 | + dir: "xcode", |
| 224 | + checksum: nil, |
| 225 | + archs: ["aarch64"], |
| 226 | + ) |
| 227 | + ] |
| 228 | + |
| 229 | + for platform in platforms { |
| 230 | + // Handle platforms with checksums (like static-sdk, wasm-sdk) |
| 231 | + if let checksum = platform.checksum { |
| 232 | + // For platforms with checksums, use the platform name directly |
| 233 | + let platformKey = platform.platform |
| 234 | + checksums[platformKey] = checksum |
| 235 | + continue |
| 236 | + } |
| 237 | + |
| 238 | + // Download for each architecture |
| 239 | + for arch in platform.archs { |
| 240 | + let platformName = |
| 241 | + platform.dir ?? platform.name.lowercased().replacingOccurrences(of: " ", with: "") |
| 242 | + let platformKey: String |
| 243 | + if platformName == "xcode" || arch == "x86_64" { |
| 244 | + platformKey = platformName |
| 245 | + } else { |
| 246 | + platformKey = "\(platformName)-\(arch)" |
| 247 | + } |
| 248 | + |
| 249 | + let downloadURL = getDownloadURL( |
| 250 | + tag: release.tag, platformName: platform.dir ?? platformKey) |
| 251 | + |
| 252 | + do { |
| 253 | + let url = URL(string: downloadURL)! |
| 254 | + let data = try downloadFile(url: url, cacheDir: cache) |
| 255 | + let hash = sha256(data: data) |
| 256 | + checksums[platformKey] = hash |
| 257 | + } catch { |
| 258 | + print("Error: \(error)", to: &standardError) |
| 259 | + throw error |
| 260 | + } |
| 261 | + } |
| 262 | + } |
| 263 | + |
| 264 | + // Print in the requested format |
| 265 | + print(" \"\(version)\": {") |
| 266 | + let sortedKeys = checksums.keys.sorted() |
| 267 | + for (index, key) in sortedKeys.enumerated() { |
| 268 | + let comma = index < sortedKeys.count - 1 ? "," : "" |
| 269 | + print(" \"\(key)\": \"\(checksums[key]!)\"\(comma)") |
| 270 | + } |
| 271 | + print(" },") |
| 272 | + } |
| 273 | + } |
| 274 | +} |
0 commit comments