Groovy DSL比较字符串

时间:2020-08-31 16:08:21

标签: groovy jenkins-job-dsl

我正在尝试将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*)":
           
}

有一些失败,不是很清楚wrt groovy dsl的语法,而是希望dsl脚本识别这两行。请建议,谢谢!

1 个答案:

答案 0 :(得分: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获得代表当前行的String),同时将上一次迭代的结果保留在last变量中。这非常有用,因为我们可以保存在选项行上创建的目录,以便可以在url行上使用它。交换机正在使用正则表达式匹配。

相关问题