Skip to content

Commit e814321

Browse files
committed
Ability to lift a ScalaVersion from a String
1 parent fca373c commit e814321

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

lib/src/main/scala/org/typelevel/scalacoptions/ScalaVersion.scala

+11
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,17 @@ object ScalaVersion {
4444
val V3_3_0 = ScalaVersion(3, 3, 0)
4545
val V3_3_1 = ScalaVersion(3, 3, 1)
4646

47+
private val versionRegex = raw"""(\d+)\.(\d+)\.(\d+)(?:-.*)?""".r
48+
def fromString(version: String): Either[IllegalArgumentException, ScalaVersion] =
49+
version match {
50+
case versionRegex(major, minor, patch) =>
51+
Right(ScalaVersion(major.toLong, minor.toLong, patch.toLong))
52+
case _ => Left(new IllegalArgumentException(s"Scala version $version not recognized"))
53+
}
54+
55+
def unsafeFromString(version: String): ScalaVersion =
56+
fromString(version).fold(throw _, identity)
57+
4758
implicit val scalaVersionOrdering: Ordering[ScalaVersion] =
4859
Ordering.by(version => (version.major, version.minor, version.patch))
4960
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Copyright 2022 Typelevel
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.typelevel.scalacoptions
18+
19+
import org.scalacheck.Gen
20+
import org.scalacheck.Prop.forAll
21+
22+
class ScalaVersionSuite extends munit.ScalaCheckSuite {
23+
val versionGen = Gen.chooseNum(0L, 20L)
24+
25+
property("fromString parse a version") {
26+
forAll(versionGen, versionGen, versionGen) {
27+
(currentMaj: Long, currentMin: Long, currentPatch: Long) =>
28+
val version = ScalaVersion.fromString(s"$currentMaj.$currentMin.$currentPatch")
29+
assertEquals(version, Right(ScalaVersion(currentMaj, currentMin, currentPatch)))
30+
}
31+
}
32+
33+
property("fromString parse an RC version") {
34+
forAll(versionGen, versionGen, versionGen) {
35+
(currentMaj: Long, currentMin: Long, currentPatch: Long) =>
36+
val version = ScalaVersion.fromString(s"$currentMaj.$currentMin.$currentPatch-RC3")
37+
assertEquals(version, Right(ScalaVersion(currentMaj, currentMin, currentPatch)))
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)