如何在Gradle Ant任务中重构公共代码?

时间:2016-03-23 00:37:41

标签: gradle groovy

我有以下Gradle代码:

ant.jdiff(destdir: outputDir) {
  old(name: "platform-${oldVersion}") {
    oldVersionRoot.eachDirMatch({ dir ->
      new File("${dir}/src").exists()
    }) { dir ->
      dirset(dir: "${dir}/src")
    }
  }

  'new'(name: "platform-${currentVersion}") {
    currentVersionRoot.eachDirMatch({ dir ->
      new File("${dir}/src").exists()
    }) { dir ->
      dirset(dir: "${dir}/src")
    }
  }
}

我试过了:

final getSrcDirSets = { root ->
  final result = []

  root.eachDirMatch({ dir ->
    new File("${dir}/src").exists()
  }) { dir ->
    result.append(dirset(dir: "${dir}/src"))
  }

  result
}

ant.jdiff(destdir: outputDir) {
  old(name: "example-${oldVersion}") {
    getSrcDirSets(oldVersionRoot)
  }

  'new'(name: "example-${currentVersion}") {
    getSrcDirSets(currentVersionRoot)
  }
}

但是会导致以下错误:

Caused by: org.gradle.api.internal.MissingMethodException: Could not find method old() for arguments [{name=example-1.2.3}, build_at5jtticxum4wmuh64edt9rhd$_run_closure6$_closure26$_closure28$_closure29@26f75d38] on task ':jdiff'.

如何将公共代码重构为单独的函数?

1 个答案:

答案 0 :(得分:0)

一种方法虽然不理想,因为DefaultAntBuilder的所有实例都受到影响,但是通过Groovy monkeypatching:

ant.metaClass.jDiff_getSrcDirSets = { root ->
  root.eachDirMatch({ dir ->
    new File("${dir}/src").exists()
  }) { dir ->
    dirset(dir: "${dir}/src")
  }
}

ant.property(name: "JDIFF_HOME", value: jdiffHome)
ant.jdiff(
    destdir: outputDir,
    verbose: 'off',
    stats: 'on',
    docchanges: 'off',
    source: '1.8') {
  old(name: "${project.name}-${oldVersion}") {
    jDiff_getSrcDirSets(oldVersionRoot)
  }

  'new'(name: "${project.name}-${currentVersion}") {
    jDiff_getSrcDirSets(currentVersionRoot)
  }
}