首页 > 解决方案 > 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 ?

标签: gradlebuild.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" 
} 

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")
}

推荐阅读