分解gradle任务

时间:2019-06-08 03:40:58

标签: gradle build.gradle

我想在我的gradle脚本(对于android项目,不知道它是否有所改变)中分解代码:

task gifFoo (dependsOn: 'test') {
    doLast{
        exec{
            commandLine 'convert', '-delay', '200', 'screenshots/jpgFoo*',
                                   '-resize', '380x',
                                   'screenshots/gifFoo.gif'
        }
    }
}

task gifBar (dependsOn: 'test') {
    doLast{
        exec{
            commandLine 'convert', '-delay', '200', 'screenshots/jpgBar*',
                                   '-resize', '380x',
                                   'screenshots/gifBar.gif'
        }
    }
}

task gif(type: Copy, dependsOn : ['gifFoo', 'gifBar']) {
    from("screenshots")
    into("doc")
    include("*.gif")
}

gif*任务的数量将随着项目的增长而增加,并且众所周知,基本上是复制/粘贴,将“ Foo”更改为“ Bar”不是一个好选择。

我对gradle脚本还很陌生,但我没有想出一种简单的方法来查找/创建函数/创建任务宏,如何做到这一点?

1 个答案:

答案 0 :(得分:1)

task gif(type: Copy) {
    from("screenshots")
    into("doc")
    include("*.gif")
}
['Foo', 'Bar'].each { thing ->
    task "gif$thing"(dependsOn: 'test') {
        doLast{
            exec{
                commandLine 'convert', '-delay', '200', "screenshots/${thing}*", 
                                   '-resize', '380x',
                                   "screenshots/gif${thing}gif" 
            }
        }
    }
    gif.dependsOn "gif$thing" 
} 

或者也许

task gifAll {
    doLast{
        ['Foo', 'Bar'].each {thing ->
           exec{
               commandLine 'convert', '-delay', '200', "screenshots/jpg${thing}*", 
                                   '-resize', '380x',
                                   "screenshots/gif${thing}.gif" 
           } 
        }
    }
} 

如果是我,我会将所有gif转换成一个文件夹并转换所有内容,而不是维护列表。这样,当您向文件夹中添加更多gif时,它们便会自动转换

例如:

task gifAll {
    inputs.dir 'src/main/screenshot' 
    outputs.dir "$buildDir/converted-screenshots" 
    doLast{
        fileTree('src/main/screenshot').each {thing ->
           exec{
               commandLine 'convert', '-delay', '200', thing.absolutePath, 
                                   '-resize', '380x',
                                   "$buildDir/converted-screenshots/$thing.name" 
           } 
        }
    }
} 
task gif(type: Copy, dependsOn: gifAll) {
    from("$buildDir/converted-screenshots")
    into("$buildDir/doc")
    include("*.gif")
}