Joe Fernandez
Joe Fernandez

Reputation: 4811

How do I define a filtered FileTree using Gradle's Java API?

I am building a Gradle plugin in Java because of some Java libraries I want to take advantage of. As part of the plugin, I need to list and process folders of files. I can find many examples of how to do this in gradle build files:

  FileTree tree = fileTree(dir: stagingDirName)
  tree.include '**/*.md'
  tree.each {File file ->
    compileThis(file)
  }

But how would do I do this in Java using Gradle's Java api?

The underlying FileTree Java class has very flexible input parameters, which makes it very powerful, but it's devilishly difficult to figure out what kind of input will actually work.

Upvotes: 2

Views: 1178

Answers (2)

Joe Fernandez
Joe Fernandez

Reputation: 4811

Here's how I did this in my java-based gradle task:

public class MyPluginTask extends DefaultTask {

    @TaskAction
    public void action() throws Exception {

        // sourceDir can be a string or a File
        File sourceDir = new File(getProject().getProjectDir(), "src/main/html");
        // or:
        //String sourceDir = "src/main/html";

        ConfigurableFileTree cft = getProject().fileTree(sourceDir);
        cft.include("**/*.html");

        // Make sure we have some input. If not, throw an exception.
        if (cft.isEmpty()) {
            // Nothing to process. Input settings are probably bad. Warn user.
            throw new Exception("Error: No processable files found in sourceDir: " +
                    sourceDir.getPath() );
        }

        Iterator<File> it = cft.iterator();
        while (it.hasNext()){
            File f = it.next();
            System.out.println("File: "+f.getPath()"
        }
    }

}

Upvotes: 1

Peter Niederwieser
Peter Niederwieser

Reputation: 123986

It's virtually the same, e.g. project.fileTree(someMap). There's even an overload of the fileTree method that takes just the base dir (instead of a map). Instead of each you can use a for-each loop, instead of closures you can typically use anonymous inner classes implementing the Action interface (although fileTree seems to be missing these method overloads). The Gradle Build Language Reference has the details. PS: You can also take advantage of Java libraries from Groovy.

Upvotes: 0

Related Questions