Run a groovy class file without main method using gradle task - gradle

I have a class file which does not have a main method. I need to run the class file only when needed with the help of a gradle task. Can someone help me with writing a gradle task for it?

I'd guess it'd be something like
buildscript {
// add your library to the buildscript classpath
classpath 'foo.bar:mygroovylib:1.0'
}
task runMyGroovy {
// let's assume your service accepts an input file and writes to an output directory
File inFile = file('path/to/some/file.xml')
File outDir = file("$buildDir/myGroovy")
// set task inputs/outputs to benefit from gradle's up-to-date checks
inputs.file inFile
outputs.dir outDir
doLast {
// actually do stuff in gradle's execution phase
def myObject = new MyGroovyObject();
myObject.doSomethingFantastic(inFile, outDir)
}
}

Related

Set the properties in the configuration phase of a task in another task

I have spent the last few hours trying to find a solution for my requirement, without luck:
I have a task that has to run some logic in a certain path:
task run(type: MyPlugin) {
pathForPlugin = myPath //Defined as a property in another gradle file
}
I want to set the "pathForPlugin" property dynamically in another task because it has to be read from some configuration file.
task initPaths(type: PathFinder) {
configurationFile = 'C:\\myConfig.conf'
}
The myConfig.conf would look like this:
pathForPlugin = 'C:\\Correct\\Path'
The problem is that "initPaths" has to run before the configuration phase of "run".
I have tried several approaches for this (GradleBuild task, dependsOn, Using Properties in the Plugin for "Lazy Configuration") but every approach only takes effect in the Execution phase leading to the "pathForPlugin" always staying at its default value.
Is there some way i can realize this or should i look for another solution outside of the gradle build?
I found a solution for the problem:
Instead of defining a task "initPaths" i directly used the java class "Pathfinder" in the build script:
import mypackage.PathFinder;
new PathFinder(project).run()
You only have to make sure that this part is above the definition of the task where the properties are used.
I admit this is a bit of a "hacky" solution but it works fine for my requirement.
you can do like this:
ext {
myPath //use it as a global variable that you can set and get from different gradle tasks and files
}
task firstTask {
doLast {
ext.myPath = "your path"
}
}
task run(type: MyPlugin) {
doFirst { //executed on runtime not on task definition
pathForPlugin = ext.myPath //Defined as a property in another gradle file
}
}
//example 2 - create run task dynamic
task initPath {
doLast {
tasks.create(name: "run", type: MyPlugin) {
pathForPlugin = ext.myPath
}
}
}

Gradle: Delete files from directory, based on Filelist

I'm currently trying to migrate my old ant system to gradle. I'm pretty new to gradle and still learning, so maybe this is something trivial I just overlooked.
I got a file, called delete.list which contains a list of files I want to delete.
This is my code so far:
task deleteLib(type:DeleteFiles) {
deleteList = file("${buildDir}/delete.list")
}
class DeleteFiles extends DefaultTask {
#SkipWhenEmpty
#InputFile
File deleteList
DeleteFiles()
{
description = 'Deletes Libs from Integris zip'
}
#TaskAction
void delete(){
def lines = deleteList.readLines()
lines.each {
delete fileTree(dir: "${project.buildDir}", include: "${it}")
}
}
}
delete.list:
lib/java/activation.jar
lib/java/pdfbox*.jar
lib/java/fontbox*.jar
lib/java/xmpbox*.jar
lib/java/jempbox*.jar
lib/java/iText*.jar
lib/java/itext*.jar
lib/java/jakarta-poi.jar
lib/java/commons-net*.jar
lib/java/jfreechart*.jar
lib/java/jcommon*.jar
lib/java/dom4j*.jar
lib/java/xmlbeans*.jar
lib/java/jaxen*.jar
lib/java/avalon-framework*.jar
lib/java/batik-all*.jar
After googling a bit I found this solution, as my _delete.list may not exist during building phase.
My current problem is that gradle seems to have a problem with the fileTree method:
* What went wrong:
Execution failed for task ':deleteLib'.
> Could not find method fileTree() for arguments [{dir=C:\entwicklung\Testumgebung\testProjectGradle\build, include=lib/java/activation.jar}] on task ':deleteLib' of type DeleteFiles.
Have somebody an idea what I'm missing here?
Since both methods are defined on Project and groovy looks for the method defined in task you need to explicitly invoke the methods on project instance:
project.with {
delete fileTree(dir: "${project.buildDir}", include: "${it}")
}

How to copy files from some source path with gradle script?

I am trying to copy images for javadocs with gradle. Currenly images are located under
MYPROJECT/src/main/resources/doc-files/images/
I refer these images with something like this
<img src="{#docRoot}/doc-files/images/myimage.jpg">
Now I wish to copy all content from under MYPROJECT/src/main/resources/doc-files/ into MYPROJECT/build/docs/javadoc/doc-files/ and I write in build.gradle:
javadoc << {
FileTree docFilesTree = fileTree(dir: 'src/main/resources/doc-files')
copy {
from docFilesTree
into destinationDir
}
}
This has two problems:
1) It does nothing :)
2) It refers resources/doc-files/images/ explicitly, while I would like to deduce it from parameters. I failed to know how to use something from here: https://docs.gradle.org/current/userguide/java_plugin.html
I'm not exactly sure what you mean by you want to deduce resources/doc-files/images from its parameters.
However, if you want to copy files from one directory to another, you can create a task such as:
FileTree docFilesTree = fileTree(dir: 'src/main/resources/doc-files')
task copyJavaDocSupportFiles(type: Copy) {
from docFilesTree
into 'build/docs/javadoc/doc-files/'
}
You can then add this dependency to a javadoc task such as:
task generateJavadocs(type: Javadoc, dependsOn: ['copyJavaDocSupportFiles']) {
source = sourceSets.main.allJava
}
When you run the generateJavadocs task, it will copy the files from src/main/resources/doc-files to build/docs/javadoc/doc-files

Gradle copy task, inside filter - gradle.properties file value not working

Inside gradle copy filter task in my build.gradle file, I am trying to read label value from gradle.properties file or from a variable. Please refer below piece of code:
def label = "2.2"
task filterJS(type: Copy) {
from 'src/main/webapp'
into 'build/webapp'
filter(ReplaceTokens, tokens: [vlabel: $label])
}
In HTML file, I have #vlabel#
On running gradle filterJS, getting below exception
What went wrong:
A problem occurred evaluating project ':CargoSystemUX'.
Could not find property $label on task :CargoSystemUX:filterJS.
I am not able to replace $label with its value at run time. Please suggest me the solution for this.
It should be:
import org.apache.tools.ant.filters.ReplaceTokens
def label = "2.2"
task filterJS(type: Copy) {
from 'webapp'
into 'filtered'
filter(ReplaceTokens, tokens: [vlabel: label])
}
Without $ when referring to label and also note the import statement.

Moving built-in gradle tasks work to doLast/built-in tasks shourtcuts

I want to create a simple sync task that slightly change it behaviour depending on build type (e.g. debug/release) and I use boolean variable 'dummy' decrared in gradle.taskGraph.whenReady:
gradle.taskGraph.whenReady {taskGraph ->
dummy = false
if (taskGraph.hasTask(':dummybuild')) {
dummy = true
}
}
The problem is that task configured by the following way has configuration scope, i.e. before whenReady so it doesn't have access to the 'dummy' variable:
task copySkins(type: Sync) {
from skinsFrom
into skinsInto
rename skinsRename
exclude symbianExclude
if (!dummy) exclude dummyExclude
}
Right now I'm using this workaround
task copySkins {
inputs.dir skinsFrom
outputs.dir skinsInto
doLast {
task skins(type: Sync) {
from skinsFrom
into skinsInto
rename skinsRename
exclude symbianExclude
if (!dummy) exclude dummyExclude
}
skins.execute()
}
}
Is it possible to
detect/setup some build properties in some other place except whenReady
move sync task work to doLast
or at least have some shortcut for sync task (.execute() looks quite ugly)
1) whenReady event allows user to access fully-initialized task graph: all initialization is finished and tasks are ready to run. The only situation, when you need to detect/setup build properties here, is when you need to introspect current build setup.
If you do not need this information, you can place your initialization anywhere in your build script. At the very end, it is nothing but groovy script.
apply plugin: 'java'
def now = new Date()
compileJava.doFirst {
println "It is ${now}. We are starting to compile"
}
2) You can not move sync task work to doLast. But you can always add your actions to doFirst ;) I think, this should work:
task copySkins(type: Sync) {
from skinsFrom
into skinsInto
rename skinsRename
exclude symbianExclude
doFirst {
if (!dummy) exclude dummyExclude
}
}
3) With all said before, missing sync task shortcut should not be that painfull

Resources