【问题标题】:How to read Maven repository credentials only when needed?如何仅在需要时读取 Maven 存储库凭据?
【发布时间】:2020-07-24 10:24:51
【问题描述】:

我有一个 Gradle Kotlin DSL 脚本,可以将一些工件发布到本地 Maven 存储库:

    publishing {
        publications {
            create<MavenPublication>("maven") {
                groupId = "my.company"
                artifactId = project.name
                version = "0.0.1"
                from(components["java"])
            }
        }
        repositories {
            maven {
                url = uri("https://maven.mycompany.com/content/repositories/whatever")
                credentials {
                    username = (read from some file)
                    password = (read from some file)
                }
            }
        }
    }

如您所见,Gradle 将总是尝试从文件中读取用户名和密码。即使发布任务不会被执行。

我试图通过将凭据移动到发布任务中的 doFirst 块来修复它,但代码根本就不会执行:

publishing {
  doFirst { // this doesn't compile, doFirst doesn't exist here 
  }
}
tasks.getByName("publish").doFirst {
  // this compiles just fine, but it's never executed
}
tasks.named("publish") {
  doFirst {
    // this compiles just fine, but it's never executed
  }
}

如何设置凭据以使其仅在执行发布任务时发生?

【问题讨论】:

    标签: kotlin gradle maven-publish


    【解决方案1】:

    无论是否需要,您总是在配置凭据。您需要有条件地配置凭据。这可以通过多种方式实现。

    例如,假设您不想发布快照版本。您的构建可能类似于:

    version = "0.0.1-SNAPSHOT"
    
    publishing {
        publications {
            create<MavenPublication>("maven") {
                from(components["java"])
            }
            repositories {
                maven {
                    url = uri("https://maven.mycompany.com/content/repositories/whatever")
                    if (!version.toString().contains("SNAPSHOT")) {
                        credentials {
                            username = property("username") as String
                            password = property("password") as String
                        }
                    }
                }
            }
        }
    }
    

    注意条件。在configuration 阶段,Gradle 将评估该条件并跳过credentials { },因为版本包含SNAPSHOT

    正如我所说,您可以通过多种方式完成上述操作。但是,最好的方法是使用环境变量:

    publishing {
        publications {
            create<MavenPublication>("maven") {
                from(components["java"])
            }
            repositories {
                maven {
                    url = uri("https://maven.mycompany.com/content/repositories/whatever")
                    credentials {
                        username = System.getenv()["username"]
                        password = System.getenv()["password"]
                    }
                }
            }
        }
    }
    

    没有任何条件。 null 是凭据的可接受值,在配置阶段无关紧要。唯一重要的是您何时会收到NullPointerException

    【讨论】:

    • 我结合了您的两个建议:使用环境变量切换读取凭据的条件,以及将凭据本身作为项目变量读取(来自我的加密主文件夹中的 gradle.properties 文件)。
    猜你喜欢
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    相关资源
    最近更新 更多