@NonCPS
def getChangeString() {
    MAX_MSG_LEN = 100
    def changeString = ""
    echo "Gathering SCM changes"
    def changeLogSets = currentBuild.changeSets
    for (int i = 0; i < changeLogSets.size(); i++) {
        def entries = changeLogSets[i].items
        for (int j = 0; j < entries.length; j++) {
            def entry = entries[j]
            truncated_msg = entry.msg.take(MAX_MSG_LEN)
            changeString += " - ${truncated_msg} [${entry.author}]\n"
        }
    }
    if (!changeString) {
        changeString = " - No new changes"
    }
    return changeString
}

pipeline {
  agent any
  stages {
    stage("Load Env") {
      steps {
        script {
          switch(env.BRANCH_NAME) {
            case 'development':
              env.NPM_VARS='--access restricted --tag alpha'
              break
            case "main":
              env.NPM_VARS='--access public --tag latest'
              break
            default:
              println("Branch value error: " + env.BRANCH_NAME)
              currentBuild.getRawBuild().getExecutor().interrupt(Result.FAILURE)
          }
        }
        sh 'printenv'
      }
    }

    stage('Startup') {
      steps {
        buildDiscarder(logRotator(numToKeepStr: '10', artifactNumToKeepStr: '10'))
        slackSend (channel: 'v2-build-notifications',
                  color: 'good',
                  message: "The pipeline ${currentBuild.fullDisplayName} is started. Changes:\n " + getChangeString())
        script {
          sh '''yarn install'''
        }
      }
    }
    stage('Build') {
      steps {
        sh 'yarn build'
      }
    }

    stage('Publish') {
      steps {
        withCredentials([string(credentialsId: 'NPM_TOKEN', variable: 'NPM_TOKEN')]) {
          sh '''echo //registry.npmjs.org/:_authToken=${NPM_TOKEN} > .npmrc
npm publish ${NPM_VARS}'''
        }
      }
    }
  }

  post {
      success {
          slackSend (channel: 'v2-build-notifications',
                    color: 'good',
                    message: "The pipeline ${currentBuild.fullDisplayName} is success.")
      }
      failure {
          slackSend (channel: 'v2-build-failures',
                    color: 'danger',
                    message: "The pipeline ${currentBuild.fullDisplayName} failed.")
      }
      fixed {
          slackSend (channel: 'v2-build-failures',
                    color: 'good',
                    message: "The pipeline ${currentBuild.fullDisplayName} back to normal.")
      }
  }
  triggers {
    pollSCM('* * * * *')
  }
  options { disableConcurrentBuilds() }
}
