Groovy:数组的最后 5 个元素(如果存在)

0 groovy jenkins

正如您从代码中看到的,我想从数组中获取最后 5 个构建。

我问自己,如果数组中只有 4 个或 0 个构建,会发生什么情况。

我可能会得到一个空引用,并且 Jenkins 脚本将会失败。

关于如何避免这种情况并且仅使用我可以获得的构建数量(最多 5 个)有什么建议吗?

hi.getItem(projectname).getItem(jobname).getItem(branchname).getBuilds()[-5,-4,-3,-2,-1]{ build ->
            def exec = build.getExecutor()

            if (build.number != currentBuild.number && exec != null) {
            exec.interrupt(
                Result.ABORTED,
                new CauseOfInterruption.UserInterruption(
                "Aborted by #${currentBuild.number}"
                )
            )
            println("Aborted previous running build #${build.number}")
            } else {
            println("Build is not running or is current build, not aborting - #${build.number}")
            }
        }
Run Code Online (Sandbox Code Playgroud)

cfr*_*ick 5

用于builds.takeRight(5)获取最多5 个最右边的元素