Master_T
Master_T

Reputation: 8007

Gradle: create a task that runs after the "build" task

This seems like a pretty simple thing to do, but I tried countless examples I found online and they all fail in some different way, which means I'm probably just not getting the concept of how tasks work in gradle (sorry, it's still very new to me).

What I'm trying to do is this: I have a multi-project gradle solution which has several java sub-projects. For each of these sub-projects I want to create a task that will:

  1. Build the project
  2. Copy the generated jar file to a different directory

This is as far as I got (it might just be missing some little thing or it might be a completely incorrect approach, I hope someone will explain it to me): in my root build.gradle I've put this:

subprojects{
    plugins.withType(JavaPlugin){ //create copyOutput task for all java projects
        tasks.create("copyOutput"){
            Path infile = Paths.get(buildDir.getCanonicalPath() + "/libs/" + project.name + ".jar")
            Path outfile = Paths.get(rootProject.projectDir.getCanonicalPath() + "/bin/" + project.name + ".jar")
            Files.copy(infile, outfile, REPLACE_EXISTING)
        }
        tasks['copyOutput'].dependsOn tasks['build'] //only run after build (doesn't work, runs immediately at configuration time)
    }
}

The problem with this, from what I can gather by the stack traces I'm getting, is that it executes the task immediately at configuration time, and every time (not just when I do gradle copyOutput, but always, even if I do something like gradle clean).

Evidently I'm not understanding how task creation and dependency work. Can anyone clarify?

Upvotes: 2

Views: 1126

Answers (1)

Opal
Opal

Reputation: 84884

You need to add an action (<<):

subprojects{
    plugins.withType(JavaPlugin){ //create copyOutput task for all java projects
        tasks.create("copyOutput") << {
            Path infile = Paths.get(buildDir.getCanonicalPath() + "/libs/" + project.name + ".jar")
            Path outfile = Paths.get(rootProject.projectDir.getCanonicalPath() + "/bin/" + project.name + ".jar")
            Files.copy(infile, outfile, REPLACE_EXISTING)
        }
        tasks['copyOutput'].dependsOn tasks['build'] //only run after build (doesn't work, runs immediately at configuration time)
    }
}

Upvotes: 2

Related Questions