Skip to content

Instantly share code, notes, and snippets.

@shyiko
Created August 29, 2017 00:16
Show Gist options
  • Save shyiko/a75c466b88ca3bd97324bb31600f6cf7 to your computer and use it in GitHub Desktop.
Save shyiko/a75c466b88ca3bd97324bb31600f6cf7 to your computer and use it in GitHub Desktop.
Maven Conflict Resolver
// Usage:
// 1. ./mvnw dependency:tree -Dverbose | kotlinc -script mvn-confict-resolver.kts
// 2. update pom.xml's
// <dependencyManagement><dependencies><!-- INSERT 1. OUTPUT HERE --></dependencies></dependencyManagement>
import java.util.Scanner
val input = Scanner(System.`in`).useDelimiter("\\A").next()
println(
Regex("[(]([\\w.-]+:[\\w.-]+:jar:[\\w.-]+):[^ ]+ - omitted for conflict with ([\\w.-]+)")
.findAll(input)
.fold(mutableMapOf<Pair<String, String>,MutableList<String>> (),
{ acc, match ->
val (groupId, artifactId, _, version) = match.groupValues[1].split(":")
val entry = acc.computeIfAbsent(groupId to artifactId, { mutableListOf<String>() })
entry.add(version)
entry.add(match.groupValues[2])
acc
})
.mapValues { it.value.sortWith(NaturalOrderComparator); it.value.last() }
.map {
val (groupId, artifactId) = it.key
val version = it.value
"""
<dependency>
<groupId>$groupId</groupId>
<artifactId>$artifactId</artifactId>
<version>$version</version>
</dependency>
""".trimIndent()
}
.distinct()
.sorted()
.joinToString("\n")
)
object NaturalOrderComparator : Comparator<String> {
/**
* General idea is to find first-from-the-left character that is different and (if both characters are numbers)
* compare the "remaining numeric part" of both strings.
*
* Complexity: time - O(n), space - O(1).
*/
override fun compare(l: String, r: String): Int {
val ll = l.length
val rl = r.length
if (ll > rl) {
return -1 * compare(r, l)
}
var di = 0
var dc = 0
while (di < ll) {
dc = l[di] - r[di]
if (dc != 0) {
break
}
di++
}
if (di == ll) {
return ll - rl
}
if (l[di].isDigit()) {
if (r[di].isDigit()) {
var lnl = 0
var rnl = 0
var j = di + 1
while (j < ll && l[j].isDigit()) {
j++
lnl++
}
j = di + 1
val e = Math.min(j + lnl + 1, rl)
while (j < e && r[j].isDigit()) {
j++
rnl++
}
return if (lnl == rnl) dc else lnl - rnl
}
if (di > 0 && r[di - 1].isDigit()) {
return 1
}
} else if (r[di].isDigit()) {
if (di > 0 && l[di - 1].isDigit()) {
return -1
}
}
return dc
}
}
@shyiko
Copy link
Author

shyiko commented Sep 7, 2017

./mvnw -pl <name of the module> dependency:tree -Dverbose | kotlinc -script mvn-confict-resolver.kts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment