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

Time:12-18

I want to get the actual tags in my Git remote in my Jenkins pipeline. So far I have

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

and I get, as expected

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^{}

However, tags just seems to be one long string, instead of multiple lines delimited by CR ("/n") like I expected. I know because I can do

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

Even a splitting with spaces doesn't work

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

So how can I parse output to get the tags?

CodePudding user response:

tags.readLines()

tags should have java.lang.String type at this point

you could check it by println tags.getClass()

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

String inherits methods from CharSequence and it has method readLines

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


btw: you could use split but readLines takes care of windows (\r\n) and linux (\n) line breaks.

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