对于 Maven 存储库凭据,buildscript 中的 Gradle 变量为空
Posted
技术标签:
【中文标题】对于 Maven 存储库凭据,buildscript 中的 Gradle 变量为空【英文标题】:Gradle variable in buildscript is null for Maven repository credentials 【发布时间】:2019-02-05 22:14:53 【问题描述】:就上下文而言,我的最终目标是通过环境变量或使用 Maven settings.xml 注入用于构建脚本插件的 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”闭包时,它似乎认为“username”为空:
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.
请注意,“用户名”和“密码”变量都在“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】:哦。发现问题。原来是我的settings.xml解析有问题。用户名和密码是 XML 节点,而不是字符串。解决方法是:
username = settings.servers.children().find it.id == id .username.toString()
password = settings.servers.children().find it.id == id .password.toString()
【讨论】:
以上是关于对于 Maven 存储库凭据,buildscript 中的 Gradle 变量为空的主要内容,如果未能解决你的问题,请参考以下文章
Maven:尝试使用 settings.xml 文件中的凭据进行部署
带有 git 存储库的 Maven 发布插件忽略 scm.user scm.password