Git学习-->关于Jenkins编译时候,如何获取Git分支的当前分支名?
一、背景
因为代码都迁移到了Gitlab,所以Jenkins编译的时候我们都需要将之前的SVN信息换成现在的Git信息。最近编译一个Lib库的时候,因为团队规定上传Release版本的AAR到Maven的话,必须需要在Jenkins上编译而且Git Branch 必须是master分支才能够上传到Maven。
因此我们就需要在Gradle脚本中,获取Git Branch ,Git Commit等相关信息。但是在获取Git Branch的时候出现了问题,在本地Android Studio编译的时候能够获取到Git Branch的名字,但是使用Jenkins编译的时候,一直获取不到信息。
下面是我写的一份gradle文件,用于获取Git和Jenkins的相关信息
/**
* 获取Git 分支名
*/
def getGitBranch() {
return 'git symbolic-ref --short -q HEAD'.execute().text.trim()
}
/**
* 获取Git 版本号
*/
def getGitSHA() {
return 'git rev-parse --short HEAD'.execute().text.trim()
}
/**
* 获取Git Tag
*/
def getGitTag() {
return 'git describe --tags'.execute([], project.rootDir).text.trim()
}
/**
* 获取Git 提交次数
*/
def getGitCommitCount() {
return 100 + Interger.parse('git rev-list --count HEAD'.execute([], project.rootDir).text.trim())
}
/**
* 判断是否有jenkins
*/
boolean isInJenkins() {
Map<String, String> map = System.getenv()
if (map == null) {
return false
}
String str = map.get("Path")
if (str != null) {
//it's windows
return false
} else {
str = ""
Iterator it = map.iterator()
while (it.hasNext()) {
str += it.next()
}
return str.contains("jenkins")
}
}
/**
* 获取jenkins任务名
*/
def getJenkinsName() {
boolean flag = isInJenkins()
if (flag) {
ext.env = System.getenv()
ext.name = env.JOB_URL
String[] stringArray = ext.name.split("/")
if (stringArray.length > 0) {
return stringArray[stringArray.length - 1]
} else {
return "Local"
}
} else {
return "Local"
}
}
/**
* 获取Jenkins Build 号
* @return
*/
def getJenkinsBuildCode() {
boolean flag = isInJenkins()
if (flag) {
ext.env = System.getenv()
ext.buildNumber = env.BUILD_NUMBER?.toInteger()
return "$buildNumber"
} else {
return 0
}
}
/**
* 定义几个变量,在build.gradle里面引用
*/
ext {
gitTag = getGitTag()
gitBranch = getGitBranch()
gitSHA = getGitSHA()
jenkinsRevision = getJenkinsBuildCode()
jenkinsName = getJenkinsName()
}
其中的方法,getGitBranch方法在Android Studio编译的时候,能够正常获取到Git分支名。
println "pom_version_type = " + pom_version_type
println "jenkinsName = " + jenkinsName
println "gitBranch = " + gitBranch
我在进行编译的时候,是会通过如上代码打印出Git Branch的信息。
在Android Studio 本地编译的时候,是可以打印出相关的信息的。
但是在Jenkins编译的时候,是不能够上传的,如下所示:
二、解决方法
后来我尝试找了很多种方法去获取Git Branch的名字,在Android Studio本地都可以获取到,如下所示:
参考链接:https://stackoverflow.com/questions/6245570/how-to-get-the-current-branch-name-in-git
方法1、git symbolic-ref --short -q HEAD
D:\GitLab Source\XTCLint>git symbolic-ref --short -q HEAD
master
D:\GitLab Source\XTCLint>
方法2、git rev-parse --abbrev-ref HEAD
D:\GitLab Source\XTCLint>git rev-parse --abbrev-ref HEAD
master
方法3、git branch | grep \* | cut -d ' ' -f2
D:\GitLab Source\XTCLint>git branch | grep \* | cut -d ' ' -f2
master
方法4、git symbolic-ref HEAD | sed -e "s/^refs\/heads\///"
D:\GitLab Source\XTCLint>git symbolic-ref HEAD | sed -e "s/^refs\/heads\///"
master
以上所有的方法,仅仅在Android Studio的终端或者本地gradle代码中有效,然而在Jenkins服务器编译的时候都是获取为空。
后来我查看了Jenkins的Git插件上的介绍,参考链接:https://wiki.jenkins.io/display/JENKINS/Git+Plugin
如上所示,在上面的链接中有介绍,有几个Environment variables环境变量可以使用。
Environment variables
The git plugin sets several environment variables you can use in your scripts:
- GIT_COMMIT - SHA of the current
- GIT_BRANCH - Name of the remote repository (defaults to origin), followed by name of the branch currently being used, e.g. “origin/master” or “origin/foo”
- GIT_LOCAL_BRANCH - Name of the branch on Jenkins. When the “checkout to specific local branch” behavior is configured, the variable is published. If the behavior is configured as null or **, the property will contain the resulting local branch name sans the remote name.
- GIT_PREVIOUS_COMMIT - SHA of the previous built commit from the same branch (the current SHA on first build in branch)
- GIT_PREVIOUS_SUCCESSFUL_COMMIT - SHA of the previous successfully built commit from the same branch.
- GIT_URL - Repository remote URL
- GIT_URL_N - Repository remote URLs when there are more than 1 remotes, e.g. GIT_URL_1, GIT_URL_2
- GIT_AUTHOR_NAME and GIT_COMMITTER_NAME - The name entered if the “Custom user name/e-mail address” behaviour is enabled; falls back to the value entered in the Jenkins system config under “Global Config user.name Value” (if any)
- GIT_AUTHOR_EMAIL and GIT_COMMITTER_EMAIL - The email entered if the “Custom user name/e-mail address” behaviour is enabled; falls back to the value entered in the Jenkins system config under “Global Config user.email Value” (if any)
然后我将这几个变量,在一个app的Jenkins任务中,编译完成后的邮件内容中添加了这几个变量的内容,如下所示:
在构建后的操作中,Editable Email Notification的邮件通知中,将邮件内容改为如下所示的代码。
$DEFAULT_CONTENT
<br />
<font color="#0B610B">单元测试</font>
<li>Launcher单元测试报告 :<a href="${BUILD_URL}testReport">点击查看测试报告</a></li>
<li>Launcher代码覆盖率 :<a href="${BUILD_URL}jacoco">点击查看代码覆盖率</a></li>
<li>Launcher Android Lint :<a href="${BUILD_URL}androidLintResult">点击查看Android Lint</a></li>
<br />
<li>GIT_COMMIT :${GIT_COMMIT}</a></li>
<li>GIT_BRANCH :${GIT_BRANCH}</a></li>
<li>GIT_LOCAL_BRANCH :${GIT_LOCAL_BRANCH}</a></li>
<li>GIT_PREVIOUS_COMMIT :${GIT_PREVIOUS_COMMIT}</a></li>
<li>GIT_PREVIOUS_SUCCESSFUL_COMMIT :${GIT_PREVIOUS_SUCCESSFUL_COMMIT}</a></li>
<li>GIT_URL :${GIT_URL}</a></li>
<li>GIT_URL_N :${GIT_URL_N}</a></li>
<li>GIT_AUTHOR_NAME :${GIT_AUTHOR_NAME}</a></li>
<li>GIT_COMMITTER_NAME :${GIT_COMMITTER_NAME}</a></li>
<li>GIT_AUTHOR_EMAIL :${GIT_AUTHOR_EMAIL}</a></li>
<li> GIT_COMMITTER_EMAIL :${ GIT_COMMITTER_EMAIL}</a></li>
这样编译完后,收到的邮件内容如下:
如上所示,收到的邮件内容包含了Git的相关信息:
GIT_COMMIT :118fa74e6a09c8c5ae713523692add256bfa6afb
GIT_BRANCH :origin/feature/UseByAnonymousDBMigrateAndApiChange
GIT_LOCAL_BRANCH :${GIT_LOCAL_BRANCH}
GIT_PREVIOUS_COMMIT :118fa74e6a09c8c5ae713523692add256bfa6afb
GIT_PREVIOUS_SUCCESSFUL_COMMIT :118fa74e6a09c8c5ae713523692add256bfa6afb
GIT_URL :git@172.28.1.116:Android/WatchApp/Third/NetEaseCloudMusic.git
GIT_URL_N :${GIT_URL_N}
GIT_AUTHOR_NAME :${GIT_AUTHOR_NAME}
GIT_COMMITTER_NAME :${GIT_COMMITTER_NAME}
GIT_AUTHOR_EMAIL :${GIT_AUTHOR_EMAIL}
GIT_COMMITTER_EMAIL :${ GIT_COMMITTER_EMAIL}
其中,GIT_BRANCH这个环境变量的值为origin/feature/UseByAnonymousDBMigrateAndApiChange,代表Jenkins上/UseByAnonymousDBMigrateAndApiChange分支远程Gitlab上该分支映射的远程分支。因此我们可以对GIT_BRANCH这个环境变量做做文章。
将之前gradle脚本中的getGitBranch方法,做如下修改,区分编译环境是Jenkins还是本地。环境不同,运行不同的脚本获取Git Branch的名字。当处于Jenkins环境的时候,先通过GIT_BRANCH这个环境变量获取到Jenkins拉下来的分支对应的远程分支,然后通过字符串分离,获取到分支名。
/**
* 获取Git 分支名
*
*参考Jenkins git 创建文档: https://wiki.jenkins.io/display/JENKINS/Git+Plugin
* Environment variables
The git plugin sets several environment variables you can use in your scripts:
GIT_COMMIT - SHA of the current
GIT_BRANCH - Name of the remote repository (defaults to origin), followed by name of the branch currently being used, e.g. "origin/master" or "origin/foo"
GIT_LOCAL_BRANCH - Name of the branch on Jenkins. When the "checkout to specific local branch" behavior is configured, the variable is published. If the behavior is configured as null or **, the property will contain the resulting local branch name sans the remote name.
GIT_PREVIOUS_COMMIT - SHA of the previous built commit from the same branch (the current SHA on first build in branch)
GIT_PREVIOUS_SUCCESSFUL_COMMIT - SHA of the previous successfully built commit from the same branch.
GIT_URL - Repository remote URL
GIT_URL_N - Repository remote URLs when there are more than 1 remotes, e.g. GIT_URL_1, GIT_URL_2
GIT_AUTHOR_NAME and GIT_COMMITTER_NAME - The name entered if the "Custom user name/e-mail address" behaviour is enabled; falls back to the value entered in the Jenkins system config under "Global Config user.name Value" (if any)
GIT_AUTHOR_EMAIL and GIT_COMMITTER_EMAIL - The email entered if the "Custom user name/e-mail address" behaviour is enabled; falls back to the value entered in the Jenkins system config under "Global Config user.email Value" (if any)
*
*
*/
def getGitBranch() {
//判断是否处于Jenkins编译环境
boolean flag = isInJenkins()
if (flag) {
ext.env = System.getenv()
ext.gitBranch = env.GIT_BRANCH
String[] stringArray = ext.gitBranch.split("/")
if (stringArray.length > 0) {
return stringArray[stringArray.length - 1]
} else {
return "UnKnown Branch"
}
} else {
return 'git symbolic-ref --short -q HEAD'.execute().text.trim()
}
}
完整代码如下所示:
/**
* 获取Git 分支名
*
*参考Jenkins git 创建文档: https://wiki.jenkins.io/display/JENKINS/Git+Plugin
* Environment variables
The git plugin sets several environment variables you can use in your scripts:
GIT_COMMIT - SHA of the current
GIT_BRANCH - Name of the remote repository (defaults to origin), followed by name of the branch currently being used, e.g. "origin/master" or "origin/foo"
GIT_LOCAL_BRANCH - Name of the branch on Jenkins. When the "checkout to specific local branch" behavior is configured, the variable is published. If the behavior is configured as null or **, the property will contain the resulting local branch name sans the remote name.
GIT_PREVIOUS_COMMIT - SHA of the previous built commit from the same branch (the current SHA on first build in branch)
GIT_PREVIOUS_SUCCESSFUL_COMMIT - SHA of the previous successfully built commit from the same branch.
GIT_URL - Repository remote URL
GIT_URL_N - Repository remote URLs when there are more than 1 remotes, e.g. GIT_URL_1, GIT_URL_2
GIT_AUTHOR_NAME and GIT_COMMITTER_NAME - The name entered if the "Custom user name/e-mail address" behaviour is enabled; falls back to the value entered in the Jenkins system config under "Global Config user.name Value" (if any)
GIT_AUTHOR_EMAIL and GIT_COMMITTER_EMAIL - The email entered if the "Custom user name/e-mail address" behaviour is enabled; falls back to the value entered in the Jenkins system config under "Global Config user.email Value" (if any)
*
*
*/
def getGitBranch() {
//判断是否处于Jenkins编译环境
boolean flag = isInJenkins()
if (flag) {
ext.env = System.getenv()
ext.gitBranch = env.GIT_BRANCH
String[] stringArray = ext.gitBranch.split("/")
if (stringArray.length > 0) {
return stringArray[stringArray.length - 1]
} else {
return "UnKnown Branch"
}
} else {
return 'git symbolic-ref --short -q HEAD'.execute().text.trim()
}
}
/**
* 获取Git 版本号
*/
def getGitSHA() {
return 'git rev-parse --short HEAD'.execute().text.trim()
}
/**
* 获取Git Tag
*/
def getGitTag() {
return 'git describe --tags'.execute([], project.rootDir).text.trim()
}
/**
* 获取Git 提交次数
*/
def getGitCommitCount() {
return 100 + Interger.parse('git rev-list --count HEAD'.execute([], project.rootDir).text.trim())
}
/**
* 判断是否有jenkins
*/
boolean isInJenkins() {
Map<String, String> map = System.getenv()
if (map == null) {
return false
}
String str = map.get("Path")
if (str != null) {
//it's windows
return false
} else {
str = ""
Iterator it = map.iterator()
while (it.hasNext()) {
str += it.next()
}
return str.contains("jenkins")
}
}
/**
* 获取jenkins任务名
*/
def getJenkinsName() {
boolean flag = isInJenkins()
if (flag) {
ext.env = System.getenv()
ext.name = env.JOB_URL
String[] stringArray = ext.name.split("/")
if (stringArray.length > 0) {
return stringArray[stringArray.length - 1]
} else {
return "Local"
}
} else {
return "Local"
}
}
/**
* 获取Jenkins Build 号
* @return
*/
def getJenkinsBuildCode() {
boolean flag = isInJenkins()
if (flag) {
ext.env = System.getenv()
ext.buildNumber = env.BUILD_NUMBER?.toInteger()
return "$buildNumber"
} else {
return 0
}
}
/**
* 定义几个变量,在build.gradle里面引用
*/
ext {
gitTag = getGitTag()
gitBranch = getGitBranch()
gitSHA = getGitSHA()
jenkinsRevision = getJenkinsBuildCode()
jenkinsName = getJenkinsName()
}
现在测试下Jenkins编译是否正常,可以看到一切都正常了。
参考链接
- https://wiki.jenkins.io/display/JENKINS/Git+Plugin
- https://stackoverflow.com/questions/6245570/how-to-get-the-current-branch-name-in-git
作者:欧阳鹏 欢迎转载,与人分享是进步的源泉!
转载请保留原文地址:http://blog.csdn.net/ouyang_peng/article/details/77802596如果觉得本文对您有所帮助,欢迎您扫码下图所示的支付宝和微信支付二维码对本文进行随意打赏。您的支持将鼓励我继续创作!
Git学习-->关于Jenkins编译时候,如何获取Git分支的当前分支名?的更多相关文章
- Git 学习(三)本地仓库操作——git add & commit
Git 学习(三)本地仓库操作——git add & commit Git 和其他版本控制系统如SVN的一个不同之处就是有暂存区的概念.这在上文已有提及,本文具体说明什么是工作区及暂存区,以及 ...
- Git学习之路(2)-安装GIt和创建版本库
▓▓▓▓▓▓ 大致介绍 前面一片博客介绍了Git到底是什么东西,如果有不明白的可以移步 Git学习之路(1)-Git简介 ,这篇博客主要讲解在Windows上安装Git和创建一个版本库 ▓▓▓▓▓▓ ...
- 【学习总结】Git学习-参考廖雪峰老师教程一-Git简介
学习总结之Git学习-总 目录: 一.Git简介 二.安装Git 三.创建版本库 四.时光机穿梭 五.远程仓库 六.分支管理 七.标签管理 八.使用GitHub 九.使用码云 十.自定义Git 期末总 ...
- git 学习笔记 —— 切换和恢复提交版本( git reset/reflog/tag 命令)
记录一下关于 git 不同提交版本间切换的操作以及如何恢复至切换之前的版本. 切换到之前提交的版本 —— git reset --hard 笔者在使用 git 时,首先接触到了一个"黑魔法& ...
- Git 学习笔记之(一) 使用 git gui 从github上下载代码
背景: 目前一些开源代码均在 GitHub上管理的,包括自己写的代码也可以放在上面进行管理.但问题是,当你换一台电脑,想要将你自己放在 GitHub 上的代码工程下载下来的时候,会遇到各种问题,目前可 ...
- jenkins 参数化构建,获取git分支
def heads= ("git ls-remote -h git@gitlab.com:*.git").execute()def headlist=heads.text.read ...
- git学习笔记08-分支管理策略-实际上我们应该怎么应用分支
Git用Fast forward模式(快进模式),但这种模式下,删除分支后,会丢掉分支信息. 如果要强制禁用Fast forward模式,Git就会在merge时生成一个新的commit,这样,从分支 ...
- 【学习总结】Git学习-本地仓库覆盖式更新对于Git仓库的影响以及pull/push到GitHub
< 许久不用Git之后的探索 > 准备日常更新自己的GitHub了.但是编写的文件平时不放在Git仓库路径下. 故测试覆盖式更新对于仓库是否有影响 直接说结论: 通过对已有库的测试发现覆盖 ...
- Git学习总结(4)——我的Git忽略文件
*.bak *.txt *.vm .gitignore #svn .svn/ # built application files *.apk *.ap_ # files for the dex VM ...
随机推荐
- 手淘H5移动端适配方案flexible源码分析
移动端适配一直是一个值得探讨的问题,在业余时间我找了一些页面,查看了一些厂商对于移动端H5页面的适配方案,看到了几个典型的例子,今天就来记录一下我看到的第一个典型的例子,也是我们公司目前普通H5项目正 ...
- Java精选笔记_IO流(字符输入输出流、字符文件输入输出流、字符流的缓冲区)
字符流 Reader是字符输入流的基类,用于从某个源设备读取字符 Writer是字符输出流,用于向某个目标设备写入字符 字符流操作文件 字符输入流FileReader,通过此流可以从关联的文件中读取一 ...
- HTTP 基础术语
URI 和 URL:URI用于标记一个网络资源,URL则表示这个网络资源的访问地址,详细说明 超文本:普通的一段文字叫做文本,如果给这段文字加上超链接,那么就叫做超文本,HTML 就是超文本标记语言 ...
- 苹果降频门:旧款iPhone哪些功能受到影响
要说苹果最近发生的大事,就数网络上传的沸沸扬扬的降频门事件了,近期苹果在新发布的iOS 11系统中新增了一项功能,意在降低旧款手机的电量消耗,但限制了旧款iPhone的性能,那么iPhone有哪些功能 ...
- 使用React写的一个小小的登录验证密码组件
哎,算了.直接上代码吧,不懂得私聊我把 <!DOCTYPE html> <html lang="en"> <head> <meta cha ...
- js插件---->jquery通知插件toastr的使用
toastr是一款非常棒的基于jquery库的非阻塞通知提示插件,toastr可设定四种通知模式:成功,出错,警告,提示,而提示窗口的位置,动画效果都可以通过能数来设置.toastr需要jquery的 ...
- js插件---->ueditor编辑器的使用
UEditor是由百度WEB前端研发部开发的所见即所得的开源富文本编辑器,具有轻量.可定制.用户体验优秀等特点.今天我们就开始学习一下.大致的效果图如下
- C++中的inline关键字
from here 1. 引入inline关键字的原因 在c/c++中,为了解决一些频繁调用的小函数大量消耗栈空间(栈内存)的问题,特别的引入了inline修饰符,表示为内联函数. 栈空间就是指放置程 ...
- 【python系列】安装完PyCharm创建项目提示No Python interpreter selected
安装Python解释器 去python官网下载python的安装包(https://www.python.org/downloads/release/python-361/) 注意安装的时候选择配置p ...
- LeetCode - Department Highest Salary
题目大概的意思是选出每个Department里工资最高的人的信息并组成相应的表信息 有几个值得注意的地方:1)使用group by语句时,前面的select语句后面的内容只能有两种情况一种是group ...