robbie70
robbie70

Reputation: 1615

gradle could not find other gradle script

/--common
/--common/build.gradle
/--common/deploy.gradle
/--project1
/--project1/build.gradle

I have a multi-project structure and have extracted repeating code from my build.gradle file and placed this into another file deploy.gradle.

I have placed the deploy.gradle file into the common project at the same folder level as the build.gradle file. The folder structure is shown above.

In the build.gradle file of the common project I can reference the file using the statement,

apply from: 'deploy.gradle'

This works like a dream and the common project build works perfectly calling in the tasks from the deploy.gradle file.

The problem comes when I try to reference deploy.gradle file from one of the other projects. When I add the apply... statement to the build.gradle of project1 I get the compilation error,

Error:(23, 0) Could not read script 'C:\path-to-project1-script-file\deploy.gradle' as it does not exist.

So Gradle is looking for the deploy.gradle file in project1 only even though I have a dependency set to the common project in the project1 build.gradle file.

Question is how can I make deploy.gradle from common project visible to project1.

Upvotes: 4

Views: 5580

Answers (2)

Frank Neblung
Frank Neblung

Reputation: 3165

We successfully use the following project layout

├── a
│   └── build.gradle
├── b
│   └── build.gradle
├── build.gradle
├── gradle-scripts
│   └── deploy.gradle
└── settings.gradle

The rootproject's build.gradle defines

ext.gradleScript = { scriptName ->
    file("${rootProject.projectDir}/gradle-scripts/${scriptName}.gradle")
}

Subprojects use the scripts within gradle-scripts this way

apply from: gradleScript('deploy')

Whole content of the project:

$> find . -type f | while read file; do echo "--- $file ---" && cat $file; done
--- ./a/build.gradle ---
apply from: gradleScript('deploy')
--- ./b/build.gradle ---
apply from: gradleScript('deploy')
--- ./build.gradle ---
// Where common build logic is found
ext.gradleScript = { scriptName ->
    file("${rootProject.projectDir}/gradle-scripts/${scriptName}.gradle")
}
--- ./gradle-scripts/deploy.gradle ---
task myDeployTask {
    doLast { println 'common deploy logic goes here' }
}
--- ./settings.gradle ---
include 'a', 'b'

$> gradle -q b:myDeployTask
common deploy logic goes here
$>

Upvotes: 5

Michael Easter
Michael Easter

Reputation: 24468

Here is an example project1/build.gradle that references common/deploy.gradle:

// import myDeploy task
apply from: "${rootDir}/common/deploy.gradle"

task myProject1Task(dependsOn: 'myDeploy') {
    doLast {
        println 'TRACER myProject1Task'
    }
}

It is often important to distinguish projectDir from rootDir in multi-project builds. projectDir is the specific subproject; rootDir is where settings.gradle lives.

Upvotes: 2

Related Questions