Hey I have created a Groovy script that will extract the version numbers of some folder. I would then like to compare the version numbers and select the highest.
I got my script to run through the dir folder and I then get the versions in this format: 02.2.02.01
So I could get something like this:
I don't have them as a list but like this:
baseDir.listFiles().each { file ->
def string = file.getName().substring(5, 15)
// do stuff
}
Also I have tested that Groovy could compare them with the >
operator and it can! But now I need to select the one with the highest version
You can find it on my GitHub. Method Version. compareVersions(String v1, String v2) compares two version strings. It returns 0 if the versions are equal, 1 if version v1 is before version v2, -1 if version v1 is after version v2, -2 if version format is invalid.
Groovy - compareTo() The compareTo method is to use compare one number against another. This is useful if you want to compare the value of numbers.
This appears to work
String mostRecentVersion(List versions) {
def sorted = versions.sort(false) { a, b ->
List verA = a.tokenize('.')
List verB = b.tokenize('.')
def commonIndices = Math.min(verA.size(), verB.size())
for (int i = 0; i < commonIndices; ++i) {
def numA = verA[i].toInteger()
def numB = verB[i].toInteger()
if (numA != numB) {
return numA <=> numB
}
}
// If we got this far then all the common indices are identical, so whichever version is longer must be more recent
verA.size() <=> verB.size()
}
println "sorted versions: $sorted"
sorted[-1]
}
Here is an inadequate set of tests. You should add some more.
assert mostRecentVersion(['02.2.02.01', '02.2.02.02', '02.2.03.01']) == '02.2.03.01'
assert mostRecentVersion(['4', '2']) == '4'
assert mostRecentVersion(['4.1', '4']) == '4.1'
assert mostRecentVersion(['4.1', '5']) == '5'
Run this code and the tests in the Groovy console to verify that it works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With