Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

Compare version strings in groovy

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:

  • 02.2.02.01
  • 02.2.02.02
  • 02.2.03.01

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...