git.exe is not found by gradle

169 views Asked by At

My Android Studio project uses git from gradle :

branchName = ByteArrayOutputStream().use { outputStream ->
                    exec {
                        commandLine("git branch --show-current")
                        standardOutput = outputStream
                    }
                    outputStream.toString()
                }

On Linux and Mac, this works just fine, but on Windows it says:

Could not start 'git'

and I have to replace it with this :

commandLine("cmd", "/c", "git branch --show-current")

this defeats the purpose for me since I want this to work on different platforms and machines. If I add it it'll instead break on Linux and Mac. any suggestions on what should I do ?

2

There are 2 answers

3
dee cue On BEST ANSWER

You can probably do an OS checking this way

import org.apache.tools.ant.taskdefs.condition.Os

// ...

branchName = ByteArrayOutputStream().use { outputStream ->
                    exec {
                        if (Os.isFamily(Os.FAMILY_WINDOWS)) commandLine("cmd", "/c", "git branch --show-current")
                        else commandLine("git branch --show-current")
                        standardOutput = outputStream
                    }
                    outputStream.toString()
                }
3
Krystian Kaniowski On

If you really want to make it only in linux way, you can give a try for WSL - Windows Subsytem for Linux. Here is an additional instruction for run Android Studio with this.

It works but require some configuration, but generally it will be a bit overkill for your case and I think @deecue is right sugesting small if - look at documentation: https://docs.gradle.org/current/dsl/org.gradle.api.tasks.Exec.html

You can just do it in a bit more pleasant and reusable way - as an extracted method:

import org.apache.tools.ant.taskdefs.condition.Os

// ...

fun runCommand(command: String, windowsDir: String = "/c") {
    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
        commandLine("cmd", windowsDir, command)
    } else {
        commandLine(command)
    }
}

// ...

branchName = ByteArrayOutputStream().use { outputStream ->
    exec {
        runCommand("git branch --show-current")
        standardOutput = outputStream
    }
    outputStream.toString()
}