给出以下Gradle-Task / Plugin-Combination
apply plugin: GreetingPlugin
class GreetingPlugin implements Plugin<Project> {
void apply(Project project) {
project.extensions.create("greeting", GreetingPluginExtension)
def task = project.task('hello', type: GreetigTask)
//don't know how/when to populate task-properties with extension-values here.
//this does NOT work... properites don't get populated
task.message = {project.greeting.message}
task.greeter = {project.greeting.greeter}
}
}
class GreetingPluginExtension {
String message
String greeter
}
class GreetigTask extends DefaultTask {
def message
def greeter
@TaskAction
def greet() {
println "${message} from ${greeter}"
}
}
greeting {
message = 'Hi'
greeter = 'Gradle'
}
task helloDirect(type: GreetigTask) {
message = "howdy"
greeter = "direct task"
}
我想为用户提供一个插件,用户可以通过两种不同的方式使用GreetingTask
。
第一路
使用GreetingPluginExtension
配置插件提供的任务hello
,其配置块如下:
greeting {
message = 'Hi'
greeter = 'Gradle'
}
第二路
让用户明确定义/创建任务并在任务定义中设置所需的值,如下所示:
task helloDirect(type: GreetigTask) {
message = "howdy"
greeter = "direct task"
}
我刚刚发现我可以直接从message
- 对象使用greeter
和GreetingTask
属性来打印问候语或更改要使用的任务操作{{1 }}
如何获得更大的灵活性?我希望我的用户可以选择使用它们。
答案 0 :(得分:0)
看起来我已找到一种方式来实现我想要的......
下面只是我已经改变的部分。问题是,我不知道这是否是实现我想要的gradle-way(tm),因为conventionMappings
似乎是使用gradle的旧的/弃用的方式。请参阅:Gradle plugin: Convention vs. Extension和How do you use a conventionMapping to do the following?(通过SO:Correct way to define a Gradle plugin property extension with Java?)
有人有更好的建议吗?或者这是最好的方法吗?
conventionMappings
似乎没有记录得很好。
class GreetingPlugin implements Plugin<Project> {
void apply(Project project) {
project.extensions.create("greeting", GreetingPluginExtension)
def task = project.task('hello', type: GreetigTask)
//using conventionMapping here
task.conventionMapping.message = {project.greeting.message}
task.conventionMapping.greeter = {project.greeting.greeter}
}
}
class GreetigTask extends DefaultTask {
def message
def greeter
@TaskAction
def greet() {
//excplicitly calling getters and setters here.
//conventionMapping-properties seem to be evaluated before class properties
println "${getMessage()} from ${getGreeter()}"
}
}