Mateusz Dymczyk Mateusz Dymczyk - 3 months ago 8
Java Question

Add gradle resources unders custom output dir

I have a project structure like this (using gradle 2.11):

submodule1
|
- src
|
- main
|
- resources
|
- file1
submodule2
|
- resources
|
- file2
- file3


I'm adding some additional things to
submodule1
's
resources
via:

sourceSets {
main {
resources {
srcDir("../submodule2/resources")
}
}
}


Is there an easy way to specify a custom output path for resources from
submodule2
? Currently when I jar it, all resource files
file1
,
file2
etc. will be put inside the jar on the top level. I would like the
submodule1
files to stay at top level and the
submodule2
resources to be put inside the jar under a custom path i.e.
submodule2resources
.

Answer

You need to filter the files during the jar file is built. It's done in jar closure in build.gradle file using the DSL. The problem here lies in the fact that when you add a source set and jar is prepared the information about the origin of a given file is lost - all files belong to submodule1 now - hence a workaround here is needed:

apply plugin: 'java'

project.ext.sm2Resources = project.file("../sm2/src/main/resources")

sourceSets {
    main {
        resources {
            srcDir(sm2Resources)
        }
    }
}

jar {
  eachFile { f ->
      if(new File(sm2Resources, f.file.name).exists()) {
        f.path = "sm2/$f.name"
      }
  }
}

Check out the demo.

Comments