如何隐藏gradle任务?

How to hide gradle task?

我定义了一些自定义构建任务,这些任务设置了一些配置属性并为不同的环境生成了构建。任务如下:

val buildStage by tasks.registering {
    doFirst {
        val profile = "stage"
        println("spring.profiles.active = $profile")
        System.setProperty("spring.profiles.active", profile)
        buildDir = File("${rootDir}/build/${profile}")
        tasks.withType<ProcessResources> {
            exclude("**/*.properties")
        }
    }
    finalizedBy(tasks.getByName("build"))
}

val buildProd by tasks.registering {
    doFirst {
        val profile = "prod"
        println("spring.profiles.active = $profile")
        System.setProperty("spring.profiles.active", profile)
        buildDir = File("${rootDir}/build/${profile}")
        tasks.withType<ProcessResources> {
            exclude("**/*.properties")
        }
    }

    finalizedBy(tasks.getByName("build"))
}

如何确保 gradle build 命令不可直接调用?

是否可以这样做:

tasks.getByName("build") {
    doFirst {
        if (System.getProperty("spring.profiles.active").isNullOrBlank()) {
            println("task not allowed")
            exitProcess(1)
        }
    }
}

您当前方法的问题在于,您的 build 任务的 doFirst 闭包仍将在任务 build 依赖于(例如 assembletest, jar ...), 导致 Gradle 在所有实际工作已经完成时失败。

您可以使用下面的示例检查任务 build 是否是从命令行调用的,但是所有这些禁用任务的方法都只是丑陋的技巧。

if (gradle.startParameter.taskNames.contains("build") {
    throw new GradleException("Task 'build' must not be called directly");
}

相反,您应该分析您的项目并检查哪些任务实际需要属于不同配置文件的配置属性。之后设置您的任务并使用 dependsOn / finalizedBy / mustRunAfter 以构建仅在需要时失败(因为未定义属性)并按预期运行的方式连接它们。

任务 build 是大多数 Gradle 项目的默认任务。您的方法可能会使与您的项目交互的其他开发人员感到困惑,因为调用 ./gradlew build 可能是新项目要做的第一件事。