user3721344
user3721344

Reputation: 221

gradle - copying directory - Issue

I have an issue with copying files in gradle. Here is a snippet of build.gradle:

task mydir() {
    new File("build/models").mkdir()
}

task copyTask(dependsOn:mydir, type: Copy){ 

   from 'src/test/groovy/models'
   into 'build/models'

   from 'src/test/groovy/test.groovy'
   into 'build/'
}

The issue here is in the first copy, that is, test.groovy is copied into build. But the first copy, where I am copying all the files in src/../models into build/models is not working. It simply copies the files into build directory only. My build/models remain empty. Can someone please tell me where what I'm doing wrong? I also have a separate task to create build/models directory prior to copyTask execution.

Upvotes: 10

Views: 13462

Answers (2)

Peter Niederwieser
Peter Niederwieser

Reputation: 123900

The build script contains the following mistakes:

  1. The directory is created when mydir is configured, not when it is executed. (This means the directory will be created on every build invocation, regardless of which tasks get executed.)
  2. new File('some/path') creates a path relative to the current working directory of the Gradle process, not a path relative to the project directory. Always use project.file() instead.
  3. A Copy task can only have a single top-level into.

Here is a corrected version:

task mydir {
    doLast {
        mkdir('build/models')
    }
}

task copyTask(dependsOn: mydir, type: Copy) {
    into 'build'
    from 'src/test/groovy/test.groovy'
    into('models') {
        from 'src/test/groovy/models'
    }
}

The Copy task will create build/models automatically, so there is likely no need to have the mydir task. It's odd to use build as the target directory of a Copy task (should use a subdirectory).

Upvotes: 13

Bill Lin
Bill Lin

Reputation: 1155

In gradle, the copy task could only have single 'into' target with multiple froms.

The second 'into' override the first 'into' value and that's why it's only copied into 'build/' not 'build/models''

You may want to have a separate copy task or use ant.copy instead.

Upvotes: -1

Related Questions