List all Java packages in SourceSet with Gradle, before compilation

Viewed 1225

Inside a build.gradle file, what's the most concise way to get a list of all packages in a SourceSet?

I can get it by parsing each source file, as below —

def sourceSet = project.sourceSets.findByName('test')
def pattern = Pattern.compile('package (\\S+);')
def packages = []
sourceSet.allSource.each {
  for (def scan = new Scanner(it); scan.hasNext();) {
    def matcher = scan.nextLine() =~ pattern
    if (matcher.matches()) {
      packages << matcher[0][1]
      break
    }
  }
}
packages.unique(true)

// allows, e.g.
packages.each { println it }

— but it seems as though there ought to be a better way.


Edited to add: I need this information in order to pass additional arguments to the JVM at compile time, so I need to get it from the source, before compilation.

1 Answers

I made some searchs and did not found a perfect clean solution.

But here is one based on java files, using the path to resolve the package. Not need to use allSource as only java files are contained in a package.

This solution avoids reading all files.

def sourceSet = project.sourceSets.findByName('main').java
def packages = sourceSet
.filter{ it.path.endsWith('.java') }
.collect{ it.getParentFile().path
    .substring(sourceSet.srcDirs[0].path.length()+1)
    .replace('/', '.') }
.unique()

packages.each { println it }
Related