Created
December 7, 2020 15:40
-
-
Save nwellis/f7c9cce0bbcc701a08633602fad7b611 to your computer and use it in GitHub Desktop.
Kotlin data class that parses a string into a semantic version, where each major/minor/patch is an integer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| data class SemanticVersion(val major: Int, val minor: Int, val patch: Int) { | |
| companion object { | |
| fun fromString(version: String?): SemanticVersion? = version | |
| ?.takeIf { it.isNotBlank() } | |
| ?.split(".") | |
| ?.let { split -> | |
| return SemanticVersion( | |
| major = split.getOrNull(0)?.toIntOrNull() ?: 0, | |
| minor = split.getOrNull(1)?.toIntOrNull() ?: 0, | |
| patch = split.getOrNull(2)?.toIntOrNull() ?: 0 | |
| ) | |
| } | |
| } | |
| fun toVersionCode() = (major * 10_000) + (minor * 100) + patch | |
| override fun toString() = "$major.$minor.$patch" | |
| operator fun compareTo(other: SemanticVersion): Int = compareTo(other, ignorePatch = false) | |
| fun compareTo(other: SemanticVersion, ignorePatch: Boolean = false): Int { | |
| return when { | |
| // Major | |
| (major < other.major) -> -1 | |
| (major > other.major) -> 1 | |
| // Minor | |
| (minor < other.minor) -> -1 | |
| (minor > other.minor) -> 1 | |
| // Patch | |
| !ignorePatch && (patch < other.patch) -> -1 | |
| !ignorePatch && (patch > other.patch) -> 1 | |
| // Equal! | |
| else -> 0 | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment