Add custom configuration to installDist for a specific task

I’m trying to make a custom runtime dependency configuration, so that the specified dependencies will only be installed for a specific task. The dependencies are installed using the installDist task. So it seems like I need the configuration to be added to the runtimeClasspath for one task and not the other. I’m thinking I need a custom distribution, but I’m not sure how to set that to have a different runtimeClasspath from the default.

In the example below, I want the run2 task to have the myRuntimeDep dependencies installed, but for the run1 task I do not.

I’ve be struggling to figure this out all day, does someone know what I’m missing?

Example build.gradle:

configurations {
    myRuntimeDep.extendsFrom runtimeOnly
}

dependencies {
    ...
    myRuntimeDep 'the:dependency:1.0'
}

task run1(type: JavaExec, dependsOn: installDist) {
   // does not need myRuntimeDep dependencies
}

task run2(type: JavaExec, dependsOn: installDist) {
    // needs myRuntimeDep dependencies
}

So after a long weekend, I sort of got something working. Maybe someone can tell me if there’s a better way? Also, it doesn’t fully work because it doesn’t follow transitive dependencies with the configuration (which is kind of a pain because all sub-dependencies need to be manually added).

Solution:


top-level build.gradle

...
subprojects {
    configurations {
        fooRuntime.extendsFrom runtimeOnly
        fooClasspath.extendsFrom runtimeClasspath, fooRuntime
    }
    
    distributions {
        foo {
            contents {
                from installDist.destinationDir
                from(configurations.fooClasspath) {
                    into 'lib'
                }
            }
        }
    }
    installFooDist.dependsOn installDist
}

project A build.gradle

dependencies {
    fooRuntime project(':projectB')
    fooRuntime project(':projectC') // only need this because transitive dependencies won't work
}

task run(type: JavaExec, dependsOn: installFooDist) {
   classpath = fileTree("$installFooDist.destinationDir/lib")
}

project B build.gradle

dependencies {
    fooRuntime project(':projectC')
}

task run(type: JavaExec, dependsOn: installFooDist) {
   classpath = fileTree("$installFooDist.destinationDir/lib")
}