项目构建

Gradle Task 入门 5 定制化task

2020-08-06  本文已影响0人  这个世界是虚拟的

需求

我们这个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 +
                '}';
    }
}

要点:

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

再次查看我们的配置,也得到了修改.

上一篇 下一篇

猜你喜欢

热点阅读