Jenkins.instance.getItemByFullName(name)始终返回null

时间:2017-03-02 17:32:55

标签: git jenkins groovy jenkins-plugins

我们曾经使用groovy-script DSL清理方法的变体来清理已删除作业的任何Jenkins工作区。当相应的GitHub分支不再存在时,将删除该作业。我们使用GitHub插件并具有MultiBranch作业/工作区。

以下是我们以前使用的代码:

/*
  Delete workspaces with no jobs (for GitHubMultiBranch)
  Forked from https://gist.github.com/ceilfors/1400fd590632db1f51ca
*/

import hudson.*
import hudson.model.*
import jenkins.*
import jenkins.model.*
import jenkins.branch.*


/***************
 Main Functions
****************/

def out = new StringBuffer()
def workspaceRoot = Jenkins.instance.rootPath.child("workspace")  

def boolean isMultiBranch(String name) {
    def item = Jenkins.instance.getItemByFullName(name)
    return item in MultiBranchProject
}


/* Deletes any workspace tree that doesn't have a task.
*/
def deleteUnusedWorkspace(FilePath root, String path, Boolean dryRun) {
    root.list().each { child ->
        println "Examining " + child.name
        String fullName = path + child.name
        if (!child.name.endsWith("@tmp")) {
            // If it's a MultiBranch then recurse.
            if (isMultiBranch(fullName)) {
                deleteUnusedWorkspace(root.child(child.name), "$fullName/", dryRun)
            } else {
                // Checks if an item (job) exists.
                if (Jenkins.instance.getItemByFullName(fullName) == null) {
                    if (dryRun) {
                        println "Would Delete: $fullName "
                    } else {
                        println "Deleting: $fullName "
                        child.deleteRecursive()
                    }
                }
            }
        }
    }
}


/***************
 Debuggery
***************/

/* Outputs class names of the root items and
   whether they happen to be MultiBranch.
*/
def printClasses(FilePath root, String path) {
    out << ' Debuggery '.center(15, "*") + '\n\n'
    out << "Item Name".padRight(40)
    out << "MultiBranch?".padRight(15)
    out << "Class Name\n\n"
    root.list().each { child ->
        String fullName = path + child.name
        className = Jenkins.instance.getItemByFullName(fullName).getClass()
        multiBranch = isMultiBranch(fullName)
        out << "$child.name".padRight(40)
        out << "$multiBranch".padRight(15)
        out << "$className\n"
    }
    out << "\n\n"
}

//printClasses(workspaceRoot, "")

/***************
 Execution
***************/
println("Begin Task")
deleteUnusedWorkspace(workspaceRoot, "", false) // true = Dry-Run // false = Real
println("Task Complete\n")

由于工作空间目录现在没有嵌套(新的Jenkins部署),我们不需要递归。问题是 Jenkins.instance.getItemByFullName()方法只返回n​​ull。有什么想法吗?

0 个答案:

没有答案