How to create RegularFileProperty from a string or classpath resource?

Viewed 1175

I'm creating a Gradle plugin that configures another Gradle plugin. One piece of configuration is to provide RegularFileProperty instance. How can I create instance of such interface if I just have String object in hand? Or a resource bundled with my plugin?

With TextResource I was doing it by resources.text.fromString(...) or

        project.with {
            resources.text.fromString(buildscript.classLoader.getResource(resourceName).text)
        }

What would be equivalent snippet to create a RegularFileProperty? If the only way is by a temporary file, how and where should I create it?

3 Answers

A RegularFileProperty is a type of provider that allows you to lazily provide a value of type RegularFile. So I think you might not be asking how to create a provider, but rather how to configure it with a RegularFile.

A RegularFile represents a fixed file on the file system. So if all you have is content for the file, you need to save it as a file somewhere - preferably somewhere in the build folder.

You can configure the provider with a new value through the setter method. There are currently not so many ways to get an instance of RegularFile, but usually you get it via various methods on a ProjectLayout:

myRegularFileProvider.set(project.layout.buildDirectory.file("myFile.txt"))

I've ended up creating a temporary file and it works for me.

    def file = File.createTempFile("config", ".xml")
    file.write '<config/>'
    extension.myRegularFileProperty.set(file)

Here is how I reference a file that is packaged within the jar of my custom Gradle plugin. I have a common test-rules.xml config for SpotBugs I want to be applied to any project applying my plugin.

String spotBugsTestRules = getClass().getResourceAsStream("config/spotbugs/test-rules.xml").text
File spotBugsTestRulesFile = File.createTempFile("test-rules", ".xml")
spotBugsTestRulesFile.write(spotBugsTestRules)

project.tasks.matching {
    it.name.startsWith('spotbugs') && it.name.endsWith('Test')
}.all {
    it.includeFilter = spotBugsTestRulesFile
}

This code reads the resource file into a String and then outputs it back as a temp file. This is because the includeFilter property is a RegularFilePropery and needs to be pointing to an actual file on the file system.

Related