Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate multiple files in Gradle?

Tags:

gradle

Is there an easy way to concatenate multiple text files into a single one in Gradle? The build script should look something like this:

FileCollection jsDeps = files(
   'file1.js',
   'file2.js'
   // other files here
)

task concatenate << {
   // concatenate the files to file.js
}

I am using Gradle 2.3.

like image 724
MartinTeeVarga Avatar asked Apr 17 '15 07:04

MartinTeeVarga


People also ask

Can you have multiple build Gradle files?

Yes. You can have multiple build files in one project. The only thing you can't do, of course, is have multiple files named build. gradle in the same folder.

What is Gradle doLast?

The doLast ensures that this code block is only executed during task execution. It basically tells Gradle during configuration to run this code block last while executing this task 1. We can also use the doFirst code block to run something first while executing the task.

Why are there multiple build Gradle files?

Android Studio projects contain a top-level project Gradle build file that allows you to add the configuration options common to all application modules in the project. Each application module also has its own build. gradle file for build settings specific to that module.

What does a Gradle wrapper not do?

The Gradle Wrapper itself does not execute your tasks. All it does is ensure you have the desired Gradle distribution and then invoke it.


3 Answers

leftShift / "<<" is deprecated in gradle 3.4 You may use something like:

task concatenate {
    doLast {
        def toConcatenate = files("filename1", "filename2", ...)
        def outputFileName = "output.txt"
        def output = new File(outputFileName)
        output.write('') // truncate output if needed
        toConcatenate.each { f -> output << f.text }
    }
like image 132
Martin Faust Avatar answered Oct 27 '22 10:10

Martin Faust


You can also register the files as inputs/outputs to help with incremental builds. It's especially helpful with larger files.

something like this:

task 'concatenateFiles', {
    inputs.files( fileTree( "path/to/dir/with/files" ) ).skipWhenEmpty()
    outputs.file( "$project.buildDir/tmp/concatinated.js" )
    doLast {
        outputs.files.singleFile.withOutputStream { out ->
            for ( file in inputs.files ) file.withInputStream { out << it << '\n' }
        }
    }
}

Instead of the fileTree, it can also be replaced with sourceset/sourceset output, specific files, outputs from a different task, etc.

Gradle doc on task inputs/output

Concatenating files in groovy

like image 27
Aarjav Avatar answered Oct 27 '22 09:10

Aarjav


The following task should do the job:

task concatenate << {
    def toConcatenate = files('f1', 'f2', 'f3')
    def output = new File('output')
    toConcatenate.each { f -> output << f.text }
}
like image 25
Opal Avatar answered Oct 27 '22 11:10

Opal