Is there a way to get the current tag ( or null if there is none ) for a job in a Jenkinsfile? The background is that I only want to build some artifacts ( android APKs ) when this commit has a tag. I tried:
env.TAG_NAME
and
binding.variables.get("TAG_NAME")
both are always null - even though this ( https://issues.jenkins-ci.org/browse/JENKINS-34520 ) indicates otherwise
I'd consider returnStdout
rather than writing to a file:
sh(returnStdout: true, script: "git tag --sort version:refname | tail -1").trim()
All the other answers yield an output in any case even if HEAD is not tagged. The question was however to return the current tag and "null" if there is nothing like that.
git tag --contains
yields the tag name name if and only if HEAD is tagged.
For Jenkins Pipelines it should look like this:
sh(returnStdout: true, script: "git tag --contains").trim()
I believe the git command that does what you want is git tag --points-at=HEAD
this will list all tags pointing to the current commit or HEAD as it usually called in git. Since HEAD is also the default argument you can also do just git tag --points-at
.
The pipeline step for executing and returning the git tags one for each line, then becomes:
sh(returnStdout: true, script: "git tag --points-at")
sh "git tag --sort version:refname | tail -1 > version.tmp"
String tag = readFile 'version.tmp'
If the current build is a tag build -- as in, when { buildingTag() }
was "true" -- then the (undocumented) environment variable BRANCH_NAME
contains the name of the tag being build.
best way from site is:
git describe --tags --abbrev=0
ofcourse this is the current/latest tag in git. Independed from writeing.
sh(returnStdout: true, script: "git tag describe --tags --abbrev=0").trim()
来源:https://stackoverflow.com/questions/37488178/jenkinsfile-get-current-tag