SemanticVersion.scala 2.12 KB
Newer Older
1
package nl.lumc.sasc.biopet.utils
2
import scala.util.matching.Regex
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

/**
  * Created by pjvanthof on 29/04/2017.
  */
case class SemanticVersion(major: Int, minor: Int, patch: Int, build: Option[String] = None) {
  def >(that: SemanticVersion): Boolean = {
    if (this.major != that.major) this.major > that.major
    else if (this.minor != that.minor) this.minor > that.minor
    else if (this.patch != that.patch) this.patch > that.patch
    else false
  }

  def <(that: SemanticVersion): Boolean = {
    if (this.major != that.major) this.major < that.major
    else if (this.minor != that.minor) this.minor < that.minor
    else if (this.patch != that.patch) this.patch < that.patch
    else false
  }

  def >=(that: SemanticVersion): Boolean = {
    if (this.major != that.major) this.major > that.major
    else if (this.minor != that.minor) this.minor > that.minor
    else if (this.patch != that.patch) this.patch > that.patch
    else true
  }

  def <=(that: SemanticVersion): Boolean = {
    if (this.major != that.major) this.major < that.major
    else if (this.minor != that.minor) this.minor < that.minor
    else if (this.patch != that.patch) this.patch < that.patch
    else true
  }
}

object SemanticVersion {
38
  val semanticVersionRegex: Regex = "[vV]?(\\d+)\\.(\\d+)\\.(\\d+)(-.*)?".r
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

  /**
    * Check whether a version string is a semantic version.
    *
    * @param version version string
    * @return boolean
    */
  def isSemanticVersion(version: String): Boolean = getSemanticVersion(version).isDefined

  /**
    * Check whether a version string is a semantic version.
    * Note: the toInt calls here are only safe because the regex only matches numbers
    *
    * @param version version string
    * @return SemanticVersion case class
    */
  def getSemanticVersion(version: String): Option[SemanticVersion] = {
    version match {
      case semanticVersionRegex(major, minor, patch, build) =>
        Some(
          SemanticVersion(major.toInt,
60 61 62
                          minor.toInt,
                          patch.toInt,
                          Option(build).map(x => x.stripPrefix("-"))))
63 64 65 66 67
      case _ => None
    }
  }

}