Skip to content

Commit d58ec13

Browse files
committed
Implementation of lenient version parsing that doesn't require patch version
1 parent 907b747 commit d58ec13

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

Sources/TSCUtility/Version.swift

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,8 @@ public extension Version {
109109
///
110110
/// - Parameters:
111111
/// - string: The string to parse.
112-
init?(string: String) {
112+
/// - lenient: Boolean indicating if partial strings should be parsed. Infers that strings without an explicit patch version have a patch version of zero. Defaults to false.
113+
init?(string: String, lenient: Bool = false) {
113114
let prereleaseStartIndex = string.firstIndex(of: "-")
114115
let metadataStartIndex = string.firstIndex(of: "+")
115116

@@ -119,11 +120,15 @@ public extension Version {
119120
.split(separator: ".", maxSplits: 2, omittingEmptySubsequences: false)
120121
.map(String.init).compactMap({ Int($0) }).filter({ $0 >= 0 })
121122

122-
guard requiredComponents.count == 3 else { return nil }
123+
guard requiredComponents.count == 3 || (requiredComponents.count == 2 && lenient) else { return nil }
123124

124125
self.major = requiredComponents[0]
125126
self.minor = requiredComponents[1]
126-
self.patch = requiredComponents[2]
127+
if(requiredComponents.count == 3) {
128+
self.patch = requiredComponents[2]
129+
} else {
130+
self.patch = 0
131+
}
127132

128133
func identifiers(start: String.Index?, end: String.Index) -> [String] {
129134
guard let start = start else { return [] }

Tests/TSCUtilityTests/VersionTests.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,4 +285,11 @@ class VersionTests: XCTestCase {
285285
XCTAssertFalse(range.contains(version: "1.1.0-beta"))
286286
}
287287
}
288+
289+
func testLenientParsing()
290+
{
291+
XCTAssertEqual(Version(string: "1.2", lenient: true), Version(string: "1.2.0"))
292+
XCTAssertEqual(Version(string: "1", lenient: true), nil)
293+
XCTAssertEqual(Version(string: "1.2", lenient: false), nil)
294+
}
288295
}

0 commit comments

Comments
 (0)