Check and Modify Artifacts versions in a pom.xml

Taking advantage of the easy XML processing, built in regular expressions I wrote a short script in Groovy to check and modify artifacts version in a pom.xml (Maven).

For example to show all dependencies with the word datanucleus in it, and display them in compact form (groupId:artifactId:version)

[sourcecode language="bash"]
$ pomVersions datanucleus
com.google.appengine.orm:datanucleus-appengine:2.0.0-RC2
org.datanucleus:datanucleus-core:3.0.4
org.datanucleus:datanucleus-api-jpa:3.0.4
org.datanucleus:datanucleus-rdbms:3.0.4
[/sourcecode]

I want to change datanucleus-core to version 3.0.7 – first I check that I indeed match only one artifact:

[sourcecode language="bash"]
$ pomVersions datanucleus-core
org.datanucleus:datanucleus-core:3.0.4
[/sourcecode]

and then I proide the new version as a second argument:

[sourcecode language="bash"]
$ pomVersions datanucleus-core 3.0.7
org.datanucleus:datanucleus-core:3.0.7
[/sourcecode]

pom.xml is already modified accordingly. Here is the best part, the source code:

[sourcecode language="groovy"]
!/usr/bin/groovy

import groovy.xml.XmlUtil

def matchAndModify(String search, String version) {
def pom = new XmlSlurper(false, false).parse(‘pom.xml’)
pom.dependencies.dependency.each { dep ->
if (dep.groupId.text() =~ /${search}/ || dep.artifactId.text() =~ /${search}/) {
if (version) {
dep.version = version
}
println "${dep.groupId}:${dep.artifactId}:${dep.version}"
}
}
return pom
}

boolean checkArgs() {
if (!(1..2).contains(args.size())) {
println ‘pomVersions: update the version of a dependency in Maven\’s pom.xml’
println "\nUsage: "
println ‘with 1 argument, look for the string specified and print matching dependencies’
println ‘with 2 arguments, look for the string specified and set the second string as version’
println "\nExample: pomVersions datanucleus-core -> list the matching dependency"
println ‘Example: pomVersions datanucleus 3.0.6 -> update all matching dependencies’
println ‘More Examples: http://www.stefanolocati.it/blog/?p=1220′
return false;
}
return true;
}

String grabArgIfExists(int position) {
if (position < args.size()) {
return args[position]
}
return ”
}

if (checkArgs()) {
String search = grabArgIfExists(0)
String version = grabArgIfExists(1)
def pom = matchAndModify(search, version)
File file = new File(‘pom.xml’)
file.write XmlUtil.serialize(pom)
}
[/sourcecode]

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">