Version.kt (2371B)
1 /* 2 * This file is part of GNU Taler 3 * (C) 2020 Taler Systems S.A. 4 * 5 * GNU Taler is free software; you can redistribute it and/or modify it under the 6 * terms of the GNU General Public License as published by the Free Software 7 * Foundation; either version 3, or (at your option) any later version. 8 * 9 * GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY 10 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 * A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License along with 14 * GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 package net.taler.common 18 19 import kotlin.math.sign 20 21 /** 22 * Semantic versioning, but libtool-style. 23 * See https://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html 24 */ 25 public data class Version( 26 val current: Int, 27 val revision: Int, 28 val age: Int 29 ) { 30 public companion object { 31 public fun parse(v: String): Version? { 32 val elements = v.split(":") 33 if (elements.size != 3) return null 34 val (currentStr, revisionStr, ageStr) = elements 35 val current = currentStr.toIntOrNull() 36 val revision = revisionStr.toIntOrNull() 37 val age = ageStr.toIntOrNull() 38 if (current == null || revision == null || age == null) return null 39 return Version(current, revision, age) 40 } 41 } 42 43 /** 44 * Compare two libtool-style versions. 45 * 46 * Returns a [VersionMatchResult] or null if the given version was null. 47 */ 48 public fun compare(other: Version?): VersionMatchResult? { 49 if (other == null) return null 50 val compatible = current - age <= other.current && 51 current >= other.current - other.age 52 val currentCmp = sign((current - other.current).toDouble()).toInt() 53 return VersionMatchResult(compatible, currentCmp) 54 } 55 56 /** 57 * Result of comparing two libtool versions. 58 */ 59 public data class VersionMatchResult( 60 /** 61 * Is the first version compatible with the second? 62 */ 63 val compatible: Boolean, 64 /** 65 * Is the first version older (-1), newer (+1) or identical (0)? 66 */ 67 val currentCmp: Int 68 ) 69 70 }