首页 文章

Jenkins:groovy DSL:使用三元运算符来区分FreeStyleJob和MatrixJob

提问于
浏览
2

我正在尝试为Jenkins编写一个groovy-dsl脚本来生成两个作业:

  • 第一份工作是FreestyleJob

  • 第二个是MatrixJob

他们的定义几乎相同;他们之间只有细微的差别 . 因此,我想重用大部分作业代码,然后我进入了以下重构场景( please focus in the fifth line, in the ternary operator ):

[
    ['toolchainsBuild': false],
    ['toolchainsBuild': true],
].each { Map config ->
    config.toolchainsBuild ? job("job1") : matrixJob("job2") {
        // job definition follows...for example:
        out.println("debug")
        steps {
            cmake {
                buildToolStep {}
            }
        }
        // if (config.toolchainsBuild) {
        //     ... // different actions, depending on the job type
        // }
    }
}

但是,这不起作用 . 证明: debug 只在日志文件中打印一次(它应该出现两次,因为我想要定义两个不同的作业) .

我还尝试将三元运算符及其操作数包装在括号中,如下所示:

(config.toolchainsBuild ? job("job1") : matrixJob("job2")) {
// ...

但是,这会导致语法错误:

Processing provided DSL script
ERROR: (script, line 20) No signature of method: javaposse.jobdsl.dsl.jobs.MatrixJob.call() is applicable for argument types: (script$_run_closure1$_closure2) values: [script$_run_closure1$_closure2@2cb2656f]
Possible solutions: wait(), label(), any(), wait(long), label(java.lang.String), each(groovy.lang.Closure)
Started calculate disk usage of build
Finished Calculation of disk usage of build in 0 seconds
Started calculate disk usage of workspace
Finished Calculation of disk usage of workspace in 0 seconds
Notifying upstream projects of job completion
Finished: FAILURE

How can I rewrite the above expression to produce two different jobs, depending on the value of the boolean?

我认为这个问题与三元运算符的闭包使用有关,也许它不是以这种方式使用的?

1 回答

  • 2

    我设法以这种方式解决它:

    def jobInstance = !config.toolchainsBuild ? job("job1") : matrixJob("job2")
    
    jobInstance.with {
        // ... job definition follows
    }
    

    即,使用 with 方法 . 这样,闭包只写了一次 .

相关问题