Eclipse .project
and .classpath
files are XML files, and you can hook into
sbteclipse's generation process by using the classpathTransformerFactories
and projectTransformerFactories
setting keys.
(The following Scala samples should be inside your project's Build.scala
file, or a plugin)
Let's say we want to add the com.example.nature
nature to our project. The
Eclipse project file has an element called <natures>
, under which each nature
is listed. For example, here is what sbteclipse will generate out of the box :
<natures>
<nature>org.scala-ide.sdt.core.scalanature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
Now, you want to insert this Node
inside the <natures>
tag :
val to_insert = <nature>com.example.nature</nature>
Let's create an XML rewrite rule for that :
import scala.xml.{Node, Elem}
import scala.xml.transform.RewriteRule
object MyExampleRule extends RewriteRule {
override def transform(parent: Node): Seq[Node] = {
parent match {
// Match the <natures> tag, store the children inside `children`, and
// return a new tag with the new nature.
case <natures>{children @ _*}</natures> =>
<natures>{children ++ Seq(to_insert): _*}</natures>
// For all other parent tags, do nothing
case other => other
}
}
}
Then, wrap it inside a transformer factory to use it within sbteclipse :
import scalaz.Scalaz._
import com.typesafe.sbteclipse.plugin.EclipsePlugin.EclipseTransformerFactory
import com.typesafe.sbteclipse.core.Validation
object MyExampleTransformer extends EclipseTransformerFactory[RewriteRule] {
override def createTransformer(
ref: Project,
state: State): Validation[RewriteRule] = {
// `success` is a method of the Validation object
MyExampleRule.success
}
}
Finally, you're done, add it inside the projectTransformerFactories
key :
EclipseKeys.projectTransformerFactories := Seq(MyExampleTransformer)
The .classpath
XML files can be modified with the same method. The
transformer factories are to be added to the classpathTransformerFactories
key.
Looks very good. Your
MyExampleRule
doesn't compile (under Scala 2.10), though, and it can be simplified:In addition, let's make the
MyExampleTransformer
code more concise: