Groovy web console

subscribe to the feed Subscribe
to this
site

Untitled

Published 3 months ago by Anonymous
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
// Jenkinsfile
post { always { handlePost() } }

// shared-library/vars/handlePost.groovy
def call() {
  PostHandler postHandler = new PostHandler(this)
  postHandler.getPostResults()
}
// shared-library/src/PostHandler.groovy
class PostHandler implements Serializable {
  def jenkins
  def POST_RESULTS = []

  PostHandler() throws  Exception {
    throw new Exception(Constants.EMPTY_CONSTRUCTOR)
  }

  PostHandler(jenkins) {
    this.jenkins = jenkins
  }

  def getPostResults() {
    setPostResults()
    jenkins.echo(POST_RESULTS.toString()) //TODO - remove this print out
    return POST_RESULTS
  }

  private def setPostResults() {
    final String currentBuildResult = jenkins.currentBuild.currentResult
    final String previousBuildResult = jenkins.currentBuild.previousBuild?.result

    final BuildResult currentBuildEnum = BuildResult.valueOf(currentBuildResult)
    final BuildResult previousBuildEnum = previousBuildResult != null ? BuildResult.valueOf(previousBuildResult) : null

    POST_RESULTS.add(currentBuildEnum)

    if(currentBuildResult != previousBuildResult) {
      POST_RESULTS.add(BuildResult.CHANGED)
    }

    final BuildResult SUCCESS = BuildResult.SUCCESS
    if (currentBuildEnum == SUCCESS && previousBuildEnum != SUCCESS) {
      POST_RESULTS.add(BuildResult.FIXED)
    } else if (previousBuildEnum == SUCCESS && currentBuildEnum != SUCCESS) {
      POST_RESULTS.add(BuildResult.REGRESSION)
    }
  }

  enum BuildResult {
    ABORTED,
    CHANGED,
    FAILURE,
    FIXED,
    REGRESSION,
    SUCCESS,
    UNSTABLE
  }
}