3

I am using codenarc 1.4 with gradle to test groovy code in a Jenkins shared library, but when running it outputs errors saying it was unable to resolve groovy.lang.Closure though this doesn't seem to prevent the checks being run.

An example of the code that's hitting the problem is

interface IStepExecutor {
    int sh(String command)
    void dir(String path, Closure commands)
    ...

when codenarc is run the following error is produced:

file:/.../IStepExecutor.groovy: 8: unable to resolve class Closure 
 @ line 8, column 27.
       void dir(String path, Closure commands)
                             ^

The codenarc parts of my gradle config is as follows:

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.5.7'
    testCompile "org.spockframework:spock-core:1.3-groovy-2.5"
}
codenarc {
    toolVersion = "1.4"
}
codenarcMain {
    configFile = file("config/codenarc/CodeNarcMain.groovy")
    source = 'src'
    compilationClasspath += files('src/')
}
codenarcTest {
    configFile = file("config/codenarc/CodeNarcMain.groovy")
    source = 'src'
    compilationClasspath += files('src/')
}

I can stop the error messages by adding an import groovy.lang.Closure but that causes the UnnecessaryGroovyImport rule to error. Is there a way to prevent these errors being reported without removing the UnnecessaryGroovyImport rule?

user1013341
  • 336
  • 1
  • 9
  • seems you missed to add groovy-all library into classpath – daggett Jan 10 '20 at 18:49
  • Do you know how that should be done with gradle? None of the examples I saw had anything adding groovy-all to the classpath. I have it as a compile dependency and I cant add dependancies for the `codenarcMain` task. – user1013341 Jan 13 '20 at 18:47

1 Answers1

8

I'm also using CodeNarc with Gradle for Jenkins shared library tests and found adding the following to my Gradle configuration fixed a similar issue:

codenarcMain {
    compilationClasspath = sourceSets.main.compileClasspath + sourceSets.main.output
}

codenarcTest {
    compilationClasspath = codenarcMain.compilationClasspath + sourceSets.test.compileClasspath + sourceSets.test.output
}

I found this in a comment on a CodeNarc issue on GitHub.

I think the problem is something to do with each file being compiled in isolation for static analysis which is different from the normal compilation steps in Gradle. I'm very new to this though so maybe misunderstanding it.

fun4jimmy
  • 672
  • 4
  • 16