【问题标题】:Groovy DSL to compare stringGroovy DSL 比较字符串
【发布时间】:2020-12-19 18:45:01
【问题描述】:

我正在尝试将 Job 动态加载到 Jenkins,有一个包含 Job Name 和 GHE URL 的文件:

GHE 文件网址:

options A
https://github.com/I/A/build.groovy

options B
https://github.com/I/B/build.groovy

options C
https://github.com/I/C/build.groovy

使用下面的 bash 脚本,我可以创建一个新的 Repo (A,B,C) 目录并在管道 scm 中使用 GHE URL,我如何在 groovy dsl 中实现这一点:

while read -r line; do
    case "$line" in
        options*)
            jenkins_dir=$(echo "$line" | cut -d ' ')
            mkdir -p ${jenkins_dir}
            ;;
        http://github*)
            wget -N $line -P ${jenkins_dir}
            ;;
        *)
            echo "$line"
            ;;
    esac
done < jenkins-ghe.urls

Groovy DSL 版本:

def String[] loadJobURL(String basePath) {
    def url = []
    new File('/path/to/file').eachLine { line ->
    switch("$line") {            
         
        case "options*)":
            
        case "http://github*)":
           
}

有几个失败,不太确定 groovy dsl 的语法,希望 dsl 脚本能够识别这两行。请推荐,谢谢!

【问题讨论】:

    标签: groovy jenkins-job-dsl


    【解决方案1】:

    不完全确定你想在这里完成什么,但在 groovy 中进行解析和处理的一种方法是这样的:

    new File('data.txt').readLines().inject(null) { last, line -> 
      switch(line.trim()) {
        case '':
          return last
        case ~/options.*/: 
          def dir = new File(line)
          if (!dir.mkdirs()) throw new RuntimeException("failed to create dir $dir")
          return dir
        case ~/http.*/:
          new File(last, 'data.txt').text = line.toURL().text
          return null
        default: throw new RuntimeException("invalid data at $line")
      }
    }
    

    当针对如下所示的数据文件运行时:

    options A
    https://raw.githubusercontent.com/apache/groovy/master/build.gradle
    
    options B
    https://raw.githubusercontent.com/apache/groovy/master/benchmark/bench.groovy
    
    options C
    https://raw.githubusercontent.com/apache/groovy/master/buildSrc/build.gradle
    

    创建以下目录结构:

    ─➤ tree
    .
    ├── data.txt
    ├── options A
    │   └── data.txt
    ├── options B
    │   └── data.txt
    ├── options C
    │   └── data.txt
    └── solution.groovy
    

    data.txt 文件包含从相应 url 加载的数据。

    我正在使用更高级的 inject construct 来使解析更加健壮,同时保持“功能”(即不恢复到 for 循环等)。如果不这样做,代码可能最终会更容易阅读,但它是我在阅读 groovy 集合/可迭代/列表方法时能想到的最佳选择。

    Inject 对行进行迭代,一次一个(其中line 获取表示当前行的字符串),同时将上一次迭代的结果保留在last 变量中。这很有用,因为我们可以保存在选项行上创建的目录,以便我们可以在 url 行上使用它。开关正在使用正则表达式匹配。

    【讨论】:

    • 非常感谢,这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 2017-06-08
    • 2023-03-31
    相关资源
    最近更新 更多