0

Seems like

  1. gradle-git plugin is no more maintained so GitBranchList api will not available with 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. 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..

How, can I get branch name properly

Swapnil Kotwal
  • 5,418
  • 6
  • 48
  • 92
  • I used https://github.com/ajoberstar/grgit recently – injecteer Feb 16 '21 at 21:15
  • You might be using lower versions of Gradle. 6.6.1 won't allowed me to use grgit plugin. Since, that project isn't maintained anymore I found it not a good idea to use those API – Swapnil Kotwal Feb 17 '21 at 01:57

1 Answers1

0

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
}
Swapnil Kotwal
  • 5,418
  • 6
  • 48
  • 92