mike-neckのブログ

Java or Groovy or Swift or Golang

gradleのカスタムタスクで他のタスクを実行する

こんなツイートがあったので、ちょっと調べてみた。

普通にdependsOnとかmustRunAfterとか使えばいいのでは?と思ったけど、書きっぷりからして条件によってタスクの実行内容を変えたいのかと思ったので、単純にdependsOnを使うのではないのだと思った。

他にもいい方法があると思うけど、とりあえず、さっと調べた感じではこんな感じ。

ただし、もっといい方法あるので、だれかマサカリを投げてください。

task hoge << {
    println 'this is hoge'
}

task foo << {
    println 'this is foo'
}

task bar << {
    def v = new Random().nextInt(9)
    println "v = ${v}"
    if(v % 2 == 0) {
        tasks['foo'].actions.each {
          it.execute(tasks['foo'])
        }
    } else {
      tasks['hoge'].actions.each {
        it.execute(tasks['hoge'])
      }
    }
}

実行結果

$ gradle bar
Picked up _JAVA_OPTIONS: -Dfile.encoding=UTF-8
:bar
v = 3
this is hoge

BUILD SUCCESSFUL

Total time: 3.252 secs

【追記1 2015/04/07 11:18】

オチ

ただ、単純にコマンドを叩きたいだけだった(´・ω・`)


【追記2 2015/04/07 12:30】

マサカリ

ちょっとスクリプトを直してみた

//なんかの条件
def condition = new Random().nextInt(9)

task hoge (type: Exec) {
    commandLine 'echo', 'this is hoge(only runs when condition is even)'
    //条件が偶数の時にのみhogeを走らす
    onlyIf {condition % 2 == 0}
}

task foo(type: Exec) {
    commandLine 'echo', 'this is foo(only runs when condition is odd)'
    //条件が奇数の時にのみfooを走らす
    onlyIf {condition % 2 == 1}
}

task bar(type: Exec) {
    commandLine 'echo', 'this is bar'
}

task baz(type: Exec) {
    commandLine 'echo', "condition == [${condition}:${condition % 2 == 0? 'even': 'odd'}]"
}

//タスクグラフ
baz.dependsOn bar
bar.dependsOn hoge, foo

で、実行してみるとこんな感じ。

$ gradle baz
Picked up _JAVA_OPTIONS: -Dfile.encoding=UTF-8
:foo
this is foo(only runs when condition is odd)
:hoge SKIPPED
:bar
this is bar
:baz
condition == [1:odd]

BUILD SUCCESSFUL

Total time: 2.426 secs
$ gradle baz
Picked up _JAVA_OPTIONS: -Dfile.encoding=UTF-8
:foo SKIPPED
:hoge
this is hoge(only runs when condition is even)
:bar
this is bar
:baz
condition == [0:even]

BUILD SUCCESSFUL

Total time: 2.372 secs

まあ、'Task'のAPIあたりを見れば、他のタスクの状況を引っ張ってこれそうではありますね。