How to add generated sources to compile classpath without adding them to the main sourceSet?

You can add an exclude rule to your

tasks.withType(Checkstyle) {
  source = sourceSets.main.allJava.matching {
    exclude '**/generated-src/**/*'
  }
}

This works well except if you treat Java warnings as errors, as often generated code has issues due to Java version skew (1.6 / 1.7). In that case you’ll want to use a custom sourceset so that the generated code has its own compile task that is configured to allow warnings. You can then make the generated code a dependency for the main sourceset.

Below is a template of steps that I’ve repeated a few times for code generation and custom sourcesets. I’m sure there’s a few unnecessary bits from debugging that could be trimmed.

configurations {
  codeGen
}
  sourceSets {
  codeGen {
    java.srcDir "${buildDir}/generated-src/"
  }
  main {
    runtimeClasspath += sourceSets.codeGen.output
  }
}
  compileCodeGenJava.options.compilerArgs = []
compileJava.dependsOn(compileCodeGenJava)
compileCodeGenJava.dependsOn(generateSources)
  dependencies {
  compile project(path: project.path, configuration: "codeGen")
  compile project(path: project.path, configuration: "codeGenCompile")
}
  project.afterEvaluate {
  dependencies {
    configurations.codeGen.allDependencies.each {
      compile it
      codeGenCompile it
    }
  }
}
  task codeGenJar(type: Jar, dependsOn: codeGenClasses, group: "Build",
    description: "Assembles a jar archive containing the generated classes.") {
  from sourceSets.codeGen.output
    afterEvaluate {
    baseName = "${baseName}.generated"
  }
}
  artifacts {
  codeGen codeGenJar
}
3 Likes