Jenkinsfile - get all changes between builds

后端 未结 2 1183
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-06 00:01

With reference to this question is there a way to get the equivalent information from when using the mult-branch pipeline? Specifically - the list of commits since the last succ

2条回答
  •  爱一瞬间的悲伤
    2021-02-06 00:20

    I have found a solution that seems to work for us. It revolves around getting the currentBuild commit hash and then the lastSuccessfulBuild commit hash. First we wrote a utility method for getting a commit hash of a given Jenkins build object:

    def commitHashForBuild(build) {
      def scmAction = build?.actions.find { action -> action instanceof jenkins.scm.api.SCMRevisionAction }
      return scmAction?.revision?.hash
    }
    

    then use that to get the lastSuccessfulBuild's hash:

    def getLastSuccessfulCommit() {
      def lastSuccessfulHash = null
      def lastSuccessfulBuild = currentBuild.rawBuild.getPreviousSuccessfulBuild()
      if ( lastSuccessfulBuild ) {
        lastSuccessfulHash = commitHashForBuild(lastSuccessfulBuild)
      }
      return lastSuccessfulHash
    }
    

    finally combine those two in a sh function to get the list of commits

      def lastSuccessfulCommit = getLastSuccessfulCommit()
      def currentCommit = commitHashForBuild(currentBuild.rawBuild)
      if (lastSuccessfulCommit) {
        commits = sh(
          script: "git rev-list $currentCommit \"^$lastSuccessfulCommit\"",
          returnStdout: true
        ).split('\n')
        println "Commits are: $commits"
      }
    

    you can then use the commits array to query various things in Git as your build requires. E.g. you can use this data to get a list of all changed files since the last successful build.

    I have put this into a complete example Jenkinsfile Gist to show how it fits together in context.

    A possible improvement would be to use a Java/Groovy native Git library instead of shelling out to a sh step.

提交回复
热议问题