30

I'm writing a task to deploy my application to the server. However, I'd like for this task to run only if my current git branch is the master branch. How can I get the current git branch?

gradle-git approach:

I know there is a gradle-git plugin that has a method getWorkingBranch() under the task GitBranchList, but anytime I try to execute

task getBranchName(type: GitBranchList) {
   print getWorkingBranch().name
}

I get a "Task has not executed yet" error. I looked at the source and it throws that error when there is no branch set. Does that mean this method doesn't do quite what I think it does? That I need to set the branch somewhere?

neptune
  • 1,380
  • 2
  • 17
  • 25

3 Answers3

54

You also are able to get git branch name without the plug-in.

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
}

Refer to: Gradle & GIT : How to map your branch to a deployment profile

Song Bi
  • 729
  • 1
  • 7
  • 11
  • 14
    Maybe this is a given, but it should be noted that many CI engines checkout out the latest commit in a detached state, instead of master or a named branch. In that case, this solution will return HEAD, not the branch name. – Jørgen Sivesind Sep 25 '19 at 08:07
  • See [this](https://docs.gradle.org/current/userguide/configuration_cache.html#config_cache:requirements:external_processes) for an alternative that won't break the configuration cache. – Leponzo Jul 29 '23 at 01:31
20

No this doesn't mean that the branch is not set. It means that the task hasn't really executed yet. What you're trying to do is calling a method in the configuration closure, whereas you probably want to call it after task execution. Try to change your task to:

task getBranchName(type: GitBranchList) << {
    print getWorkingBranch().name
}

With the << you're adding a doLast, which will be executed after the task has been executed.

Hiery Nomus
  • 17,429
  • 2
  • 41
  • 37
5

Here's essentially @Song Bi's answer, but in kotlin DSL (inspired by this thread here):

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import java.io.ByteArrayOutputStream


/**
 * Utility function to retrieve the name of the current git branch.
 * Will not work if build tool detaches head after checkout, which some do!
 */
fun gitBranch(): String {
    return try {
        val byteOut = ByteArrayOutputStream()
        project.exec {
            commandLine = "git rev-parse --abbrev-ref HEAD".split(" ")
            standardOutput = byteOut
        }
        String(byteOut.toByteArray()).trim().also {
            if (it == "HEAD")
                logger.warn("Unable to determine current branch: Project is checked out with detached head!")
        }
    } catch (e: Exception) {
        logger.warn("Unable to determine current branch: ${e.message}")
        "Unknown Branch"
    }
}
UncleBob
  • 1,233
  • 3
  • 15
  • 33