【问题标题】:How does this jenkins groovy script work?这个詹金斯 groovy 脚本是如何工作的?
【发布时间】:2020-11-24 16:33:48
【问题描述】:

这是我在 Jenkins 上的 groovy 脚本

def gitURL = "http://bitbucket.webapp.intern.de/scm/myproject.git"
def command = "git ls-remote -h $gitURL"

def proc = command.execute()  // line 3
proc.waitFor()              

if ( proc.exitValue() != 0 ) {
   println "Error, ${proc.err.text}"
   System.exit(-1)
}

def branches = proc.in.text.readLines().collect {    // line 9
    it.replaceAll(/[a-z0-9]*\trefs\/heads\//, '')    // line 10
}

return branches

首先我什么都不懂。如何在第 3 行调用执行应该是字符串的命令??

第 9 行的变量分支是什么类型??? 分支是字符串吗??

第 10 行的 it.replaceAll 是什么???我知道 replaceAll 是 String 中的方法。但它有2个参数。 我在这里没有看到 2 个参数。

现在我以某种方式理解分支包含所有分支。我想做的事。我只想拥有 包含“-REST”的分支是它们的名字。我该怎么做??

我的意图是使用 java。但它不起作用。

List<String> branchesNew = new ArrayList<String>();

for(String branch : branchesNew)
{
     if(branch.contains("-REST"))
            branchesNew.add(branch);
}

【问题讨论】:

  • 别担心,如果您使用 Groovy 的第一个方法有点令人沮丧。我认为这是一种普遍的感觉。 :) 恕我直言,您可以执行以下操作:阅读 groovy-lang.org 上的官方文档,在本地安装 groovy 并使用 groovish 测试您的单个命令(类似于 java 中的 jshell),使用您自己的 Playground Jenkins 项目测试您的代码(不是每个 groovy由于几个原因,脚本在 Jenkins 中开箱即用)。

标签: jenkins groovy


【解决方案1】:

第 3 行:这是一个 Groovy 功能​​,请参阅 http://groovy-lang.org/groovy-dev-kit.html#process-management

第 9 行:它是一个集合(例如一个列表),作为 collect 方法的输出给出。另见http://groovy-lang.org/groovy-dev-kit.html#_working_with_collections

第 10 行:第二个参数是 ''。它将正则表达式匹配(分支前缀)替换为空字符串。

您可以使用集合上的findAll 方法过滤所有想要的分支。按照给定的示例:

def branchesNew = proc.in.text.readLines().findAll{ it.contains('-REST') }

查看Filtering and searching 了解所有相关操作方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    相关资源
    最近更新 更多