As part of my project, I need to read files from a directory and do some operations all these in build script. For each file, the operation is the same(reading some SQL queries and execute it). I think its a repetitive task and better to write inside a method. Since I'm new to Gradle, I don't know how it should be. Please help.
Gradle builds a script file for handling two things; one is projects and other is tasks. Every Gradle build represents one or more projects. A project represents a library JAR or a web application or it might represent a ZIP that is assembled from the JARs produced by other projects.
buildSrc is a separate build whose purpose is to build any tasks, plugins, or other classes which are intended to be used in build scripts of the main build, but don't have to be shared across builds.
Keyword def comes from Groovy and means that variable has local scope. Using ext. outDir means that you add property outDir to ExtraPropertiesExtension, think of it like project has a map of properties with name ext , and you put your property in this map for later access.
One approach given below:
ext.myMethod = { param1, param2 -> // Method body here }
Note that this gets created for the project scope, ie. globally available for the project, which can be invoked as follows anywhere in the build script using myMethod(p1, p2)
which is equivalent to project.myMethod(p1, p2)
The method can be defined under different scopes as well, such as within tasks:
task myTask { ext.myMethod = { param1, param2 -> // Method body here } doLast { myMethod(p1, p2) // This will resolve 'myMethod' defined in task } }
If you have defined any methods in any other file *.gradle - ext.method() makes it accessible project wide. For example here is a
versioning.gradle
// ext makes method callable project wide ext.getVersionName = { -> try { def branchout = new ByteArrayOutputStream() exec { commandLine 'git', 'rev-parse', '--abbrev-ref', 'HEAD' standardOutput = branchout } def branch = branchout.toString().trim() if (branch.equals("master")) { def stdout = new ByteArrayOutputStream() exec { commandLine 'git', 'describe', '--tags' standardOutput = stdout } return stdout.toString().trim() } else { return branch; } } catch (ignored) { return null; } }
build.gradle
task showVersion << { // Use inherited method println 'VersionName: ' + getVersionName() }
Without ext.method() format , the method will only be available within the *.gradle file it is declared. This is the same with properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With