jenkins 如何打印当前分支(并行分支的)分支

tyky79it  于 2023-01-25  发布在  Jenkins
关注(0)|答案(1)|浏览(286)

我得到了列出管道的所有分支和阶段的代码

def build_jobs = [:]
build_jobs['1'] = {
    node('builder'){
        stage('A'){
            sh 'echo 1'
            printMyStage()
        }
        stage('B'){
           printMyStage()
           "error"
        }
    }
}
build_jobs['2'] = {
    node('builder'){
        printMyStage()
        sh 'echo 2'
    }
}
build_jobs['3'] = {
    node('builder'){
        stage('A'){
            printMyStage()
            sh 'echo 3'
        }
        stage('B'){
            printMyStage()
        }
    }
}
parallel build_jobs

在运行开始时,我得到以下指纹:

[Pipeline] parallel
[Pipeline] { (Branch: 1)
[Pipeline] { (Branch: 2)
[Pipeline] { (Branch: 3)

如何访问具有分支名称的变量,以便printMyStage()函数打印它运行的分支?
对于当前代码,输出为:

Branch: 1
Branch: 1
Branch: 2
Branch: 3
Branch: 3

我还尝试使用PipelineNodeGraphVisitor(currentBuild.rawBuild),但没有成功

6ljaweal

6ljaweal1#

您可以通过未记录的CpsThread.current().head获取当前线程的 headFlowNode。使用FlowNode.getEnclosingBlocks()可以获取父块,并在某些条件下确定分支节点。
包含嵌套parallel分支的完整脚本化管道示例:

import org.jenkinsci.plugins.workflow.cps.CpsThread
import org.jenkinsci.plugins.workflow.graph.FlowNode
import org.jenkinsci.plugins.workflow.actions.LabelAction
import org.jenkinsci.plugins.workflow.actions.ThreadNameAction

node {
    def build_jobs = [:]
    
    build_jobs['1'] = {
        stage('A'){
            printMyStage('#1.A')
        }
        stage('B'){
           printMyStage('#1.B')
        }
    }
    build_jobs['2'] = {
        
        def nestedParallel = [:]
        
        nestedParallel['3'] = {
            stage('A') {
                printMyStage('#3.A')
            }            
        }
        nestedParallel['4'] = {
            stage('A'){
                printMyStage('#4.A')
            }
            stage('B'){
                printMyStage('#4.B')
            }
        }
        
        parallel nestedParallel
    }
    
    parallel build_jobs
}

// Get list of enclosing branches from "parallel" statement for given FlowNode
@NonCPS
List<FlowNode> getEnclosingBranches(FlowNode node) {
    List<FlowNode> enclosingBlocks = new ArrayList<>()
    for (FlowNode enclosing : node.getEnclosingBlocks()) {
        if (enclosing != null && enclosing.getAction(LabelAction.class) != null) {
            if (enclosing.getAction(ThreadNameAction.class) != null) {
                enclosingBlocks.add(enclosing)
            }
        }
    }

    return enclosingBlocks
}

// Print current branch name(s)
void printMyStage( String prefix ) {
    def branches = getEnclosingBranches( CpsThread.current().head.get() )
    if( branches ) {
        echo "$prefix ${branches.displayName}"
    }
}

输出(由于并行性,顺序是随机的):

#1.A [Branch: 1]
#3.A [Branch: 3, Branch: 2]
#4.A [Branch: 4, Branch: 2]
#1.B [Branch: 1]
#4.B [Branch: 4, Branch: 2]

函数printMyStage()列出所有父分支的名称,如果只需要直接父分支,则使用branches[0].displayName

相关问题