如何在JenkinsGroovy中为分支创建Array



如何在git分支-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?

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

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}") 
}
}