首页 > 解决方案 > 如何在 Jenkins Groovy 中为分支创建数组

问题描述

如何在 git branch -r 之后创建一个数组。我的目标是我想删除/清理所有超过 2 个月的分支。

所以我的詹金斯脚本看起来像这样:


pipeline {
    agent { label "base" }
    
    

    stages {
        stage('Get All Branches') {
            steps{
                withCredentials([usernamePassword(credentialsId: "${config.git.credentialsId}", usernameVariable: 'GITUSER', passwordVariable: 'GITPASSWD')]) {
                //      test -d "./.git" && git fetch || git clone -n http://$GITUSER:$GITPASSWD@${srcurl} .
                sh """
                    test -d "./.git" && git fetch || git clone -n gitRepo .
                    git branch -r --sort=-committerdate > .git/branchesList
                """
               
                }    
                
            }
        }
        
        stage('show branches'){
            steps{
                 branchesList = readFile(".git/branchesList").trim()
                    echo branchesList // this line I want to get all branches

             // the Question is How to create an Array from branchesList
            }
        }

       
    }
}


Any solutions?

标签: jenkinsjenkins-pipelinejenkins-groovy

解决方案


您可以在 Jenkins 中使用 : 读取文件readFile(file: '<Filepath>')

stage('show branches'){
            steps{
                 // Define Array containing branches
                  def BRANCHES = []
                 // Give your path of file. Please change the path according to your requirements

                 def branchesList = readFile(file: 'C:\\Data\\.git\\branchesList.txt')

                 // I assumed your file contains one branch per line, that is why i split with "\n".
                 // You can change this line as per your condition

                 BRANCHES = branchesList.split("\n")                 

                 for (branch in BRANCHES){
                          println ("Branch is : ${branch}") 
                       }
            }


推荐阅读