Kilokahn
Kilokahn

Reputation: 2311

Include specific classes in jar archive in gradle build

I have a newbie question on a gradle java project. I wish to configure the output artifact jar of this to only include certain classes from my project. I have the desired classes to be included in a file say classes.txt that is generated as a part of a separate task. How should one configure the jar task of the gradle build so that does this. This is what I have tried so far:

jar {
    // reset actions
    actions = []
    copy {
        def dependentClasses = file("classes.txt")
        if (dependentClasses.exists()) {
            dependentClasses.eachLine { include it }
        }

        from sourceSets.main.output
        includeEmptyDirs = false
        into "build/tmp/jar" //Some temporary location
    }
    // How to zip the contents?
}

I am sorry for the possibly naive question, but I haven't had luck with the other solutions seen.

Thanks!

Upvotes: 3

Views: 2236

Answers (2)

Kilokahn
Kilokahn

Reputation: 2311

Using Opal's answer, here is the answer for the include of files

apply plugin: 'java'

jar {
   def included = project.file('classes.txt').readLines()
   include { f ->
      included.any { i -> f.isDirectory() ? true : f.path.replaceAll(File.separator, '.').contains(i) }
   }
}

The slight trick was that the FileTreeElement f being passed to the closure also has the package directory passed and if that happens to return false, the subtree below is not traversed and hence the check on it being a directory to return true to enable processing of the subtree.

Demo for solution is here and Lol1.class will be included. Thanks for the help, Opal!

Upvotes: 2

Opal
Opal

Reputation: 84756

It can be done in the following way:

apply plugin: 'java'

jar {
   def excluded = project.file('classes.txt').readLines()

   exclude { f ->
      excluded.any { e -> f.path.replaceAll(File.separator, '.').contains(e) }
   }
}

Demo can be found here, Lol1.class will be excluded.

Upvotes: 3

Related Questions