How to add other project's task as dependincies


(Mike Guo) #1

I need add a dependency of other proejct’task in a sub-project, how can I do this?
My gradle projects structure as below:

| - Core
| - Manager
  | - caseManager
    | -- case1
    | -- case2
    | --  ....

build.gradle in case1:
dependencies {
if(findProject(':Core')) {
    compile project(":Core")
    // need run a task in Core project
}
}

When I do #gradle build under case1 folder, I need run a task in Core project, is there a way to do this?

Thanks.


(uklance) #2

I think you are confusing concepts here. The dependencies { ... } block is evaluated in the configuration phase which is before any tasks have been run. Here’s what I think you want to do

project(':project1') {
    configurations {
      generated
   }
   dependencies {
      generated files({ tasks.getByName('generateFiles') })
   }
   task generateFiles {
      outputs.dir "$buildDir/generateFiles"
      doLast {
         mkdirs "$buildDir/generateFiles"
         file("$buildDir/generateFiles/file1.txt").text = 'foo'
         file("$buildDir/generateFiles/file2.txt").text = 'bar'
      }
   }
}
project('project2') {
   dependencies {
      compile project(path: ':project1', configuration: 'generated')
   }
}

(Mike Guo) #3

Thanks Lance for your replay.

I change the build.gradle file as your suggestion, but build failed.

dependencies {
// build project1 if found locally
if(findProject(':project1')) {
    println "Found project1 locally."
    //add dependency test
    project(':project1 '){
        configurations {
            generated
        }
        dependencies {
            generated files({ tasks.getByName('uploadArchives') })    //the task defined in project1's build.gradle
        }
    }
    //end dependecny test
    compile project(":project1 ", configuration: 'generated')
}

}

I met below error:

Could not find method project() for arguments [{configuration=generated}, :project1 ] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

Could you help to take a look?


(uklance) #4

I’m not sure why you are doing this inside a dependencies { ... } block (which I also think is the cause of your error).

Also unsure why the findProject(...) logic is required since project structure is usually fixed and known at build time


(Mike Guo) #5
  1. I met same error when put it outside dependencies {…} block.

    $ cat Manager/caseManager/case1/build.gradle

     project(':project1'){
         configurations {
         generated
         }
         dependencies {
             generated files({ tasks.getByName('uploadArchives') })
         }
     }
    
     dependencies {
          compile project(":project1", configuration: 'generated')
     }
    
  2. This case need to be run outside the whole project, maybe anywhere, so I need findProject(…) block.