简体   繁体   English

Gradle 处理 git 数据的最佳方法是什么

[英]What is best way in Gradle to deal with git data

Seems like看起来像

  1. gradle-git plugin is no more maintained so GitBranchList api will not available with Gradle-6.6.1 gradle-git 插件不再维护,因此GitBranchList api 将不适用于Gradle-6.6.1
task getBranchName(type: GitBranchList) << {
   print getWorkingBranch().name
}
  1. https://stackoverflow.com/a/36760102/1665592 ... it fails on CI tools(Jenkins) if gradle wrapper isn't invoked from root of project where .git dir is. https://stackoverflow.com/a/36760102/1665592 ...如果没有从项目的根目录调用 gradle 包装器,则它在 CI 工具(Jenkins)上失败,其中.git . It produces error fatal: not a git repository (or any of the parent directories): .git as Gradle Wrapper is invoked by Jenkins Gradle plugin from outside of dir where .git folder resides. It produces error fatal: not a git repository (or any of the parent directories): .git as Gradle Wrapper is invoked by Jenkins Gradle plugin from outside of dir where .git folder resides.
def gitBranch() {
    def branch = ""
    def proc = "git rev-parse --abbrev-ref HEAD".execute()
    proc.in.eachLine { line -> branch = line }
    proc.err.eachLine { line -> println line }
    proc.waitFor()
    branch
}

Both solutions doesn't work well to detect current git branch using Gradle..两种解决方案都不能很好地使用 Gradle 检测当前的 git 分支。

How, can I get branch name properly如何正确获取分支名称

I figured it out as我认为它是

/*
   Gets the HEAD git commit for the module.
   Use git to find the hash tag and format a date into YYYYMMDD-hhmmss format.
 */
def getGitCommitHash() {
    def gitFolder = "${project.projectDir}/.git/"
    def takeFromHash = 12
    def head = new File(gitFolder + "HEAD").text.split(":")
    def isCommit = head.length == 1
    if (isCommit) return head[0].trim().take(takeFromHash)
    def refHead = new File(gitFolder + head[1].trim())
    refHead.text.trim().take takeFromHash
}

/*
   Use git to find the current branch name
 */
def getGitBranch() {
    def gitBranch = "Unknown branch"
    try {
        def workingDir = new File("${project.projectDir}/.git/")
        def result = 'git rev-parse --abbrev-ref HEAD'.execute(null, workingDir)
        result.waitFor()
        if (result.exitValue() == 0) {
            gitBranch = result.text.trim()
        }
    } catch (e) {
    }
    return gitBranch
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM