Error compiling a Groovy project using @Grab annotation
Asked Answered
S

2

21

I'm compiling a Groovy project with Gradle, but I've noticed that when I use the @Grab annotation in my code, I get the following error:

$ gradle compile
:buildInfo
:compileJava UP-TO-DATE
:compileGroovy FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileGroovy'.
> org/apache/ivy/core/report/ResolveReport

(full stack trace here http://pastebin.com/0ty4jNct)

I've found out that the only way to get it working is to add the 'groovy' and 'ivy' module to the groovy classpath, but I would like to avoid this, since the groovy classpath is deprecated.

Is this a Gradle bug? or there's a better way to manage the @Grab dependency?

Subtreasury answered 11/8, 2013 at 16:5 Comment(0)
K
38

@Grab is meant to be used for standalone scripts that aren't precompiled, and you wouldn't normally use it together with compiled code. If you do, you may have to add Ivy to groovyClasspath. Something like:

repositories {
    mavenCentral()
}

configurations {
    ivy
}

dependencies {
    ivy "org.apache.ivy:ivy:2.3.0"
    compile "org.codehaus.groovy:groovy-all:2.1.5"
}  

tasks.withType(GroovyCompile) {
    groovyClasspath += configurations.ivy
}

That said, a better approach is to manage dependencies with Gradle.

Kraigkrait answered 11/8, 2013 at 16:16 Comment(3)
Hi, I think you mean: configurations { ivy } and use it in the dependencies block, but it returns Cannot infer Groovy class path because no Groovy Jar was found on class path: configuration ':compile'Subtreasury
Right. And of course you'll have to declare a Groovy dependency.Kraigkrait
Is it possible to have a Groovy "script" that can be ran both standalone (with @Grab) as well as in Maven context?Ctn
T
5

The accepted solution worked for me at compile-time, but I still had similar issues at runtime. The following worked for me by excluding the grape code from the compile altogether:

compileGroovy {
  groovyOptions.configurationScript = file("gradle/config.groovy")
}

... where gradle/config.groovy is a separate file, contents of which were:

withConfig(configuration) {
  configuration.setDisabledGlobalASTTransformations(['groovy.grape.GrabAnnotationTransformation'] as Set)
}
Toluca answered 19/12, 2016 at 21:15 Comment(1)
It looks like Gradle 7.4 added an option for disabling AST transformations without the file - compileGroovy.disabledGlobalASTTransformations. The default value is ["groovy.grape.GrabAnnotationTransformation"] which would then be disabled. So, if you use @Grab in your code, you would then add a compile dependency for it to work in Gradle then at runtime it would "grab" the dependency, so you get both to work.Pskov

© 2022 - 2024 — McMap. All rights reserved.