Gradle add 2 source files from directory

31 views Asked by At

I have a gradle project that by default adds src\main\java.

I need to add 2 additional files that are outside of this directory - say ../project1/src/main/java/com/github/blabla/pcg1/

if I do it like this: sourceSets.main.java.srcDirs += '../project1/src/main/java/com/github/blabla/pcg1/'

I see they appear in the log

File in source set: C:\...\src\main\java
File in source set: C:\.../project1/src/main/java/com/github/blabla/pcg1/

But then they do not compile - the files in /project1/src/main/java/com/github/blabla/pcg1/ relate each other and the compilation fails because they cannot find each other.

My suspicion is that they are located in a wrong directory, so to say.

if I would do sourceSets.main.java.srcDirs += '../project1/src/main/java/'

Then all the files in another project will be compiled - which I don't want.

I've also tried to include only those 2 files, but I can't find any working example how to add all files int one source dir and only specific files in another.

I.e. I would expect something like this to work

sourceSets {
    main {
        java {
            srcDir "src"
            srcDir "../project1/src/main/java/com/github/blabla/pcg1/" {
                include 'fil1.java'
                include 'fil2.java'
            }
        }
    }
}

but it does not.

Or i've tried

sourceSets {
    main {
        java {
            srcDir 'src'
            srcDir '../project1/src/main/java/'
            includes[
                    'com/github/blabla/pcg1/fil1.java',
                    'com/github/blabla/pcg1/fil2java'
            ]
        }
    }
}

Does anyone know how to properly add specific 2 files from another project to this one?

1

There are 1 answers

0
Simon Jacobs On BEST ANSWER

Two observations:

  • You don't need to "re-include" the normal project Java source, so no need for lines like:
srcDir 'src'
  • The includes and excludes methods can be called with a Groovy Closure, which is similar to a lambda (see API documentation for PatternFilterable, an interface which is implemented by SourceDirectorySet).

    The Closure will be called with each FileTreeElement in the SourceDirectorySet and you return a Boolean to stipulate whether each element is to be included or excluded.

So to include only your specific files in the directory and keep all the regular source included, you can write something like:

sourceSets {
    main {
        java {
            def extraDir = "../project1/src/main/java/com/github/blabla/pcg1"
            srcDir extraDir
            include { fileElement ->
                fileElement.file.parentFile != file(extraDir) ||
                    fileElement.file == file("$extraDir/Foo.java") ||
                    fileElement.file == file("$extraDir/Bar.java")
            }
        }
    }
}

This will include the files Foo.java and Bar.java in your extra directory, but exclude everything else.