Git学习-->关于Jenkins编译时候,如何获取Git分支的当前分支名?

简介: 一、背景因为代码都迁移到了Gitlab,所以Jenkins编译的时候我们都需要将之前的SVN信息换成现在的Git信息。最近编译一个Lib库的时候,因为团队规定上传Release版本的AAR到Maven的话,必须需要在Jenkins上编译而且Git Branch 必须是master分支才能够上传到Maven。

一、背景

因为代码都迁移到了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单元测试报告&nbsp;:<a href="${BUILD_URL}testReport">点击查看测试报告</a></li>
  <li>Launcher代码覆盖率&nbsp;:<a href="${BUILD_URL}jacoco">点击查看代码覆盖率</a></li>
  <li>Launcher Android Lint&nbsp;:<a href="${BUILD_URL}androidLintResult">点击查看Android Lint</a></li>


<br />
 <li>GIT_COMMIT&nbsp;:${GIT_COMMIT}</a></li>
 <li>GIT_BRANCH&nbsp;:${GIT_BRANCH}</a></li>
 <li>GIT_LOCAL_BRANCH&nbsp;:${GIT_LOCAL_BRANCH}</a></li>
 <li>GIT_PREVIOUS_COMMIT&nbsp;:${GIT_PREVIOUS_COMMIT}</a></li>
 <li>GIT_PREVIOUS_SUCCESSFUL_COMMIT&nbsp;:${GIT_PREVIOUS_SUCCESSFUL_COMMIT}</a></li>
 <li>GIT_URL&nbsp;:${GIT_URL}</a></li>
 <li>GIT_URL_N&nbsp;:${GIT_URL_N}</a></li>
 <li>GIT_AUTHOR_NAME&nbsp;:${GIT_AUTHOR_NAME}</a></li>
 <li>GIT_COMMITTER_NAME&nbsp;:${GIT_COMMITTER_NAME}</a></li>
 <li>GIT_AUTHOR_EMAIL&nbsp;:${GIT_AUTHOR_EMAIL}</a></li>
 <li> GIT_COMMITTER_EMAIL&nbsp;:${ GIT_COMMITTER_EMAIL}</a></li>

这样编译完后,收到的邮件内容如下:
这里写图片描述

如上所示,收到的邮件内容包含了Git的相关信息:

GIT_COMMIT118fa74e6a09c8c5ae713523692add256bfa6afb
GIT_BRANCH :origin/feature/UseByAnonymousDBMigrateAndApiChange
GIT_LOCAL_BRANCH${GIT_LOCAL_BRANCH}
GIT_PREVIOUS_COMMIT118fa74e6a09c8c5ae713523692add256bfa6afb
GIT_PREVIOUS_SUCCESSFUL_COMMIT118fa74e6a09c8c5ae713523692add256bfa6afb
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编译是否正常,可以看到一切都正常了。

这里写图片描述

参考链接


这里写图片描述

作者:欧阳鹏 欢迎转载,与人分享是进步的源泉!
转载请保留原文地址:http://blog.csdn.net/ouyang_peng/article/details/77802596

如果觉得本文对您有所帮助,欢迎您扫码下图所示的支付宝和微信支付二维码对本文进行随意打赏。您的支持将鼓励我继续创作!

这里写图片描述

相关文章
|
11天前
|
开发工具 git
git学习四:常用命令总结,包括创建基本命令,分支操作,合并命令,压缩命令,回溯历史命令,拉取命令
这篇文章是关于Git常用命令的总结,包括初始化配置、基本提交、分支操作、合并、压缩历史、推送和拉取远程仓库等操作的详细说明。
47 1
git学习四:常用命令总结,包括创建基本命令,分支操作,合并命令,压缩命令,回溯历史命令,拉取命令
|
11天前
|
Shell 开发工具 git
git学习三:git使用:删除仓库,删除仓库内文件
通过GitHub的设置页面删除仓库,以及如何使用Git命令行删除仓库中的文件或文件夹。
42 1
git学习三:git使用:删除仓库,删除仓库内文件
|
17天前
|
开发工具 git 开发者
关于git 解决分支冲突问题(具体操作,包含截图,教你一步一步解决冲突问题)
本文通过具体操作和截图,详细讲解了如何在Git中解决分支冲突问题,包括如何识别冲突、手动解决冲突代码、提交合并后的代码,以及推送到远程分支。
76 3
关于git 解决分支冲突问题(具体操作,包含截图,教你一步一步解决冲突问题)
|
1月前
|
缓存 开发工具 git
Git创建分支以及合并分支
在Git中,创建分支使用`git branch [branch_name]`,切换分支使用`git checkout [branch_name]`。修改文件后,通过`git add [file]`添加到暂存区,然后`git commit`提交到本地仓库。如果是新建分支的第一次推送,使用`git push origin [branch_name]`推送到远程仓库,之后可以简化为`git push`。合并分支时,使用`git merge [branch_name]`将指定分支的更改合并到当前分支。
35 2
Git创建分支以及合并分支
|
12天前
|
开发工具 git
Git分支使用总结
Git分支使用总结
19 1
|
7天前
|
Unix Shell 网络安全
git学习六:(bug总结)git@github.com: Permission denied (publickey).等
本文是关于解决在使用Git和GitHub时遇到的“git@github.com: Permission denied (publickey)”错误的指南。文章提供了详细的步骤,包括确认SSH Agent运行状态、检查密钥配置、确保密钥匹配、验证仓库URL、检查权限和代理设置,以及配置SSH文件。这些步骤帮助用户诊断并解决SSH认证问题。
17 0
|
29天前
|
存储 Linux 开发工具
Git基础命令,分支,标签的使用【快速入门Git】
本文详细介绍了Git版本控制系统的基础概念和常用命令,包括工作区、暂存区和版本库的区别,文件状态的变化,以及如何进行文件的添加、提交、查看状态、重命名、删除、查看提交历史、远程仓库操作和分支管理,还涉及了Git标签的创建和删除,旨在帮助读者快速入门Git。
Git基础命令,分支,标签的使用【快速入门Git】
|
1月前
|
测试技术 开发工具 git
掌握 Git 分支策略:提升你的版本控制技能
在现代软件开发中,版本控制至关重要,Git 作为最流行的分布式版本控制系统,其分支管理策略对于高效协作和代码维护尤为重要。本文介绍了几种常用的 Git 分支策略,包括主线开发模型、功能分支模型、Gitflow 工作流和 Forking 工作流,并探讨了如何根据项目需求选择合适的分支模型。通过保持 `master` 分支稳定、及时合并清理分支、使用命名规范、利用 Pull Request 进行代码审查及自动化测试等最佳实践,可以显著提升团队协作效率和软件质量。掌握这些策略将帮助开发者更好地管理代码库,加快开发流程。
|
11天前
|
编译器 网络安全 开发工具
git学习五:切换本地仓库出现的问题。修改git配置初始化。error:src refspec master does not match any。错误总结,送上几个案例
这篇文章是关于Git使用中遇到的一些问题及其解决方案的总结,包括切换本地仓库时的问题、修改Git初始化配置、以及解决"error: src refspec master does not match any"错误等。
27 0
|
2月前
|
开发工具 git 开发者