对于Maven存储库凭据,buildscript中的Gradle变量为null

时间:2019-02-05 22:14:53

标签: gradle groovy

对于上下文,我的最终目标是通过环境变量或使用Maven settings.xml注入用于buildscript插件的Maven凭据。

我创建了这个buildscript闭包以获取信誉:

buildscript {
  ext.nexusCreds = {
    def id = "releases"
    def username = System.getenv("NEXUS_USER")
    def password = System.getenv("NEXUS_PASSWORD")

    if (!(username && password && username.trim() && password.trim())) {
      File mavenSettings = new File("${System.properties['user.home']}/.m2/settings.xml")
      if (mavenSettings.exists()) {
        def xmlSlurper = new XmlSlurper()
        def settings = xmlSlurper.parse(mavenSettings)
        username = settings.servers.children().find { it.id == id }.username
        password = settings.servers.children().find { it.id == id }.password
      }
    }

    println("Username: $username")
    println("Password: $password")
    [username: username, password: password]
  }()
  repositories {
    mavenLocal()
    maven {
      url "http://nexus.ourStagingEnv.com/content/repositories/releases/"
      credentials {
        username nexusCreds.username
        password nexusCreds.password
      }
    }
    jcenter()
    mavenCentral()
  }
  dependencies {
    classpath group: 'com.myPlugin', name: 'myPlugin', version: '1.0.0'
  }
}

问题是,当构建到达自定义“ maven”关闭时,似乎认为“用户名”为空:

A problem occurred evaluating root project 'myProject'.
> Could not find method username() for arguments [deployment] on Credentials [username: null] of type org.gradle.internal.credentials.DefaultPasswordCredentials_Decorated.

请注意,“ username”和“ password”变量都在“ nexusCreds”闭包中打印为非空(我在settings.xml中设置了这些变量)。

这是奇怪的部分: 如果我在“ nexusCreds”闭包中对这些值进行硬编码,则一切正常。

ext.nexusCreds = {
    def id = "releases"
    def username = System.getenv("NEXUS_USER")
    def password = System.getenv("NEXUS_PASSWORD")

    if (!(username && password && username.trim() && password.trim())) {
      File mavenSettings = new File("${System.properties['user.home']}/.m2/settings.xml")
      if (mavenSettings.exists()) {
        def xmlSlurper = new XmlSlurper()
        def settings = xmlSlurper.parse(mavenSettings)
        username = settings.servers.children().find { it.id == id }.username
        password = settings.servers.children().find { it.id == id }.password
      }
    }

    username = "myUsername"
    password = "myPassword"
    println("Username: $username")
    println("Password: $password")
    [username: username, password: password]
  }()

为什么第一个代码块失败,但对其进行硬编码有效?在这些闭包周围的Groovy或Gradle行为方面我缺少什么吗?

1 个答案:

答案 0 :(得分:0)

哦!找到了问题。事实证明,这是我的settings.xml解析中的问题。用户名和密码是XML节点,而不是字符串。解决方法是:

username = settings.servers.children().find { it.id == id }.username.toString()
password = settings.servers.children().find { it.id == id }.password.toString()