Gradle change resource files target location in JAR

classpath, gradle, jar, java

Solution

Here's how I ended up doing it. This is the `build.gradle` file for the `config` module:

apply plugin: 'java'

sourceSets {
  main {
    resources {
      srcDir 'props'
    }
  }
}

// this is to force Gradle to create the JAR used at 
// runtime with the correct folder structure
jar.into('props')

idea.module.iml.withXml {
  def node = it.asNode()
  // this is to force IntelliJ to create the folders 
  // used at runtime with the correct folder ('package') structure
  node.component.content.sourceFolder.@packagePrefix="props"
}

It works like a charm because the `config` module only contains resources in the props folder. Whew.

Problem

I am Gradle-fying a legacy project with the following structure: ``` root +--- common | \--- config +--- module1 \--- module2 ``` In the original project, `config` is just a folder that contains configuration files organized in subfolders for different environments. It contains a top level folder `props` and many subfolders as in: ``` config \--- props +--- prod +--- dev +--- john \--- mike ``` The project can be configured to use any of the subfolders. The configuration gets loaded by a method that looks like this: ``` Config.class.getClassLoader().getResourceAsStream("props/" + ENV + "/" + name); ``` where `ENV` defines the environment (it's a system property), i.e., it can be `prod`, `dev`, `mike`, etc., and `name` is just the name of the file to load. When running tests, I need to have the `props` folder in the classpath. When building the production artifacts (JARs and WARs) I wan't to avoid that and manually copy only the files I need in order to avoid possible conflicts or accidents. So I decided to make `config` its own Gradle project and add it as a testCompile dependency to other modules that require configuration. However, if I add the `props` folder as a resource folder in Gradle, the generate JAR file for the `config` module will flatten all the subfolders of `props` (which is the intended behavior), and thus the code above will simply fail. My question is: is there a way to tell Gradle to copy those files to a subfolder called props instead of to the root of the JAR? I know it would be easy to refactor the project and move the folders around but we are in a phase of transition from legacy build and deployment tools and want to maintain the original structure as much as possible until we can switch to Gradle completely. It's an iterative process and can't happen overnight. So I need an interim solution.

Original source