如何从插件扩展中配置DSL样式gradle插件

时间:2015-02-27 09:19:39

标签: gradle

我使用Gradle DSL样式实现了Gradle插件。该插件添加了多个方面,例如添加自定义任务和配置更多其他任务。总的来说,插件在源文件夹中生成一些元数据属性文件,必须由插件扩展名配置。

apply plugin: 'artifactMetadata'
// configure the path for the metadata
artifactMetadata {
    destinationDirectory = "src/main/generated/otherlocation/resources"
}

我已经能够弄清楚如何使用扩展属性配置任务,但是它会使用剩余的东西来欺骗我。配置源集,清理任务和构思插件的好方法是什么(请参阅下面插件代码中的#n:TODO注释)?下面的实现将始终使用默认值,而不是通过插件扩展注入的默认值。

class ArtifactMetadataPlugin implements Plugin<Project> {
    public static final String EXTENSION_NAME = 'artifactMetadata'
    public static final String TASK_NAME = 'generateArtifactMetadata'
    void apply(Project project) {
        createExtension(project)
        project.configure (project) {

            task (TASK_NAME, type: GenerateArtifactMetadata) {
                group = project.group
                artifact = project.name
                version = project.version.toString()
            }

            sourceSets {
                main {
                    // #1:TODO to get the plugin extension property current value here                            output.dir(project.artifactMetadata.destinationDirectory, builtBy: TASK_NAME)
                    resources.srcDirs += file(project.artifactMetadata.destinationDirectory)
                }
            }

            clean {
                // #2:TODO get the plugin extension property here                       
                delete file(project.artifactMetadata.destinationDirectory)
            }

            if (project.plugins.hasPlugin(IdeaPlugin)) {
                idea {
                    module {
                        // #3:TODO get the plugin extension property here                       
                        sourceDirs += file(project.artifactMetadata.destinationDirectory)
                    }
                }
            }
        }
        project.afterEvaluate {
            def extension = project.extensions.findByName(EXTENSION_NAME)
            project.tasks.withType(GenerateArtifactMetadata).all { task ->
                task.destinationDirectory = project.file(extension.destinationDirectory)
            }
        }
    }

    private static void createExtension(Project project) {
        def extension = project.extensions.create(EXTENSION_NAME, ArtifactMetadataPluginExtension)
        extension.with {
            destinationDirectory = "src/main/generated/artifactinfo/resources"
        }
    }
}

0 个答案:

没有答案