首页 文章

Gradle sourceSet依赖于另一个sourceSet

提问于
浏览
4

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

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

sourceSets {
  testenv
}

dependencies {
  testenvCompile sourceSets.main
}

这不起作用,因为您无法直接将sourceSets添加为依赖项 . 建议的方法是:

sourceSets {
  testenv
}

dependencies {
  testenvCompile sourceSets.main.output
}

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

如何正确声明依赖项?

EDIT:

这个

sourceSets {
  testenv
}

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

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

1 回答

  • 4

    毕竟这是要走的路:

    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.")
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    

相关问题