Jenkinsfile 是纯 Groovy 吗? Jenkinsfile 的“steps”中使用了什么 Groovy 语言结构?

Is a Jenkinsfile in pure Groovy? What Groovy language construct is used in `steps` in a Jenkinsfile?

Jenkinsfile 中的以下代码片段使用了什么 Groovy 语言构造、语法或控制结构?

stage('Stage 1') {
    steps {
        // One or more steps
    }
}

即就纯 Groovy 语言而言,Jenkinsfile 中的块是什么?

什么是 'steps'?或 stage? 是调用函数吗?或定义?或带有匿名 (lambda) 参数的函数调用?

这个问题的内在是另一个问题:

问题 2:

是Jenkinsfile,groovy语言的代码片段吗?

换句话说,1. Jenkinsfile 是否遵循纯 Groovy 的所有语法和控制结构? (也许通过隐式库 import-ed 或 #include d 在开始时默默地),

与成为 DSL 相反:2. Jenkinsfile 几乎是一个 groovy 源文件,增加了新的 Jenkins-specific 结构,而不是最初在 Groovy 中,例如Jenkins 使用预处理。

以上两个哪个成立?

相关:

在 Jenkins(或 Gradle)中使用了 2 个主要功能:

  1. Groovy (java) 循环、开关、命令链等惯用结构
  2. 基于 Closure 的 DSLBuilder 工具允许嵌套和调用特定领域的方法,因为它们是 Groovy 本身的一部分。

所以,如果你写这样的东西

stage('Stage 1') {
    steps {
        // One or more steps
    }
}

它在内部大致翻译为:

jenkinsContext.stage('Stage 1') {
    jenkinsContext.steps {
        // One or more steps
    }
}

所以写和读起来更清晰。这里的闭包 - {...} 块 - 代表代码的嵌套或分组。

在此块中,您还可以看到 Groovy 调用方法的方式,其中最后一个参数是闭包。上面的代码可以重写为:

jenkinsContext.stage 'Stage 1', { // here no brackets around args
    jenkinsContext.steps( { // here with normal java-style brackets
        // One or more steps
    } )
}

在 jenkins 中,您可以混合和匹配具有 Groovy 结构的 DSL 调用:

[ 'Stage 1', 'Stage 2' ].each{
  stage( it ) {}
}

甚至动态生成您的 DSL 名称:

[ 'Stage 1':'stage', 'step 2':'steps' ].each{ value, name ->
  "$name"( value ) {}
}

将创建 DSL(仅作为示例!):

  stage( 'Stage 1') {}
  steps( 'Step 2' ) {}

因此,Jenkins 管道语法是 Groovy + Jenkins DSL

看起来主要是 Groovy,所以如果您正在寻找简单的语法高亮,添加如下内容即可。

<!-- language: lang-groovy -->

但在线文档中记录了一些注意事项,所以这可能意味着它不是以纯 groovy 形式编写的,而是以某种 specialized/constrained 形式编写的?

The basic statements and expressions which are valid in Declarative Pipeline follow the same rules as Groovy’s syntax with the following exceptions:

  • The top-level of the Pipeline must be a block, specifically: pipeline { }.

  • No semicolons as statement separators. Each statement has to be on its own line.

  • Blocks must only consist of Sections, Directives, Steps, or assignment statements.

  • A property reference statement is treated as a no-argument method invocation. So, for example, input is treated as input().

https://www.jenkins.io/doc/book/pipeline/syntax/#declarative-pipeline