比较groovy中的版本字符串

时间:2011-10-11 08:36:38

标签: string groovy compare

嘿,我创建了一个Groovy脚本,它将提取某个文件夹的版本号。然后我想比较版本号并选择最高版本。

我让我的脚本运行在dir文件夹中,然后我以这种格式获取版本:02.2.02.01

所以我可以得到这样的东西:

  • 02.2.02.01
  • 02.2.02.02
  • 02.2.03.01

我没有将它们作为列表但是像这样:

baseDir.listFiles().each { file -> 
  def string = file.getName().substring(5, 15)
  // do stuff
}

此外,我测试过Groovy可以将它们与>运算符进行比较,它可以!但现在我需要选择版本最高的那个

12 个答案:

答案 0 :(得分:10)

如果我们要求最短的答案,那就必须接近; - )

String mostRecentVersion( List versions ) {
  versions.sort( false ) { a, b ->
    [a,b]*.tokenize('.')*.collect { it as int }.with { u, v ->
      [u,v].transpose().findResult{ x,y-> x<=>y ?: null } ?: u.size() <=> v.size()
    }
  }[-1]
}

答案 1 :(得分:8)

这似乎有效

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()
      println "comparing $numA and $numB"

      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]
}

这是一组不充分的测试。你应该再添加一些。

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'

在Groovy控制台中运行此代码和测试以验证其是否正常工作

答案 2 :(得分:4)

如果有人使用Grails(例如Grails 2.2.3),我认为VersionComparator已经提供了我们所需要的。

如果您不使用Grails,则可以随时使用此类的源代码。

工作测试示例:

import org.codehaus.groovy.grails.plugins.VersionComparator

assert ['1.13.4', '1.4.5'].sort( new VersionComparator() ) == ['1.4.5', '1.13.4']
assert ['3.1.20', '3', '3.0.1', '3.1'].sort( new VersionComparator() ) == ['3', '3.0.1', '3.1', '3.1.20']
assert ['02.2.02.02', '02.2.03.01', '02.2.02.01'].sort( new VersionComparator() ) == ['02.2.02.01', '02.2.02.02', '02.2.03.01']
assert ['4', '2'].sort( new VersionComparator() ) == ['2', '4']
assert ['4.1', '4'].sort( new VersionComparator() ) == ['4', '4.1']
assert ['4.1', '5'].sort( new VersionComparator() ) == ['4.1', '5']

assert new VersionComparator().compare( '1.13.4', '1.4.5' ) > 0
assert new VersionComparator().compare( '1.4.5', '1.13.4' ) < 0

希望这有帮助。

答案 3 :(得分:2)

我的是最短的!大声笑)

versions = versions.sort {a, b ->
  def a1 = a.tokenize('.')*.toInteger(), b1 = b.tokenize('.')*.toInteger()
  for (i in 0..<[a1.size(), b1.size()].min()) 
    if (a1[i] != b1[i]) return a1[i] <=> b1[i]
  0
}

答案 4 :(得分:2)

String maxVersion(versions) {
    versions.max { 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
            }
        }
        verA.size() <=> verB.size()
    }
}

答案 5 :(得分:1)

我使用Jenkins ExtendedChoiceParameter的代码(容忍版本字符串中的非整数片段)

def vers = ['none']
new File(this.getBinding().getVariable('dir')).eachDir() { dir -> dirs.add(dir.getName()) }

vers.sort{x, y ->
  def xa = x.tokenize('._-'); def ya = y.tokenize('._-')
  def sz = Math.min(xa.size(), ya.size())
  for (int i = 0; i < sz; ++i) {
    def xs = xa[i]; def ys = ya[i];
    if (xs.isInteger() && ys.isInteger()) {
      def xn = xs.toInteger()
      def yn = ys.toInteger()
      if (xn != yn) { return xn <=> yn }
    } else if (xs != ys) {
      return xs <=> ys
    }
  }

  return xa.size() <=> ya.size()
}.reverse().join(',')

答案 6 :(得分:0)

这是尼基塔贡献的略微修改版本:

List versions = [ '02.2.02.01', '02.2.02.02', '02.2.03.01']
String mostRecentVersion = versions.sort {a, b ->
  def a1 = a.tokenize('.')*.toInteger(), b1 = b.tokenize('.')*.toInteger()   

  for (i in 0..<[a1.size(), b1.size()].min()){      
    if (a1[i] != b1[i]) {
      return a1[i] <=> b1[i]   
    }
  }
}[-1]

assert mostRecentVersion == '02.2.03.01'

答案 7 :(得分:0)

这是对Tim的回答的修改,它接受两个版本字符串并返回一个布尔值(如果第一个比第二个更新,则为true)

String v1 = '02.2.01.02'
String v2 = '02.2.06.02'

boolean isMoreRecent( String a, String b ) {
    [a,b]*.tokenize('.')*.collect { it as int }.with { u, v ->
       Integer result = [u,v].transpose().findResult{ x,y -> x <=> y ?: null } ?: u.size() <=> v.size()
       return (result == 1)
    } 
}

assert !isMoreRecent(v1,v2)
assert isMoreRecent(v2,v1)​

答案 8 :(得分:0)

我在Android Studio 3.0 Beta 7中使用gradle 4.1。有VersionNumber.java(在C:\ Users \ ssfang.gradle \ wrapper \ dists \ gradle-4.1-all \ bzyivzo6n839fup2jbap0tjew \ gradle-4.1 \ src \ core \下有机\ gradle这个\ util的)

例如:

apply plugin: 'com.android.application'

try{ // undocumented
    println "${android.plugin.getSdkFolder().getAbsolutePath()}"
    // Since 1.3.1 or 1.5.0? android studio version or android gradle plugin?
    println "${android.getSdkDirectory().getAbsolutePath()}"
}catch (ignored){
}

// As of android gradle plugin v2.1.2
println android.sdkDirectory.path
println android.ndkDirectory.path
def buildToolsVer = new File(android.sdkDirectory.path, 'build-tools').listFiles().collect{ VersionNumber.parse(it.getName()) }.sort()
println buildToolsVer
printf('%s, %s\n',  buildToolsVer.head(), buildToolsVer.last().toString())

def String mostRecentVersion(List<String> versions) {
//   TreeMap<VersionNumber, String> verNum2StrMap = versions.collectEntries(new TreeMap(), { [VersionNumber.parse(it), it] })

//    TreeMap<VersionNumber, String> verNum2StrMap = versions.inject(new TreeMap()) { memo, entry ->
//        memo[VersionNumber.parse(entry)] = entry
//        memo
//    }

    TreeMap<VersionNumber, String> verNum2StrMap = versions.inject(new TreeMap()) { map, verStr ->
        map << [(VersionNumber.parse(verStr)): verStr]
    }

    // println verNum2StrMap.lastEntry().value
    verNum2StrMap.lastEntry().value
}

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'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "ss.xsigner"
        minSdkVersion 14
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        setProperty("archivesBaseName", "xsigner")
    }
}

-

enter image description here

enter image description here

答案 9 :(得分:0)

这是我的解决方法:

def availVersion = "1.5.0.2"
def ownVersion   = "2.6.0.1"

def availTokens = availVersion.split('\\.')
def ownTokens   = ownVersion.split('\\.')

def availSize   = availTokens.size()
def ownSize     = ownTokens.size()

def maxSize     = Math.max(availSize, ownSize)

for (int i = 1; i <= maxSize; i++) {
    def availItem = ((i <= availSize) ? availTokens[i - 1] : 0)
    def ownItem    = ((i <= ownSize)  ? ownTokens[i - 1]   : 0)

    print "Avail: ${availItem} -> Own: ${ownItem}\n"

    if ((ownItem > availItem) || ( (i == maxSize) && (ownItem >= availItem) )) {
        print "Upgrade NOT needed.\n"
        return
    }
}

print "Upgrade needed!\n"

答案 10 :(得分:0)

只要版本包含在字符串中,为什么不使用字符串比较属性? (或者我错过了什么?)

示例:

v1 = "1.2.6.5"
v2 = "1.3.4"

assert (v1 != v2)
assert (v1 < v2)
assert (v1 <= v2)
assert !(v1 > v2)

def availVersion = "1.5.0.2"
def ownVersion   = "2.6.0.1"

assert (availVersion != ownVersion)
assert (availVersion < ownVersion)
assert (availVersion <= ownVersion)
assert !(availVersion > ownVersion)

我做了以下操作来确定最新版本,并且效果很好:

ma_list = [v1, v2, "2.6.1.0.0", availVersion, ownVersion]

latest = ""
ma_list.each{
    //println it

    if (it > latest)
        latest = it
}
assert (latest == "2.6.1.0.0")
println "latest = $latest"

答案 11 :(得分:0)

如果您只需要实现ComparableComparator接口,这是我根据其他答案得出的最短的解决方案:

    [first, second]*.tokenize('.').with { a, b ->
        [a, b].transpose().findResult { x, y -> x <=> y ?: null } ?: a.size() <=> b.size()
    }