xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / PackLib / SwiftVersion.swift
SwiftVersion.swift92 lines · 2.5 KiBRaw
| 1 | import Subprocess |
| 2 | import XUtils |
| 3 | |
| 4 | public struct SwiftVersion: Sendable, Comparable, Hashable { |
| 5 | public var major: Int |
| 6 | public var minor: Int |
| 7 | public var patch: Int |
| 8 | |
| 9 | public init(_ major: Int, _ minor: Int, _ patch: Int = 0) { |
| 10 | self.major = major |
| 11 | self.minor = minor |
| 12 | self.patch = patch |
| 13 | } |
| 14 | |
| 15 | public static func < (lhs: Self, rhs: Self) -> Bool { |
| 16 | lhs.tuple < rhs.tuple |
| 17 | } |
| 18 | |
| 19 | fileprivate var tuple: (Int, Int, Int) { |
| 20 | (major, minor, patch) |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | extension SwiftVersion { |
| 25 | public var supportsSwiftBuild: Bool { |
| 26 | self >= SwiftVersion(6, 4) |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | extension SwiftVersion: LosslessStringConvertible, CustomStringConvertible { |
| 31 | public var description: String { |
| 32 | "\(major).\(minor).\(patch)" |
| 33 | } |
| 34 | |
| 35 | public init?(_ description: String) { |
| 36 | // inverse of https://github.com/swiftlang/swift/blob/896191b38/lib/Basic/Version.cpp#L266 |
| 37 | |
| 38 | var output = description[...] |
| 39 | if output.hasPrefix("Apple ") { |
| 40 | output = output.dropFirst("Apple ".count) |
| 41 | } |
| 42 | if output.hasPrefix("Swift version ") { |
| 43 | output = output.dropFirst("Swift version ".count) |
| 44 | output = output.prefix { !$0.isWhitespace } |
| 45 | } |
| 46 | let isDev = output.hasSuffix("-dev") |
| 47 | if isDev { output = output.dropLast("-dev".count) } |
| 48 | |
| 49 | let parts = output.split(separator: ".") |
| 50 | var numericParts = parts.compactMap { Int($0) } |
| 51 | guard parts.count == numericParts.count else { |
| 52 | return nil |
| 53 | } |
| 54 | |
| 55 | switch numericParts.count { |
| 56 | case 2: numericParts.append(0) |
| 57 | case 3: break |
| 58 | default: return nil |
| 59 | } |
| 60 | |
| 61 | self.init(numericParts[0], numericParts[1], numericParts[2]) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | extension SwiftVersion { |
| 66 | private static let cached = Task<Self, Error> { |
| 67 | let outputString: String? |
| 68 | do { |
| 69 | outputString = try await Subprocess.run( |
| 70 | .path(try await BuildSettings.swiftURL()), |
| 71 | arguments: ["--version"], |
| 72 | output: .string(limit: .max) |
| 73 | ) |
| 74 | .checkSuccess() |
| 75 | .standardOutput |
| 76 | } catch { |
| 77 | throw StringError("Failed to obtain Swift version") |
| 78 | } |
| 79 | |
| 80 | let output = outputString ?? "" |
| 81 | guard let version = Self(output) else { |
| 82 | throw StringError("Could not parse Swift version: '\(output)'") |
| 83 | } |
| 84 | return version |
| 85 | } |
| 86 | |
| 87 | public static var current: Self { |
| 88 | get async throws { |
| 89 | try await cached.value |
| 90 | } |
| 91 | } |
| 92 | } |