sbt-gs-semver/src/main/scala/gs/SemVer.scala

83 lines
2.1 KiB
Scala

package gs
import scala.util.matching.Regex
/** Simplified representation of SemVer. Only supports major, minor and patch
* versions. Not intended to be used as a generalized SemVer implementation.
*
* @param major
* The major version.
* @param minor
* The minor version.
* @param patch
* The patch version.
*/
case class SemVer(
major: Int,
minor: Int,
patch: Int
) {
/** Render this SemVer as: `Major.Minor.Patch`
*
* @return
* The `Major.Minor.Patch` representation of this SemVer.
*/
override def toString(): String =
s"$major.$minor.$patch"
/** Render this SemVer as: `Major.Minor.Patch`, and append a suffix,
* `-SNAPSHOT` if a snapshot rendition is requested.
*
* @param isSnapshot
* Requests a snapshot rendition if true. Uses the `-SNAPSHOT` pre-release
* suffix.
* @return
* The string rendition of this version.
*/
def render(isSnapshot: Boolean): String = {
val version = toString()
if (isSnapshot) version + "-SNAPSHOT" else version
}
/** @return
* Copy of this SemVer with the major version incremented by 1.
*/
def incrementMajor(): SemVer = copy(major = this.major + 1)
/** @return
* Copy of this SemVer with the minor version incremented by 1.
*/
def incrementMinor(): SemVer = copy(minor = this.minor + 1)
/** @return
* Copy of this SemVer with the patch version incremented by 1.
*/
def incrementPatch(): SemVer = copy(patch = this.patch + 1)
}
object SemVer {
/** Version 0.1.0
*/
val DefaultVersion: SemVer = SemVer(0, 1, 0)
private val SemVerPattern: Regex =
"^(0|(?:[1-9][0-9]*))\\.(0|(?:[1-9][0-9]*))\\.(0|(?:[1-9][0-9]*))$".r
/** Attempt to parse the input string as a [[SemVer]].
*
* @param candidate
* The candidate string to parse.
* @return
* The parsed [[SemVer]], or `None` if parsing failed.
*/
def parse(candidate: String): Option[SemVer] =
candidate match {
case SemVerPattern(major, minor, patch) =>
Some(SemVer(major.toInt, minor.toInt, patch.toInt))
case _ =>
None
}
}