如何使用自定义Gradle构建文件和Gradle设置文件

5
gradle命令有很多标志可以自定义其环境[1]。其中包括--build-file--settings-file。但我似乎无法使它们按照我的预期工作。
我希望以下内容能够奏效。
$ cat <<-EOF > alt-settings.gradle
    rootProject.name = 'custom-name'
EOF
$ cat <<-EOF > alt-build.gradle
    task test { /* ... */ }
EOF
$ gradle \
    --settings-file alt-settings.gradle \
    --build-file alt-build.gradle \
    tasks --all

但是这会抛出一个异常。
Build file './alt-build.gradle' is not part of the build defined by settings file './alt-settings.gradle'. If this is an unrelated build, it must have its own settings file.

如果我从上面的命令中省略--settings-file,事情就能正常进行,gradle会选择alt-build.gradle
出了什么问题,我该怎么解决?
理想情况下,即使存在一个不起作用的settings.gradle文件,我也希望能够运行gradle。例如在以下场景中。
$ cat <<-EOF > alt-build.gradle
    task test { /* ... */ }
EOF
$ cat <<-EOF > alt-settings.gradle
    rootProject.name = 'custom-name'
EOF

$ cat <<-EOF > settings.gradle
    This will not compile
EOF
$ cat <<-EOF > build.gradle
    This will not compile
EOF

$ gradle \
    --settings-file alt-settings.gradle \
    --build-file alt-build.gradle \
    tasks --all

[1] https://docs.gradle.org/current/userguide/command_line_interface.html#environment_options

[1] https://docs.gradle.org/current/userguide/command_line_interface.html#environment_options 的内容是关于 Gradle 命令行界面中的环境选项。
1个回答

4
你需要在自定义设置文件中配置自定义构建文件,然后只有在调用Gradle时使用“--settings-file”参数。
alt-settings.gradle:
rootProject.name = 'custom-name'
rootProject.buildFileName = 'alt-build.gradle'

alt-build.gradle:

task test { /* ... */ }

Gradle 调用:

gradle --settings-file alt-settings.gradle tasks --all

这种方式根本不使用默认的构建和设置文件,它们是否有效都无所谓。

更新适用于较新 gradle 版本(在 haridsv 的评论后进行了测试,适用于版本 8.0.1):

gradle 升级指南(https://docs.gradle.org/8.0.1/userguide/upgrading_version_7.html#configuring_custom_build_layout)提供了如何处理自定义构建布局的建议。您可以在设置文件和/或构建文件中使用 if 语句来构建不同的构建。

if (System.getProperty("profile") == "custom") {
    println("custom profile")
} else {
    println("default profile")
}

else分支包含您的默认构建,并且可以通过以下方式调用gradle来执行它:
gradle tasks --all

如果您想运行自定义构建,则需要使用-D命令行选项调用gradle。像这样:

gradle -Dprofile=custom tasks --all

非常感谢,这是一个老问题,我以为我永远不会得到任何答案。所以谢谢你。根据您的建议,我尝试更多地搜索并找到了以下内容:https://discuss.gradle.org/t/how-change-project-name-when-using-non-build-gradle-build-file/4343/2也许将其包含在您的答案中是个好主意。如果您在alt-settings.gradle中包含它,它将使--build-file--settings-file一起工作。 - MiniMe
这两个选项都被标记为已弃用,有什么替代方案吗?https://docs.gradle.org/current/userguide/command_line_interface.html#sec:environment_options - haridsv
更新了针对较新版本Gradle的答案。 - ckoidl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接