Kapil Malhotra
Kapil Malhotra

Reputation: 135

Weird behaviour of a simple gradle copy task

I am completely baffled by the gradle behaviour of a Copy task into multiple directories.

I intend to copy all files from src/common into

Below is how my build.gradle looks:

project.ext.dirs = ["dir1", "dir2", "dir3"]

// ensures that ps_modules directory is created before copying
def ensurePsModulesDir() {
  dirs.each {
    def psModules = file("target/$it/ps_modules")
    if (!(psModules.exists())) {
      println("Creating ps_modules directory $psModules as it doesn't exist yet")
      mkdir psModules
    }
  }
}

task copyCommons(type: Copy) {
  doFirst {
    ensurePsModulesDir()
  }

  from("src/common")
  dirs.each {
    into "target/$it/ps_modules"
  }
}

The result of running the command ./gradlew copyCommons is completely weird.

The folder creation works as expected, however, the contents/files are copied only in the target/dir3/ps_modules directory. The rest two directories remain empty.

Any help would be appreciated.

Below is the screen grab of target directory tree once the job is run:

enter image description here

Upvotes: 2

Views: 3552

Answers (2)

lance-java
lance-java

Reputation: 28099

I think you want to do something like:

task copyCommons(type: Copy) {
    dirs.each {
        with copySpec {
            from "src/common"
            into "target/$it/ps_modules"
        }
    }
}

I think you can get rid of the ensurePsModulesDir() with this change

* edit *

it seems that the copy task is forcing us to set a destination dir. You might think that setting destinationDir = '.' is ok but it's used in up-to-date checking so likely the task will NEVER be considered up-to-date so will always run. I suggest you use project.copy(...) instead of a Copy task. Eg

task copyCommons {
   // setup inputs and outputs manually 
   inputs.dir "src/common"
   dirs.each {
       outputs.dir "target/$it/ps_modules"
   }

   doLast {
       dirs.each { dir ->
           project.copy {
               from  "src/common"
               into "target/$dir/ps_modules"
           } 
       }
   }
}

Upvotes: 1

Opal
Opal

Reputation: 84874

You can configure a single into for a task of type Copy. In this particular example gradle behaves as expected. Since dir3 is the last element on the list it is finally configured as a destination. Please have a look at this question - which you can find helpful. Also this thread might be helpful as well.

Upvotes: 0

Related Questions