Jenkinsfile - 获取构建之间的所有更改

问题描述 投票:4回答:2

参考this question有没有办法从使用多分支管道获取等效信息?特别是 - 自上次成功构建以来的提交列表。

目前我们使用以下内容

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

但是,如果多次提交被推送,这只会返回触发构建的最后一次提交。我接受新分支的第一个构建可能是模棱两可的,但是在可能的情况下获得触发构建的提交列表将非常有用。

jenkins jenkins-pipeline
2个回答
8
投票

我找到了一个似乎对我们有用的解决方案。它围绕着获取currentBuild提交哈希,然后是lastSuccessfulBuild提交哈希。首先,我们编写了一个实用程序方法,用于获取给定Jenkins构建对象的提交哈希:

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

然后使用它来获取lastSuccessfulBuild的哈希:

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

最后将这两个组合在一个sh函数中以获取提交列表

  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"
  }

然后你可以使用commits数组在你的构建需要的Git中查询各种东西。例如。您可以使用此数据获取自上次成功构建以来所有已更改文件的列表。

我把它放到一个完整的example Jenkinsfile要点中,以展示它如何在上下文中融合在一起。

可能的改进是使用Java / Groovy本机Git库而不是shelling到sh步骤。


1
投票

我认为Jenkins Last change插件可以提供您需要的信息,请看一下:https://wiki.jenkins-ci.org/display/JENKINS/Last+Changes+Plugin,以下是一个例子:

node {
      stage("checkout") {
        git url: 'https://github.com/jenkinsci/last-changes-plugin.git'
      }

      stage("last-changes") {
        def publisher = LastChanges.getLastChangesPublisher "LAST_SUCCESSFUL_BUILD", "SIDE", "LINE", true, true, "", "", "", "", ""
              publisher.publishLastChanges()
              def changes = publisher.getLastChanges()
              println(changes.getEscapedDiff())
              for (commit in changes.getCommits()) {
                  println(commit)
                  def commitInfo = commit.getCommitInfo()
                  println(commitInfo)
                  println(commitInfo.getCommitMessage())
                  println(commit.getChanges())
              }
      }

}

请注意,默认情况下(不需要groovy脚本),插件会在jenkins UI see here上提供可供浏览的提交列表。

我希望它有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.