Search code examples
intellij-ideagroovyclasspathgroovydsl

Modify GroovyDSL classpath to include 3rd party libraries


I'm trying to create a GroovyDSL script which references some external libraries. Here's my script:

import com.github.javaparser.ast.Node
import org.reflections.Reflections

def ctx = context(
        ctype: 'groovy.util.ObjectGraphBuilder',
        paths: ['com/example/scripts/.*'],
        filetypes: ["groovy"]
)

Map<String, Class> candidateClasses = new Reflections(Node.packageName).getSubTypesOf(Node)
        .collectEntries { Class type -> [(type.simpleName.uncapitalize()): type] }

contributor(ctx) {
    candidateClasses.each { String methodName, Class type ->
        method name: methodName, params: [props: "java.util.Map", closure: "groovy.lang.Closure"], type: type.name
    }
}

Trying to enable it in Intellij, I'm getting:

startup failed: transformDslSyntaxgdsl: 1: unable to resolve class com.github.javaparser.ast.Node

@ line 1, column 1.

import com.github.javaparser.ast.Node

Now, I have the proper external dependencies declared in pom.xml, the rest of the code that depends on them is working just fine. I've also put the script inside a source folder (which some other answers here suggested might be relevant).

I have seen some examples for GDSL reference Intellij types like PsiClass, which tells me the classpath for GDSL files seems to be different from the project classpath. Is there any way to make sure project dependencies are appended to that classpath?

I also tried using @Grape only to get this error. Adding Apache Ivy as a dependency doesn't help, because again, project dependencies don't seem to influence the GDSL classpath.


Solution

  • After a bit more digging, I found that it is pretty easy to modify the IDE's classpath itself.

    All you need to do is to drop a dependency into Intellij installation directory's lib subfolder, and reference the jar inside classpath.txt.

    Initially, I added the jars my GDSL depends on directly, but then I realized I could simply add a dependency on Apache Ivy to classpath.txt instead and @Grab annotations would start working.