问题描述
我想对 Iterable<Component> components
中的版本进行排序。当我在控制台中打印时,它会显示以下结果:
artifact 1.0.1
artifact 1.0.10
artifact 1.0.11
artifact 1.0.12
artifcat 1.0.2
artifcat 1.0.3
artifcat 1.0.4
这是我的代码
import org.sonatype.nexus.repository.storage.Component
import org.sonatype.nexus.repository.storage.Query
import org.sonatype.nexus.repository.storage.StorageFacet
def repoName = "artifact"
log.info("delete components for repository: " + repoName)
def repo = repository.repositoryManager.get(repoName)
def tx = repo.facet(StorageFacet).txsupplier().get()
try {
tx.begin()
Iterable<Component> components = tx.findComponents(Query.builder()
.where('version < ').param('1.1.0')
.build(),[repo])
tx.commit()
for(Component c : components) {
log.info("Name " + c.name() + " Version" + c.version())
}
} catch (Exception e) {
log.warn("Transaction Failed {}",e.toString())
tx.rollback()
} finally {
tx.close()
}
解决方法
可以按如下方式进行一些简单的按版本排序:
def components = []
'''\
artifact 1.2.1
artifact 1.0.1
artifact 1.0.10
artifact 2.0.10
artifact 1.0.11
artifact 1.0.12
artifact 1.4.12
artifcat 1.0.2
artifcat 1.0.3
artifcat 1.0.4'''.splitEachLine( ' ' ){ name,version ->
components << [ name:name,version:version ]
}
// augment each component with numeric represenation of version
components.each{
it.versionNumeric = it.version.split( /\./ )*.toInteger().reverse().withIndex().sum{ num,pow -> 100.power( pow ) * num }
}
components.sort{ it.versionNumeric }*.version.join '\n'
印刷品
1.0.1
1.0.2
1.0.3
1.0.4
1.0.10
1.0.11
1.0.12
1.2.1
1.4.12
2.0.10
,
另一个例子:
def components = '''\
artifact 1.2.1
artifact 1.0.1
artifact 1.0.10
artifact 2.0.10
artifact 10.2
artifact 1.0.11
artifact 1.0.12
artifact 1.4.12
artifcat 1.0.2
artifcat 1.0.3
artifcat 1.0.4
artifact 1.0.4.2'''.readLines()*.tokenize(' ').collect { name,version ->
[name: name,version: version]
}
def sorted = components.sort { a,b ->
def f = { it.version.tokenize('.')*.toInteger() }
[f(a),f(b)].transpose().findResult { ai,bi ->
ai <=> bi ?: null
} ?: a.version <=> b.version
}
sorted.each { c ->
println c.version
}
打印:
─➤ groovy solution.groovy
1.0.1
1.0.2
1.0.3
1.0.4
1.0.4.2
1.0.10
1.0.11
1.0.12
1.2.1
1.4.12
2.0.10
10.2
请注意,此解决方案还(至少或多或少)处理具有不同元素数量的版本,例如 10.2
和 1.0.4.2
。