I want to replace few lines in my Config.java file before the code gets compiled. All I was able to find is to parse file through filter during copying it. As soon as I have to copy it I had to save it somewhere - thats why I went for solution: copy to temp location while replacing lines > delete original file > copy duplicated file back to original place > delete temp file. Is there better solution?
May be you should try something like ant's replaceregexp:
task myCopy << {
ant.replaceregexp(match:'aaa', replace:'bbb', flags:'g', byline:true) {
fileset(dir: 'src/main/java/android/app/cfg', includes: 'TestingConfigCopy.java')
}
}
This task will replace all occurances of aaa with bbb. Anyway, it's just an example, you can modify it under your purposes or try some similar solution with ant.
To complement lance-java's answer, I found this idiom more simple if there's only one value you are looking to change:
task generateSources(type: Copy) {
from 'src/replaceme/java'
into "$buildDir/generated-src"
filter { line -> line.replaceAll('xxx', 'aaa') }
}
Caveat: Keep in mind that the Copy task will only run if the source files change. If you want your replacement to happen based on other conditions, you need to use Gradle's incremental build features to specify that.
I definitely wouldn't overwrite the original file
I like to keep things directory based rather than filename based so if it were me, I'd put Config.java in it's own folder (eg src/replaceme/java)
I'd create a generated-src directory under $buildDir so it's deleted via the clean task.
You can use the Copy task and ReplaceTokens filter. Eg:
apply plugin: 'java'
task generateSources(type: Copy) {
from 'src/replaceme/java'
into "$buildDir/generated-src"
filter(ReplaceTokens, tokens: [
'xxx': 'aaa',
'yyy': 'bbb'
])
}
// the following lines are important to wire the task in with the compileJava task
compileJava.source "$buildDir/generated-src"
compileJava.dependsOn generateSources
If you do wish to overwrite the original file, using a temp file strategy, the following will create the filtered files, copy them over the original, and then delete the temp files.
task copyAtoB(dependsOn: [existingTask]) {
doLast {
copy {
from("folder/a") {
include "*.java"
}
// Have to use a new path for modified files
into("folder/b")
filter {
String line ->
line.replaceAll("changeme", "to this")
}
}
}
}
task overwriteFilesInAfromB(dependsOn: [copyAtoB]) {
doLast {
copy {
from("folder/b") {
include "*.java"
}
into("folder/a")
}
}
}
// Finally, delete the files in folder B
task deleteB(type: Delete, dependsOn: overwriteFilesInAfromB) {
delete("folder/b")
}
nextTask.dependsOn(deleteB)
Related
I have a gradle task to zip the .yaml files into a zip folder, which looks like this:
task gradleTask1(type: Zip) {
from 'src/test/resources/source_one/'
include '**/*'
archiveName 'file-collect.zip'
destinationDir(file("${buildDir}/resources/test/staging/target_one"))
}
Similarly, I have other tasks that look the same, but the source and target directories are different.
task gradleTask2(type: Zip) {
from 'src/test/resources/source_two/'
include '**/*'
archiveName 'file-collect.zip'
destinationDir(file("${buildDir}/resources/test/staging/target_two"))
}
task gradleTask3(type: Zip) {
from 'src/test/resources/source_three/'
include '**/*'
archiveName 'file-collect.zip'
destinationDir(file("${buildDir}/resources/test/staging/target_three"))
}
And the main issue is I have to add dependency every time I add a new zip task as follows:
compileJava.finalizedBy gradleTask1
compileJava.finalizedBy gradleTask2
compileJava.finalizedBy gradleTask3
Is there any way I can achieve these steps dynamically? Can I have a single zip task (something like zipAll) and finally the task dependency can be
compileJava.finalizedBy zipAll
Consider the following (example here):
tasks.withType(Zip).all { task ->
def taskName = task.name
if (taskName ==~ /gradleTask.*/) {
println "TRACER adding dependency on ${taskName}"
compileJava.finalizedBy taskName
}
}
This will dynamically find tasks of type Zip with name matching gradleTask* and add it to the list of tasks for compileJava.finalizedBy.
There is no zipAll task, but gradle compileJava will work as desired.
I try to build jar and after that copy it to another folder.
task createJar(type: Jar) {
archiveName = "GradleJarProject.jar"
manifest {
attributes 'Implementation-Title': 'Gradle Jar File Example',
'Implementation-Version': version,
'Main-Class': 'me.test.Test'
}
baseName = project.name
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
with jar
}
task copyJarToBin {
copy {
from 'build/libs/GradleJarProject.jar'
into "d:/tmp"
}
}
task buildApp (dependsOn: [clean, createJar, copyJarToBin])
But I can't figure out one problem.
copyJarToBin task try to copy old jar. If I delete /build folder in the project and run buildApp() task, task createJar() will generate .jar file, but copyJarToBin() won't find that .jar file.
Could you help me?
Thanks.
The culprit is your copyJarToBin task. when doing
task copyJarToBin {
copy {
from 'build/libs/GradleJarProject.jar'
into "d:/tmp"
}
}
you copy the jar during the configuration time by using the copy method. (see the gradle user guide at https://docs.gradle.org/current/userguide/userguide_single.html#sec:build_phases to understand the build lifecycle)
You want to run the actual copy operation during the execution phase (the execution of the task).
One way to solve that is to move the call of the copy method into a doLast block:
task copyJarToBin {
doLast {
copy {
from 'build/libs/GradleJarProject.jar'
into "d:/tmp"
}
}
}
The problem with this approach is that you won't benefit of gradles incremental build feature and copy that file every single time you execute the task even though the file hasn't changed.
A better and more idiomatic way of writing your copyJarToBin task is to change your task implementation to use the Copy task type:
task copyJarToBin(type: Copy) {
from 'build/libs/GradleJarProject.jar'
into "d:/tmp"
}
We can even improve this snippet by taking advantage of gradle's autowiring feature. You can declare the output of one task as input to another. So instead of writing `build/libs/GradleJarProject.jar' you can simply do:
task copyJarToBin(type: Copy) {
from createJar // shortcut for createJar.outputs.files
into "d:/tmp"
}
Now you don't need to bother about task ordering as gradle know that the createJar task must be executed before the copyJarToBin task can be executed.
I think the above answer is somehow old. Here is an answer using gradle 3.3
jar {
baseName = 'my-app-name'
version = '0.0.1'
}
task copyJar(type: Copy) {
from jar // here it automatically reads jar file produced from jar task
into 'destination-folder'
}
build.dependsOn copyJar
Just made few corrections to above Answers:
jar {
baseName = "$artifactId"
version = '0.0.1'
}
task copyJar(type: Copy) {
from jar // copies output of file produced from jar task
into 'destination-folder'
}
build.finalizedBy copyJar
You probably need to ensure they are run in the right order,
task copyJarToBin(type:Copy,dependsOn:[createJar]) {
copy {
from "${buildDir}/GradleJarProject.jar" // needs to be gstring
into "d:/tmp"
}
}
In my use case I needed projectA to consume (unzip) contents from projectB's jar output. In this case the embedded doLast { copy { .. }} was required.
configurations {
consumeJarContents
}
dependencies {
consumeJarContents project(':projectB')
}
task copyFromJar() {
dependsOn configurations.consumeJarContents
doLast {
copy {
configurations.consumeJarContents.asFileTree.each {
from( zipTree(it) )
}
into "$buildDir/files"
}
}
}
The problem with task copyFromJar(type: Copy) in this scenario is that the Copy configuration phase checks for the jar file, which it does not find because it has not yet been created, and so declares NO-INPUT for the task at execution time.
I have a typical Antlr 4.5 project with two grammar files: MyLexer.g4 and MyParser.g4. From them, Antlr generates 6 output files: MyLexer.java, MyLexer.tokens, MyParser.java, MyParser.tokens, MyParserBaseListener.java and MyParserListener.java. The gradle tasks are all working correctly so that the output files are all generated, compiled and tested as expected.
The problem is that gradle sees the 6 target files as always being out of date, so every run or debug session has to regenerate them and therefore has to recompile the main java project even if none of the source files have changed.
The gradle task which generates the file has the output spec defined as the folder into which the 6 output files are generated. I think that I need a way to define it as being the 6 specific files rather than the output folder. I just don't know the syntax to do that.
Here's the pertinent part of my build.gradle file:
ext.antlr4 = [
antlrSource: "src/main/antlr",
destinationDir: "src/main/java/com/myantlrquestion/core/antlr/generated",
grammarpackage: "com.myantlrquestion.core.antlr.generated"
]
task makeAntlrOutputDir << {
file(antlr4.destinationDir).mkdirs()
}
task compileAntlrGrammars(type: JavaExec, dependsOn: makeAntlrOutputDir) {
// Grammars are conveniently sorted alphabetically. I assume that will remain true.
// That ensures that files named *Lexer.g4 are listed and therefore processed before the corresponding *Parser.g4
// It matters because the Lexer must be processed first since the Parser needs the .tokens file from the Lexer.
// Also note that the output file naming convention for combined grammars is slightly different from separate Lexer and Parser grammars.
def grammars = fileTree(antlr4.antlrSource).include('**/*.g4')
def target = file("${antlr4.destinationDir}")
inputs.files grammars
// TODO: This output spec is incorrect, so this task is never considered up to date.
// TODO: Tweak the outputs collection so it is correct with combined grammars as well as separate Lexer and Parser grammars.
outputs.dir target
main = 'org.antlr.v4.Tool'
classpath = configurations.antlr4
// Antlr command line args are at https://theantlrguy.atlassian.net/wiki/display/ANTLR4/ANTLR+Tool+Command+Line+Options
args = ["-o", target,
"-lib", target,
//"-listener", //"-listener" is the default
//"-no-visitor", //"-no-visitor" is the default
"-package", antlr4.grammarpackage,
grammars.files
].flatten()
// include optional description and group (shown by ./gradlew tasks command)
description = 'Generates Java sources from ANTLR4 grammars.'
group = 'Build'
}
compileJava {
dependsOn compileAntlrGrammars
// this next line isn't technically needed unless the antlr4.destinationDir is not under buildDir, but it doesn't hurt either
source antlr4.destinationDir
}
task cleanAntlr {
delete antlr4.destinationDir
}
clean.dependsOn cleanAntlr
I discovered the problem was not that the target files were out of date, but rather, due to a bug in the cleanAntlr task, they were being deleted every time that any gradle task was run. The problem was that all of the code in cleanAntlr was being run during gradle's initialization and configuration phase, even if the cleanAntlr task itself wasn't being executed.
Originally, the task was defined as:
task cleanAntlr {
delete antlr4.destinationDir
}
clean.dependsOn cleanAntlr
The solution was to define it like this: (Note the "<<" after the task name.)
task cleanAntlr << {
delete antlr4.destinationDir
}
clean.dependsOn cleanAntlr
... or, for additional clarity, use this more verbose, but functionally equivalent task definition:
task cleanAntlr {
doLast() {
// Be sure to wrap the execution phase code inside doLast().
// Otherwise it will run during the initialization or configuration phase, even when an unrelated task is is run.
// It would also run when the NetBeas IDE first loaded the project.
//println 'Deleting Antlr Directory: ' + antlr4.destinationDir
delete antlr4.destinationDir
}
}
clean.dependsOn cleanAntlr
With that bug fixed, the original outputs specification for the compileAntlrGrammars task works correctly. There is no need to specify each individual output file. This is explained quite well in section 15.9.2 of https://gradle.org/docs/current/userguide/more_about_tasks.html.
def grammars = fileTree(antlr4.antlrSource).include('**/*.g4')
def target = file("${antlr4.destinationDir}")
inputs.files grammars
outputs.dir target
Could you please try the following piece of code:
generatedFiles = ['MyLexer.java',] // and so on..
generatedFiles.each { f -> outputs.file("$target/$f") }
I have a copy task with a set of inclusions
task test_init(dependsOn: generate_scripts){
doFirst{
mkdir (project.test_dir)
mkdir (project.test_data_dir)
mkdir (project.test_reports_dir)
mkdir (project.test_logs_dir)
mkdir (project.test_jasper_dir)
mkdir (project.test_chart_dir)
}
doLast{
copy
{
from"${test_script_hsqldb_nd}"
into"${test_dir}"
}
copy
{
from"${test_script_create_constraints}"
into"${test_dir}"
}
copy
{
from"${test_script_drop_constraints}"
into"${test_dir}"
}
copy
{
from fileTree(dir: "${test_src_dir}",
include:
[
'**/*.xml',
'**/*.dtd',
'**/*.csv',
'**/*.mpp',
'**/*.dic',
'**/*.png',
'**/*.properties'
])
into"${build_classes_dir}"
}
}
//////THIS IS MY UGLY WORKAROUND////////////////////
doLast{
delete "${build_classes_dir}/com/XXXX/ppm/gantt"
delete "${build_classes_dir}/com/XXXX/ppm/util"
delete "${build_classes_dir}/com/XXXX/ppm/action/pageinformation"
}
}
It works fine and dandy however there are 3 folders that are included in the 'from' tree of the last copy task that don't contain any files pertinent to the inclusions, as such following the task they are empty.
I would like to have them excluded from the task altogether but I'm having troubles achieving that. Currently I am simply deleting them in the final final 'doLast' block and that seems a little stupid.
I have tried
exclude: "${test_src_dir}/com/XXXX/ppm/gantt",..**similar statements for other files**
and
exclude: "${test_src_dir}/**/gantt"
Though I have a feeling the '**' usage isn't right in this context.
I would appreciate any input people may have.
You could try includeEmptyDirs = false, although I'm not completely sure if it will work for non-empty directories that only become empty after honoring includes/excludes.
PS: It's usually better to use a Copy task (also shows how your syntax can be simplified a lot):
task test_init(type: Copy, dependsOn: generate_scripts) {
from test_script_hsqldb_nd
from test_script_create_constraints
from test_script_drop_constraints
into test_dir
}
// assuming build_classes_dir is not a subdirectory of test_dir, we need a
// second Copy task (every Copy task has a single top-level destination dir)
task test_init_2(type: Copy, dependsOn: generate_scripts) {
from test_src_dir
into build_classes_dir
include '**/*.xml'
include '**/*.dtd'
include '**/*.csv'
include '**/*.mpp'
include '**/*.dic'
include '**/*.png'
include '**/*.properties'
includeEmptyDirs = false
}
Both the Copy task and the copy method will create target directories automatically.
We're trying to build up a minorly complicated Zip file in Gradle from multiple filesystem source trees, but no matter how many into specifications we give, it all puts them in the same one. Is this possible to do in Gradle?
build/libs/foo.jar --> foo.jar
bar/* --> bar/*
We're getting this instead:
build/libs/foo.jar --> bar/foo.jar
bar/* --> bar/*
Using this:
task installZip(type: Zip, dependsOn: jar) {
from('build/libs/foo.jar').into('.')
from('bar').into('bar')
}
Any help would be appreciated.
EDIT: Gradle 1.0-milestone-3
Try this:
task zip(type: Zip) {
from jar.outputs.files
from('bar/') {
into('bar')
}
}
First... the jar should be in the root / of the zip (which seems to be what you want). Second, by specifying the from jar.outputs.files, there is an implicit dependsOn on the jar task, so this shows another way of accomplishing what you want. Except with this approach if the jar name changes over time it doesn't matter. Let me know if you need additional help.
Apparently the comments to an answer will not allow for a convenient way to show more code... or it isn't obvious :) I have a project which is for a client... so I can't share the full project / build file. Here is what I can share (I changed the project specific acron to XXX):
task zip(type: Zip) {
from jar.outputs.files
from('scripts/') {
fileMode = 0755
include '**/runXXX.sh'
include '**/runXXX.bat'
}
from('lib/') {
include '**/*.jar'
into('lib')
}
from('.') {
include 'xxx.config'
}
}
This creates a zip with the project jar in the root of the zip. Copies the scripts from a directory to the root, copies the config file to the root and creates a directory in the root of the zip named /lib and copies all the jars from the project /lib to the zip/lib.
This answer does not directly answer the question but I guess this would help someone who writes 'Gradle Plugins'
final Zip zipTask = project.getTasks().create(taskName, Zip.class);
final Action<? super CopySpec> cp1 = (p) -> {
p.include("**/Install_*.xml", "**/Install.xml").into(WORKING_DIR_1);
};
final Action<? super CopySpec> cp2 = (p) -> {
p.include("*Terminology*.xml").into(WORKING_DIR_2);
};
zipTask.from(projectDir + "/Release", cp1);
zipTask.from(projectDir + "/Release", cp2);