Jenkins groovy - How to retrieve tag from latest commit?

半城伤御伤魂 提交于 2020-01-24 13:15:31

问题


To fetch the latest commit from branchName, we run below code:

treeMapData = git(branch: branchName, credentialsId: credential, url: "${gitLabServer}/${projectName}/${repo}.git")

It is ensured that there is one tag per commit, as per our workflow

We want to build the code, only if the commit is tagged.


How to retrieve the tag name for that latest commit?


回答1:


We can fetch the tags from the repo in case Jenkins hasn't already.

git fetch --tags

We need to find a tag(s) which point to a specific commit or HEAD in our case. Thankfully there is a handy command in git which allows us to do this.

git tag --points-at HEAD

Using awk we can turn this into an output which groovy can falsify.

awk NF

So we, first we check if the pushed branch is master

if (env.BRANCH_NAME == 'master') {

lock it down

  lock('publish master') {

execute the git tag shell script and assign it to TAG

    TAG = sh (
      returnStdout: true,
      script: 'git fetch --tags && git tag --points-at HEAD | awk NF'
    ).trim()

if a tag exists, do something!

    if (TAG) {
      stage('Deploy Prod') {
        echo "Deploying to Prod ${TAG}"
      }
    }

Hopefully this answers your question, or at the very least will get you on the right track.



来源:https://stackoverflow.com/questions/54949432/jenkins-groovy-how-to-retrieve-tag-from-latest-commit

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