user2656732
user2656732

Reputation:

Groovy: Last 5 elements of array if they exist

As you can see from the code I want to get the last 5 builds from the array.

I ask myself what will happen in case there are are only 4 or 0 builds in the array.

I probably will get a null reference and the Jenkins script will fail.

Any proposal on how to avoid this and only work with the number of builds that I can get (max of 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}")
            }
        }

Upvotes: 0

Views: 827

Answers (1)

cfrick
cfrick

Reputation: 37008

Use builds.takeRight(5) to get up to 5 rightmost elements

Upvotes: 6

Related Questions