【问题标题】:How to access git branch name from pipeline job?如何从管道作业访问 git 分支名称?
【发布时间】:2018-02-02 00:40:13
【问题描述】:

我有一个 Jenkins Pipeline 作业,它被配置为检查一个 git repo 和一个特定的本地分支。

如何在我的 Jenkinsfile 中获取本地分支的名称?

我尝试加载 git jenkins plugin env 属性,但没有成功。

node {
  checkout scm
  echo "1 "+ env.GIT_LOCAL_BRANCH
  echo "2 "+ env.GIT_BRANCH
}

两个值都是“空”

【问题讨论】:

    标签: jenkins jenkins-pipeline


    【解决方案1】:

    我发现我可以从checkout scm 捕获返回值并使用它来获取分支名称(和其他值)

      def scmVars
    
      node('api-sample-build') {
        stage('Clone source code') {
            scmVars = checkout scm
            // scmVars contains the following values
            // GIT_BRANCH=origin/mybranch
            // GIT_COMMIT=fc8279a107ebaf806f2e310fce15a7a54238eb71
            // GIT_PREVIOUS_COMMIT=6f2e319a1fc82707ebaf800fce15a7a54238eb71
            // GIT_PREVIOUS_SUCCESSFUL_COMMIT=310fce159a1fc82707ebaf806f2ea7a54238eb71
            // GIT_URL=https://stash.someworkplace.com/scm/poc/api-sample.git
        }
        stage('test scope') {
          echo scmVars.GIT_BRANCH
        }
      }
    

    通过在节点外定义变量,它可以在结帐后分阶段使用。

    【讨论】:

      【解决方案2】:

      我现在使用 sh 调用来获取分支名称。这需要至少 2.4 版的管道节点和流程插件。

      def branchName = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
      echo branchName
      

      【讨论】:

      • 我尝试过同样的事情,但我得到的是 HEAD 而不是分支名称......有什么想法吗?我尝试了其他方式作为 git branch | grep * | cut ' ' -f 但一切似乎都返回 None 或 HEAD
      • @JavierPR 您可能处于分离的头部状态,无法使用此命令。 stackoverflow.com/questions/6059336 可能会有所帮助
      【解决方案3】:

      您可以使用scm 属性来获取为您的scm 配置的分支列表:

      // List of all configured branches
      def allBranches = scm.branches
      
      // Only the first configured branch name
      def gitBranch = scm.branches[0].name
      

      【讨论】:

      • org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException:脚本不允许使用方法 hudson.plugins.git.GitSCM getBranches
      • @RicardoStuven 您需要在脚本控制台中授权该方法签名。
      猜你喜欢
      • 2018-05-25
      • 2020-09-21
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 2021-01-11
      • 1970-01-01
      相关资源
      最近更新 更多