Jens
Jens

Reputation: 2637

How to create and use a gradle task factory function

How do I create a function that create function or maybe I should ask to call it

// cant use this method see comment tagged ERROR further down
def webRollbackFactory(parentTask) {
  tasks.create(name: "webRollback.${parentTask.name}", type: Copy, dependsOn: [webBackup]) {
    onlyIf { patentTask.state.failure != null }
    from(zipTree("${webPublishPath}/../${getWebBackupName()}")) { include '*' }
    into webPublishPath
    doLast {
      println "\nwebRollback.${parentTask.name}.doLast"
    }
  }
}

// this task which do the same works with out problems
task webRollback_webPublish(type: Copy) {
  onlyIf { webPublish.state.failure != null }
  from(zipTree("${webPublishPath}/../${getWebBackupName()}")) { include '*' }
  into webPublishPath
  doLast {
    println "\nwebRollback.webPublish.doLast"
  }
}

task webPublish(type: com.ullink.Msbuild) {
  dependsOn msbuild, webBackup
  projectFile = "${webPublishProjectDir}/${webPublishProjectFileName}"
  targets = ['Publish']
  parameters = [PublishProfile: webPublishProfile]
  configuration = BUILD_TYPE
  parameters.maxcpucount
  doLast {
    println '\nwebPublish.doLast'
  }

  // ERROR: fails with: Could not find method webRollbackFactoy() for arguments [task ':webAccessTest'] on task ':webAccessTest' of type org.gradle.api.tasks.Exec.
  //finalizedBy webRollbackFactory(webPublish)

  // the version that works
  finalizedBy webRollback_webPublish
}

I am on Gradle 4.8

Upvotes: 0

Views: 119

Answers (1)

Ian Pilipski
Ian Pilipski

Reputation: 535

The reason you get that error is because the closure being evaluated does not find the function declared in the main file.

Try changing your function to a closure as a variabe reference and then it should work. webRollbackFactory = { parentTask -> tasks.create(name: "webRollback.${parentTask.name}", type: Copy, dependsOn: [webBackup]) { onlyIf { patentTask.state.failure != null } from(zipTree("${webPublishPath}/../${getWebBackupName()}")) { include '*' } into webPublishPath doLast { println "\nwebRollback.${parentTask.name}.doLast" } } }

Upvotes: 1

Related Questions