Skip to content

Commit

Permalink
Make SemVer sortable
Browse files Browse the repository at this point in the history
  • Loading branch information
jiangpengcheng committed Sep 29, 2020
1 parent dbea286 commit f02111f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import spray.json.deserializationError
import spray.json.JsString
import spray.json.JsValue
import spray.json.RootJsonFormat

import scala.annotation.tailrec
import scala.util.Try

/**
Expand All @@ -34,7 +36,7 @@ import scala.util.Try
*
* @param (major, minor, patch) for the semantic version
*/
protected[core] class SemVer private (private val version: (Int, Int, Int)) extends AnyVal {
protected[core] class SemVer private (private val version: (Int, Int, Int)) extends AnyVal with Ordered[SemVer] {

protected[core] def major = version._1
protected[core] def minor = version._2
Expand All @@ -46,6 +48,24 @@ protected[core] class SemVer private (private val version: (Int, Int, Int)) exte

protected[entity] def toJson = JsString(toString)
override def toString = s"$major.$minor.$patch"

protected[core] def versionList = Seq(major, minor, patch)

override def compare(that: SemVer): Int = {
compareVersion(that)
}

@tailrec
private def compareVersion(that: SemVer, depth: Int = 0): Int = {
require(depth >= 0 && depth <= 2, "depth exceed the limit of 0 to 2")
val result = versionList(depth) - that.versionList(depth)
if (result != 0)
result
else if (depth == 2)
0
else
compareVersion(that, depth + 1)
}
}

protected[core] object SemVer {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ case class WhiskActionVersionList(namespace: EntityPath, name: EntityName, versi
case Some(ver) =>
versions.get(ver).map(DocId(_))
case None if versions.nonEmpty =>
Some(DocId(versions.maxBy(_._1.toString)._2))
Some(DocId(versions.maxBy(_._1)._2))
case _ =>
None
}
Expand Down

0 comments on commit f02111f

Please sign in to comment.