Wednesday, August 18, 2010

Cleaning up after maven-eclipse-plugin

There are a few of us out there who are in situations where we cannot use the m2eclipse plugin to run our Maven based projects without pain. To resolve that pain there's the maven-eclipse-plugin.

Unfortunately, the current version of the plugin has a bug which causes an in issue where duplicate facet entries are placed in the org.eclipse.wst.common.project.facet.core.xml file.

As an example:

<fixed facet=""/>
<fixed facet="jst.utility"/>
<installed facet="jst.utility" version="1.0"/>
<installed facet="" version="5.0"/>
<installed facet="" version="5.0"/>
<installed facet="jst.utility" version="1.0"/>

How to solve this problem? A convient excuse to try out some Groovy and the GMaven plugin. Fortunately, Groovy is pretty good at modifying XML, and GMaven is pretty good at playing within the maven pom.

Here's the Groovy script:

if (project.packaging != 'pom') {
def facetXml = new File(project.basedir, '.settings/org.eclipse.wst.common.project.facet.core.xml')
def facets = new XmlParser().parse(facetXml)
def facetSet = [] as Set'Loaded Eclipse Facet XML')
facets.installed.each {
if (! facetSet.add(it.'@facet')) {
it.parent().remove(it)'Removed ' + it.'@facet')
} else {'Put in ' + it.'@facet')
}'backup old XML')
new File(project.basedir, '.settings/org.eclipse.wst.common.project.facet.core.xml.bkp').delete()
facetXml.renameTo(new File(project.basedir, '.settings/org.eclipse.wst.common.project.facet.core.xml.bkp'))'writing items')
def newFacetXml = new File(project.basedir, '.settings/org.eclipse.wst.common.project.facet.core.xml')

new XmlNodePrinter().print(facets)

PrintWriter pw = new PrintWriter(newFacetXml)
xmlNodePrinter = new XmlNodePrinter(pw)

I'm sure there's some code golf you could play to shorten this up, but it does the trick. When you run it, the two extra entries in the file are gone, and a harmless backup file is left behind.