Gradle 因式分解梯度任务

Gradle 因式分解梯度任务,gradle,build.gradle,Gradle,Build.gradle,我想在我的gradle脚本中分解代码(对于android项目,不知道它是否改变了什么),现在看起来是这样的: task gifFoo (dependsOn: 'test') { doLast{ exec{ commandLine 'convert', '-delay', '200', 'screenshots/jpgFoo*', '-resize', '380x',

我想在我的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脚本的新手,我没有想出一个简单的方法来查看/创建函数/创建任务宏,你是怎么做到的

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时,它们会自动转换

例如:


看起来我在
exec
块中使用
${it}
时遇到问题,它看起来是这样解释的
org.gradle.process.internal.DefaultExecAction_Decorated@107b6869
而不是
Foo
?尝试
['Foo',Bar']。每个{thing->…}
然后引用“thing”而不是“it”。。。你能解释一下原因吗?用“东西”修改你的答案,我会接受的。非常感谢;)每个闭包都有一个隐式的“it”变量,您的问题是由嵌套在顶级闭包中的另一个闭包(它有自己的“it”变量)引起的。这意味着我们不得不命名变量,而不是依赖隐式的“it”。答案已更新。看见
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")
}