如何解析 "git ls-remote --tags" 以获取 Jenkins 管道中的实际标签?

How to parse "git ls-remote --tags" to get the actual tags in Jenkins pipeline?

我想在我的 Jenkins 管道中的 Git 远程获取实际标签。到目前为止我有

node("node1") {
  def tags = null
  stage("Get tags") {
    sshagent(["my-ssh-key"]) {
      tags = sh(script: "git ls-remote --tags origin",
                returnStdout: true)
    }
    println tags
  }
}

我得到了,如预期的那样

ad10e315b9be0503727e4f787ee5779caed1be0f    refs/tags/st-2021-12-15-6
40e642c746852298513e80d4f778febf99578d64    refs/tags/st-2021-12-15-6^{}
64d64e515fd3a745e3119c5d318b242b1cfc3cef    refs/tags/st-2021-12-15-7
63ff8407af9ecf38b6cb38ed7479fd1aab88dc8e    refs/tags/st-2021-12-15-7^{}
56be4e5a1e131c56dcca4ae1ccf19cb542ad7590    refs/tags/st-2021-12-15-8
93b6cbdfa2bb95231a39b5407eb446bcaf7a7931    refs/tags/st-2021-12-15-8^{}
43d85ec58628e390296ec473ea982671be235759    refs/tags/st-2021-12-16-4
96fb5e45590957a3df14402362f3e7bcef839f67    refs/tags/st-2021-12-16-4^{}

然而,tags 似乎只是一个长字符串,而不是像我预期的那样由 CR ("/n") 分隔的多行。我知道因为我能做到

println tags.split("/n").size()
1

即使用空格分割也行不通

println tags.split(" ").size()
1

那么如何解析输出以获取标签?

tags.readLines()

tags 此时应该有 java.lang.String 类型

你可以通过println tags.getClass()

查看

https://docs.groovy-lang.org/docs/latest/html/groovy-jdk/java/lang/String.html

String 继承了 CharSequence 的方法,它有方法 readLines

https://docs.groovy-lang.org/docs/latest/html/groovy-jdk/java/lang/CharSequence.html#readLines()


顺便说一句:您可以使用 split,但 readLines 会处理 windows (\r\n) 和 linux (\n) 换行符。

tags.split("\n").size()