Search code examples
javagradlegroovy

How to run execute a command in project directory in gradle?


I have the following task

task runSomeTool(type: JavaExec, dependsOn: 'jar') {
....
    "git config remote.origin.url".execute().text.trim()
....
}

which returns and empty string.
When I change the command string to list all properties (git config --list), I see that it is listing the global config properties. This led me to discover that it runs in ${user.dir}/.gradle/daemon/6.8.3/ directory.
Is there anyway I can execute the command in $projectDir?

Thanks very much


Solution

  • I ended up using the ProcessBuilder instead

    public String gitProperty(String command, String... argsArray){
        def commandArgs = ["git", command]
        if (argsArray.length > 0)
            commandArgs+=argsArray.flatten()ProcessBuilder pb = new ProcessBuilder(commandArgs)
        // To make sure it executes in the correct directory
        pb.directory(new File ("${wDir}"))
        Process p = pb.start()
        //Wait for the process to finish
        p.waitFor()
        String result = new String(p.getInputStream().readAllBytes())
        return result.trim()
    }
    

    wDir, in this case, is the working directory one specifies.