gradle - Factorize gradle task
问题描述
I would like to factorize code in my gradle script (for android project, don't know if it change something) that looks like this right now:
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")
}
The number of gif*
tasks will grow with the project and for know it's basically copy/pasted changing "Foo" with "Bar" which is not a good option.
I'm pretty new to gradle script and I didn't figured out a simple way to look/create a function/create a task macro, how do you do that ?
解决方案
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"
}
Or perhaps
task gifAll {
doLast{
['Foo', 'Bar'].each {thing ->
exec{
commandLine 'convert', '-delay', '200', "screenshots/jpg${thing}*",
'-resize', '380x',
"screenshots/gif${thing}.gif"
}
}
}
}
If it was me, I'd put all the gifs to convert into a single folder and convert everything rather than maintaining the list. This way as you add more gifs to the folder they are automatically converted
Eg:
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")
}
推荐阅读
- android - RegExp 奇怪的情况
- java - 将字母映射到数字的最佳方法
- partitioning - 如何使用blocking.cv
- react-native - 不变违规:requireNativeComponent:在 UIManager 中找不到“RCTView”
- java - Java Casting:Java 11 抛出 LambdaConversionException 而 1.8 没有
- c# - Angular 与 npm 或视觉工作室?
- android - 检查您的 google-services 插件配置,未填充 default_web_client_id 字符串
- python - 如何在 sql 中连接现有的 python 脚本?
- c# - 是否允许将两个程序之间的部分接口转移到构造函数?
- javascript - 在 Android 设备上放大时图像模糊