如何在gradle中使用exec()输出

Bob*_*har 41 gradle

我正在尝试实现一个gradle任务,从一系列环境变量值和shell执行中动态创建buildsignature.properties文件.我有它主要工作,但我似乎无法获得shell命令的输出.这是我的任务......

task generateBuildSignature << {
    ext.whoami = exec() {
        executable = "whoami"
    }
    ext.hostname = exec() {
         executable = "hostname"
    }
    ext.buildTag = System.env.BUILD_TAG ?: "dev"

    ant.propertyfile(
        file: "${buildDir}/buildsignature.properties",
        comment: "This file is automatically generated - DO NOT EDIT!" ) {
        entry( key: "version", value: "${project.version}" )
        entry( key: "buildTimestamp", value: "${new Date().format('yyyy-MM-dd HH:mm:ss z')}" )
        entry( key: "buildUser", value: "${ext.whoami}" )
        entry( key: "buildSystem", value: "${ext.hostname}" )
        entry( key: "buildTag", value: "$ext.buildTag" )
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,生成的属性字段无法获得buildUser和buildSystem的预期结果.

#This file is automatically generated - DO NOT EDIT!
#Mon, 18 Jun 2012 18:14:14 -0700
version=1.1.0
buildTimestamp=2012-06-18 18\:14\:14 PDT
buildUser=org.gradle.process.internal.DefaultExecHandle$ExecResultImpl@2e6a54f9
buildSystem=org.gradle.process.internal.DefaultExecHandle$ExecResultImpl@46f0bf3d
buildTag=dev
Run Code Online (Sandbox Code Playgroud)

如何让buildUser和buildSystem匹配相应exec的输出而不是默认的ExecResultImpl toString?这真的不能那么难,可以吗?

Tay*_*tay 62

这是我从exec获取stdout的首选语法:

def stdout = new ByteArrayOutputStream()
exec{
    commandLine "whoami"
    standardOutput = stdout;
}
println "Output:\n$stdout";
Run Code Online (Sandbox Code Playgroud)

在这里找到:http://gradle.1045684.n5.nabble.com/external-process-execution-td1431883.html (注意页面有一个拼写错误,并提到ByteArrayInputStream而不是ByteArrayOutputStream)


Ben*_*hko 43

这篇文章描述了如何解析Exec调用的输出.您将在下面找到运行命令的两个任务.

task setWhoamiProperty {
    doLast {
        new ByteArrayOutputStream().withStream { os ->
            def result = exec {
                executable = 'whoami'
                standardOutput = os
            }
            ext.whoami = os.toString()
        }
    }
}

task setHostnameProperty {
    doLast {
        new ByteArrayOutputStream().withStream { os ->
            def result = exec {
                executable = 'hostname'
                standardOutput = os
            }
            ext.hostname = os.toString()
        }
    }
}

task printBuildInfo {
    dependsOn setWhoamiProperty, setHostnameProperty
    doLast {
         println whoami
         println hostname
    }
}
Run Code Online (Sandbox Code Playgroud)

实际上,无需调用shell命令就可以更轻松地获取此信息.

目前登录用户: System.getProperty('user.name')

主机名: InetAddress.getLocalHost().getHostName()

  • 快速提问,是不是你的代码缺少`standardOutput = os` ?? (3认同)

jav*_*ett 5

ExecGradle文档中解读

task execSomething {
  doFirst {
    exec {
      workingDir '/some/dir'
      commandLine '/some/command', 'arg'

      ...
      //store the output instead of printing to the console:
      standardOutput = new ByteArrayOutputStream()

      //extension method execSomething.output() can be used to obtain the output:
      ext.output = {
        return standardOutput.toString()
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


mko*_*bit 5

使用kotlin-dsl

import java.io.ByteArrayOutputStream

val outputText: String = ByteArrayOutputStream().use { outputStream ->
  project.exec {
    commandLine("whoami")
    standardOutput = outputStream
  }
  outputStream.toString()
}
Run Code Online (Sandbox Code Playgroud)


swp*_*mer 5

在许多情况下,Groovy 允许更简单的实现。因此,如果您使用的是基于 Groovy 的构建脚本,您可以简单地执行以下操作:

def cmdOutput = "command line".execute().text
Run Code Online (Sandbox Code Playgroud)


Lew*_*wik 5

kotlin-dsl 变体

绝妙风格

在buildSrc中:

import org.codehaus.groovy.runtime.ProcessGroovyMethods

fun String.execute(): Process = ProcessGroovyMethods.execute(this)
fun Process.text(): String = ProcessGroovyMethods.getText(this)
Run Code Online (Sandbox Code Playgroud)

构建.gradle.kts:

"any command you want".execute().text().trim()
Run Code Online (Sandbox Code Playgroud)

执行风格

在buildSrc中:

import org.gradle.api.Project
import org.gradle.process.ExecSpec
import java.io.ByteArrayOutputStream

fun Project.execWithOutput(spec: ExecSpec.() -> Unit) = ByteArrayOutputStream().use { outputStream ->
    exec {
        this.spec()
        this.standardOutput = outputStream
    }
    outputStream.toString().trim()
}
Run Code Online (Sandbox Code Playgroud)

build.gradle.kts:

val outputText = project.execWithOutput {
    commandLine("whoami")
}

//variable project is actually optional

val outputText = execWithOutput {
    commandLine("whoami")
}
Run Code Online (Sandbox Code Playgroud)