问题
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