Gradle Copy task for list of files

I wanted to copy files from src/main/resources to a build directory.
Basically, I wanted to “copy” files 3 times (because my envList has 3 files). I could do it with below code. But its bad that I’m registering the task every time I copy, so here 3 times I register copy task I’m looping copy task which is odd.


var envList = mutableListOf("foo.yaml", "bar.yaml", "sample.yaml")

envList.indices.forEach { index ->
    tasks.register<Copy>("package") {
        parsedFileList[index].forEach {
            it.value.forEach { filePath ->
                fileTree(file("src/main/resources")).visit {
                    if (this.path.endsWith(".json") && this.toString().contains(filePath)) {
                        from(layout.buildDirectory.dir("resources/main/"))
                        include(this.path)
                        into(layout.buildDirectory.dir("deployment/${envList[index]}"))
                    }
                }
            }
        }
    }
}

Is there any way that I can just register copy only once and copy files for all the envList?

Any Suggestions?

I don’t understand exactly the details of what you are trying to do, and I don’t know what parsedFileList contains, but you don’t need to create 3 copy tasks. Project contains a copy {} directive that can allow you to accomplish the same thing imperatively as many times as you like without making a Copy task for each one.

tasks.register("customCopyTask") {
    doFirst {
        copy {
            from("src/main/resources")
            filesMatching {
                <conditons for files to take>
            }
            into(layout.buildDirectory.dir("deployment/${destination dir name"))
        }
        copy {
        }
        copy {
        }
    }
}

Depending on what you need to do, you could loop over the copy {} directive.

With more details of what you are working with and trying to do exactly, I could give a better answer, but this above is the general idea of how to do multiple copies in one task execution.