Gradle sourceSet 依赖于另一个 sourceSet

标签 gradle dependencies source-sets

这个问题类似于Make one source set dependent on another

除了主要的 SourceSet,我还有一个 testenv SourceSet。
testenv SourceSet 中的代码引用了主代码,因此我需要将主 SourceSet 添加到 testenvCompile 配置中。

sourceSets {
  testenv
}

dependencies {
  testenvCompile sourceSets.main
}

这不起作用,因为您不能直接添加 sourceSet 作为依赖项。推荐的方法是:
sourceSets {
  testenv
}

dependencies {
  testenvCompile sourceSets.main.output
}

但这在 eclipse 中不能正常工作,因为当我清理 gradle build 文件夹时,eclipse 无法再编译,因为它依赖于 gradle build。
此外,如果我更改主代码,我必须在 gradle 中重建项目才能使更改在 eclipse 中生效。

如何正确声明依赖项?

编辑:

这个
sourceSets {
  testenv
}

dependencies {
  testenvCompile files(sourceSets.testenv.java.srcDirs, sourceSets.testenv.resources.srcDirs)
}

适用于主要源代码,但是因为我现在引用了 .java 文件,所以我缺少从 Annotation-Processor 生成的类:(

最佳答案

所以毕竟这是要走的路:

sourceSets {
  testenv
}

dependencies {
  testenvCompile sourceSets.main.output
}

要使其与 Eclipse 一起正常工作,您必须手动从 Eclipse 类路径中排除所有 sourceSet 输出。
这很丑陋,但对我有用:
Project proj = project

eclipse {
  classpath {
    file {
      whenMerged { cp ->
        project.logger.lifecycle "[eclipse] Excluding sourceSet outputs from eclipse dependencies for project '${project.path}'"
        cp.entries.grep { it.kind == 'lib' }.each { entry ->
          rootProject.allprojects { Project project ->
            String buildDirPath = project.buildDir.path.replace('\\', '/') + '/'
            String entryPath = entry.path

            if (entryPath.startsWith(buildDirPath)) {
              cp.entries.remove entry

              if (project != proj) {
                boolean projectContainsProjectDep = false
                for (Configuration cfg : proj.configurations) {
                  boolean cfgContainsProjectDependency = cfg.allDependencies.withType(ProjectDependency).collect { it.dependencyProject }.contains(project)
                  if(cfgContainsProjectDependency) {
                    projectContainsProjectDep = true
                    break;
                  }
                }
                if (!projectContainsProjectDep) {
                  throw new GradleException("The project '${proj.path}' has a dependency to the outputs of project '${project.path}', but not to the project itself. This is not allowed because it will cause compilation in eclipse to behave differently than in gradle.")
                }
              }
            }
          }
        }
      }
    }
  }
}

关于Gradle sourceSet 依赖于另一个 sourceSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32122363/

相关文章:

ant - 如何为项目/lib 中的本地 jar 创建 Ivy 依赖项?

asp.net - 创建对文件夹及其子文件夹的缓存依赖关系

android - 使用不同方法在 gradle 构建期间合并资源

java - 如何使用 gradle java-plugin 将一些 java 文件构建到一个 jar 中?

java - 当我尝试git push heroku时出现错误

intellij-idea - 将另一个 gradle 项目导入现有的 android 项目时,Android Studio 访问被拒绝

android - 如果修改或删除了其使用的依赖项,我的应用程序会中断吗?

android - 如何为具有 flavor 维度的不同产品变体指定 signingConfigs?

java - 动态依赖关系