How can I reuse a closure to configure multiple tasks?


(eirik.lygre) #1

In the example below, the tasks “war” and “expandedWar” both have the same configuration (from…). Is it possible to reuse that configuration (which is shown as the unused closure “operations”), to avoid having to duplicate it in the two tasks?

def operations = {
        from ("src/iknowbase/libs/jquery/") {
            include "jquery-${jqueryVersion}*"
            into "iknowbase/libs/jquery"
            rename { String fileName ->
                fileName.replace("-${jqueryVersion}", '-latest')
            }
        }
    }
      war {
        from ("src/iknowbase/libs/jquery/") {
            include "jquery-${jqueryVersion}*"
            into "iknowbase/libs/jquery"
            rename { String fileName ->
                fileName.replace("-${jqueryVersion}", '-latest')
            }
        }
    }
      task expandedWar (type:Copy) {
        from "src"
        into "target/build"
        from ("src/iknowbase/libs/jquery/") {
            include "jquery-${jqueryVersion}*"
            into "iknowbase/libs/jquery"
            rename { String fileName ->
                fileName.replace("-${jqueryVersion}", '-latest')
            }
        }
    }

Filtering a war file with a copySpec
(Peter Niederwieser) #2

Generic way to reuse a configuration block:

def operations = { ... }
  war operations
  task expandedWar ...
  expandedWar operations

For reusing copy operations in particular, there is a special concept called copy spec:

def jquerySpec = project.copySpec {
    from ("src/iknowbase/libs/jquery/") { ... }
}
  war {
    with jquerySpec
}
  task expandedWar(type: Copy) {
    from "src"
    into "target/build"
    with jquerySpec
}

(eirik.lygre) #3

Great reply, great response time :slight_smile:

Thanks!


(Peter Niederwieser) #4

A good question provokes a good answer. :slight_smile: