How to provide a sourceset to a custom scalacompile task


(kevin.stembridge.dev) #1

I’m writing a plugin that needs to compile scala classes that are in a non-default location. This has to happen before the main compile phase of the build lifecycle, so I can’t just change the src dir of the standard scala plugin.

I can’t figure out how to specify a source set.

This is the task class of my plugin:

class MyTask extends DefaultTask {
      @TaskAction
    def doIt() {
          def compileScalaTask = new ScalaCompile()
        compileScalaTask.setSource(project.mytask.sourceSet)
        compileScalaTask.execute()
        ...
              }
          }

and this is my attempt at the extension class, which is obviously wrong:

class MyExtension {
      def ScalaSourceSet mySourceSet
          def MyExtension(Project project) {
        mySourceSet = new ScalaSourceSet().scala {
            srcDir: project.file('src/main/myscala')
        }
    }
      }

(Peter Niederwieser) #2

Can you explain the bigger problem, and also what exactly you mean by “This has to happen before the main compile phase of the build lifecycle”?


(kevin.stembridge.dev) #3

Hi Peter, The plugin is a code generator. Previously, it was reading an xml descriptor that determined the code to be generated. The plugin was invoked like so:

compileScala.dependsOn generateModel

Now, I want the descriptor to be a Scala class. This class will have to be compiled first so that the code generator can read it and generate the code before running the standard compileScala task.

I’m pretty sure I can achieve this if I can just figure out how to programmatically configure a ScalaCompile task with the right src directory.


(Peter Niederwieser) #4

Either add a source set, in which case you get another ‘ScalaCompile’ task for free, or do ‘compileScala.source(“path/to/dir”)’.

PS: A task should never execute other tasks. Configuring tasks is the responsibility of plugins.


(kevin.stembridge.dev) #5

I’m afraid I don’t really understand your answer. Based on your response, it seems as though you may have assumed that I want to specify an extra source set in a build script. ie. from the point of view of the user of the plugin.

To clarify, I’m creating a plugin that needs to execute a scala compile task on a given source directory. That directory will not be the standard scala src dir. I want it to default to ‘src/main/modelgen’, but it should be overridable by users of the plugin. The plugin will then generate source code in ‘build/generated-src/scala/main’ by default, or some other location that the user may configure.

Sorry if I’ve misunderstood your answer. Perhaps you could show some snippets of what I need to do in my plugin extension and task classes.


(Peter Niederwieser) #6

Your plugin needs to declare a source set, same way as a build script would. Exact same syntax, except that it’s ‘project.sourceSets’ instead of ‘sourceSets’.