需求
我们这个task就是修改配置文件并保存,我们将使用自己定义的task来实现这个需求
定义Task类
继续沿用我们之前定义的类MyTag, 并加入了一个新的变量release
class MyTag {
String prefix;
String postfix;
Boolean release;
MyTag(String prefix, String postfix, Boolean release) {
this.prefix = prefix
this.postfix = postfix
this.release = release
}
@Override
String toString() {
return "MyTag{" +
"prefix='" + prefix + '\'' +
", postfix='" + postfix + '\'' +
", release=" + release +
'}';
}
}
要点:
- 自定义的task继承 DefaultTask
- 使用@input和@OutputFile定义taks 输入输出
- 更多示例可以参考: https://docs.gradle.org/current/userguide/custom_tasks.html
class ReleaseVersionTask extends DefaultTask {
@Input
Boolean release
@OutputFile
File destFile
ReleaseVersionTask() {
this.group = "versioning"
this.description = "Release Version Class"
}
@TaskAction
void start() {
println "do task action ... ..."
project.ext.myNewTag.release = true;
Properties properties = new Properties()
project.ext.myTagFile.withInputStream {
stream -> properties.load(stream)
}
println properties.prefix.toString()
properties.setProperty('prefix', 'releaseVersion-prefix')
properties.setProperty('postfix', 'releaseVersion-postfix')
properties.setProperty('release', 'true')
println properties.prefix.toString()
project.ext.myTagFile.withWriter {
properties.store(it, null)
}
}
定义Task
task makeReleaseVersion(type: ReleaseVersionTask) {
release = project.ext.myNewTag.release
destFile = myTagFile
}
执行
我们现在的配置文件mytag.properies内容为
release=true
prefix=heng
postfix=ha
然后执行我们的自己的task
//gradlew makeReleaseVersion
//得到结果:
> Task :makeReleaseVersion
do task action ... ...
heng
releaseVersion-prefix
再次查看我们的配置,也得到了修改.