如何有条件地应用源集排除基于提供的参数构建

时间:2018-06-15 08:23:56

标签: java gradle

我正在使用Gradle 4.4(编辑:问题仍存在于Gradle 4.8中)。出于原因,我的项目具有以下布局

src/main/java/com/company/common
src/main/java/com/company/mod1
src/main/java/com/company/mod2

构建可以生成mod1或mod2,具体取决于执行的构建任务。 mod1中的类永远不会使用mod2中的类,反之亦然。因此,如果要么使用另一个的类,我希望构建失败。但是我仍然希望能够在Eclipse中开发这两个源,这就是为什么我只希望构建在CI服务器上失败。 CI服务器提供参数CI_BUILD。构建文件使用以下机制来允许:

此处未正确应用排除:

ext {
    ext_template_mod1 = [:]
    ext_template_mod1.src_excludes       = "**/mod2/**"

    ext_template_mod2 = [:]
    ext_template_mod2.src_excludes       = "**/mod1/**"

    if (project.hasProperty("mod2")) {
      ext_template = ext_template_mod2
    } else {
      ext_template = ext_template_mod1
    }
}
sourceSets {
  main {
    java {
      if (project.hasProperty("CI_BUILD")) {
        exclude "${project.ext_template.src_excludes}"
      }
    }
  }
}

出于某种原因,这不起作用。如果mod1上的源文件从mod2引用源文件,则gradlew build -PCI_BUILD不会失败。

我不明白为什么不这样做。如果我不检查项目属性,则排除按预期工作:

工作配置:

ext {
    ext_template_mod1 = [:]
    ext_template_mod1.src_excludes       = "**/mod2/**"

    ext_template_mod2 = [:]
    ext_template_mod2.src_excludes       = "**/mod1/**"

    if (project.hasProperty("mod2")) {
      ext_template = ext_template_mod2
    } else {
      ext_template = ext_template_mod1
    }
}
sourceSets {
  main {
    java {
      exclude "${project.ext_template.src_excludes}"
    }
  }
}

当mod1上的源文件从mod2引用源文件时,gradlew build -PCI_BUILD按预期失败。

但是现在我的IDE将不再将mod2文件夹中的源识别为源。

如何根据构建参数的存在将排除应用于我的源集?

1 个答案:

答案 0 :(得分:0)

我一直在创建一个最小的例子,它在那里工作得很好:

apply plugin: 'java'

ext {
    ext_template_mod1 = [:]
    ext_template_mod1.src_excludes       = "**/mod2/**"

    ext_template_mod2 = [:]
    ext_template_mod2.src_excludes       = "**/mod1/**"

    if (project.hasProperty("mod2")) {
      ext_template = ext_template_mod2
    } else {
      ext_template = ext_template_mod1
    }
}
sourceSets {
  main {
    java {
      if (project.hasProperty("CI_BUILD")) {
        exclude "${project.ext_template.src_excludes}"
      }
    }
  }
}

jar {
  if (project.hasProperty("CI_BUILD")) {
    exclude "${project.ext_template.src_excludes}"
  }
}

上面的问题是我自己构建的工件。我曾使用动态任务生成而忘记提供我正在检查的参数startParameter.projectProperties