How to access git branch name from pipeline job?

独自空忆成欢 提交于 2019-12-05 05:24:10

I found that I can capture the return value from checkout scm and use that to get the branch name (and other values)

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

By defining the variable outside the node it is available in stages after the checkout.

Jotschi

I'm now using the sh call to get the branch name. This requires at least version 2.4 of the Pipeline Nodes and Processes Plugin.

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

You can use scm attributes to get the list of branches configured for your scm :

// List of all configured branches
def allBranches = scm.branches

// Only the first configured branch name
def gitBranch = scm.branches[0].name
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!