How to get the git latest commit message and prevent the jenkins build if the commit message contains [ci skip]?

若如初见. 提交于 2019-12-17 18:34:54

问题


I tried to get the git commit message in jenkinsfile and prevent the build based on commit message.

env.GIT_COMMIT doesn't return the commit details in jenkinsfile.

How to get the git latest commit message and prevent the jenkins build if the commit message contains [ci skip] in it?


回答1:


The build will pass when [ci skip] is provided in the last git log, but will not run the actual build code (the replacement to the first echo statement)

node {
  checkout scm
  result = sh (script: "git log -1 | grep '\\[ci skip\\]'", returnStatus: true) 
  if (result != 0) {
    echo "performing build..."
  } else {
    echo "not running..."
  }
}



回答2:


I had the same issue. I'm using pipelines. I solved this issue by implementing a shared library.

The code of the library is this:

// vars/ciSkip.groovy

def call(Map args) {
    if (args.action == 'check') {
        return check()
    }
    if (args.action == 'postProcess') {
        return postProcess()
    }
    error 'ciSkip has been called without valid arguments'
}

def check() {
    env.CI_SKIP = "false"
    result = sh (script: "git log -1 | grep '.*\\[ci skip\\].*'", returnStatus: true)
    if (result == 0) {
        env.CI_SKIP = "true"
        error "'[ci skip]' found in git commit message. Aborting."
    }
}

def postProcess() {
    if (env.CI_SKIP == "true") {
        currentBuild.result = 'NOT_BUILT'
    }
}

Then, in my Jenkinsfile:

pipeline {
  stages {
    stage('prepare') { steps { ciSkip action: 'check' } }
    // other stages here ...
  }
  post { always { ciSkip action: 'postProcess' } }
}

As you can see, the build is marked as NOT_BUILT. You can change it to ABORTED if you prefer, but it cannot be set to SUCCESS because a build result can only get worse




回答3:


I think you could easily do that in multi branch pipeline job configuration Branch Sources > Additional Behaviours > Polling ignores commits with certain messages




回答4:


As for declarative pipeline one can use 'changelog' in 'when' directive to skip a stage:

when {
    not {
    changelog '.*^\\[ci skip\\] .+$'
    }
}

See: https://jenkins.io/doc/book/pipeline/syntax/#when




回答5:


As of today, it's quite easy to achieve. The interesting line is the extension named MessageExclusion where excludedMessage accepts a regular expression.

checkout([ $class: 'GitSCM', 
  branches: [[name: '*/master']], 
  doGenerateSubmoduleConfigurations: false, 
  extensions: [[
    $class: 'MessageExclusion', excludedMessage: '.*skip-?ci.*'
  ]], 
  submoduleCfg: [], 
  userRemoteConfigs: [[
    credentialsId: 'xxx', url: 'git@github.com:$ORG/$REPO.git'
  ]]
])


来源:https://stackoverflow.com/questions/41140255/how-to-get-the-git-latest-commit-message-and-prevent-the-jenkins-build-if-the-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!