Adding dependencies to a configuration created from a custom source set

How can one programmatically add dependency to a configuration created from a custom source set? The configuration object gets created, but then when trying to add dependency it complains:

task t3 << {
  project.apply(plugin:'java-base')

  def sourceSet1 = project.sourceSets.create('sourceSet1')
  def compile1 = configurations.getByName(sourceSet1.compileConfigurationName)

  println "My configuration: " + compile1

  dependencies {
     compile1 files('xxx', 'yyy')
  }
}

This is producing the following error:

$ gradle t3 
:t3
My configuration: configuration ':sourceSet1Compile'
:t3 FAILED

FAILURE: Build failed with an exception.

* Where:
Build file '/Users/user/code/intellij/Proj1/build.gradle' line: 256

* What went wrong:
Execution failed for task ':t3'.
> Could not find method call() for arguments [file collection] on configuration ':sourceSet1Compile'.

On the other hand, for explicitly created configurations, it works normally:

configurations { compile2 }
dependencies {
    compile2 files('xxx', 'yyy')
}

The following works:

dependencies.add(compile1.name, files('xxx', 'yyy'))

Just a few notes…

task t3 << {
  project.apply(plugin:'java-base')

This is applying a plug-in during the “execution” lifecycle. I’m surprised this works, but it’s going to cause problems if you leave it like this. All of this configuration should be done outside a task block.

  def compile1 = configurations.getByName(sourceSet1.compileConfigurationName)
  dependencies {
     compile1 files('xxx', 'yyy')
  }

The error you’re getting takes a little explaining of what Groovy’s doing here in the “normal” case. dependencies is really a DependencyHandler. When you say compile1 files(...), Groovy looks for a method called “compile1” on DependencyHandler. When it doesn’t find one, it calls methodMissing() passing “compile1” and the arguments. We’ve implemented methodMissing() to look for configurations with the missing method name and add dependencies to it (basically doing exactly what you found that works). So you can’t assign a configuration name to a variable and get the same behavior. We’ll look for a configuration with the variable’s name and not the value of the variable.

We’re doing something similar to what you’re trying in one of the samples:

We’re just relying on the convention that new source sets create configurations with the names "sourceSet"Compile/Runtime.