How to use Sync task's from method with closures in Java code?


(jai) #1

Hi,

I want to write a java plugin with a task very similar to this one (found here):

task extractApi(type: Sync) {
    dependsOn configurations.api

    from { // use of closure defers evaluation until execution time
        configurations.api.collect { zipTree(it) }
    }
    into "$buildDir/api/"
}

Ultimately I want to do what the comment says: defer dependency evaluation until execution time. But I struggle to find the right syntax to transfer the groovy code to java code. I want to pass a closure as a parameter to the from method, but so far I failed. Infact, looking at the api, there doesn’t even seem to be a method that takes just a closure? But the groovy task works anyways.

Here’s my what I got so far:

//Configuration conf = ...
//Project p = ...
p.getTasks().register("extract" + capitalizedConfName, Sync.class, t -> {        
    t.dependsOn(conf);
    for(File dep : conf) {
        t.from( dummy -> { //doesn't work, syntax error!!
            return p.zipTree(dep);
        });
    }
    t.into(p.getBuildDir().getAbsolutePath() + "/extracted/");
});

Thanks for your help!


(Chris Doré) #2

I didn’t test it, but you could try something like:

//Configuration conf = ...
//Project p = ...
p.getTasks().register("extract" + capitalizedConfName, Sync.class, t -> {        
    t.dependsOn(conf);
    t.from( (Callable<Collection<FileTree>>) () -> {
        List<FileTree> trees = new ArrayList<FileTree>();
        for( File dep : conf ) {
            trees.add( project.zipTree( dep ));
        }
        return trees;
    } );
    t.into(p.getBuildDir().getAbsolutePath() + "/extracted/");
});