Converting a Gradle SourceSet into an Ant fileset

How can I convert a Gradle sourceSet into an Ant fileset? I want to convert sourceSets.main.java into a fileset to send to the PMD Ant task. Here’s what I have, and it almost works…

task pmd << {
    inputs.files(sourceSets.main.java)
    outputs.dir("$buildDirName/pmd")
    file("$buildDirName/pmd").mkdirs()
    ant {
        taskdef(name: 'pmd', classname: 'net.sourceforge.pmd.ant.PMDTask',
                classpath: configurations.pmdConf.asPath)
        pmd(rulesetFiles: 'basic,design,unusedcode', targetjdk: "$sourceCompatibility", shortfilenames: "true") {
            formatter(type: 'xml', toFile: "$buildDirName/pmd/pmd.xml")
        }
    }
    sourceSets.main.java.addToAntBuilder(ant, 'pmd', FileCollection.AntType.FileSet)
}

The error I get back from Gradle is this:

  * What went wrong:  Execution failed for task ':bridge:pmd'.  Cause: pmd doesn't support the "location" attribute  

Normally the pmd task would take a fileset at the same level as its nested formatter.

Haven’t tested this, but it should give you the right idea:

pmd(rulesetFiles: 'basic,design,unusedcode', targetjdk: "$sourceCompatibility", shortfilenames: "true") {
            formatter(type: 'xml', toFile: "$buildDirName/pmd/pmd.xml")
            fileset(dir: projectDir.getPath()) {
              sourceSets.main.java.each { sourceDir ->
                include(name: project.relativePath(sourceDir.getPath()) + '/****/**.java')
              }
            }
        }

That should read “/**/*.java” but the code styling is eating it for some reason…

Actually, that should read “sourceSets.main.java.srcDirs.each { sourceDir ->”

I actually used this, based on your suggestion:

gproj = project
ant {
    taskdef(name: 'pmd', classname: 'net.sourceforge.pmd.ant.PMDTask', classpath: configurations.pmdConf.asPath)
    pmd(rulesetFiles: 'basic,design,unusedcode',
        targetjdk: "$sourceCompatibility", shortfilenames: "true") {
        formatter(type: 'xml', toFile: outDir.path + "/pmd.xml")
        fileset(dir: projectDir.getPath()) {
            sourceSets.main.java.each { file ->
                include(name: gproj.relativePath(file))
            }
        }
    }
}

It turns out that, inside the ant block, “project” resolves to the ant project instead of the gradle project; so I made the gproj variable to reference that.

Chris, just an FYI that I have a PMD plugin available on Maven Central. Info is here: https://github.com/ajoberstar/gradle-plugins

They’re not perfect, but if all you’re trying to do right now is execute PMD, that should get you there.