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

j7dteeu8  于 2023-02-04  发布在  其他
关注(0)|答案(6)|浏览(123)

我正在尝试实现一个gradle任务,以便buildsignature.properties根据一系列环境变量值和shell执行动态创建一个www.example.com文件。我让它大部分时间都在工作,但似乎无法获得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" )
    }
}

但是结果属性字段没有获得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

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

bqjvbblv

bqjvbblv1#

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

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

在此找到:http://gradle.1045684.n5.nabble.com/external-process-execution-td1431883.html(请注意,该页面有一处排印错误,提到的是ByteArrayInputStream而不是ByteArrayOutputStream)

xoshrz7s

xoshrz7s2#

这个post描述了如何解析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
    }
}

实际上,有一种更简单的方法可以获得这些信息,而不必调用shell命令。
当前登录用户:System.getProperty('user.name')
主机名:InetAddress.getLocalHost().getHostName()

7fyelxc5

7fyelxc53#

使用kotlin-dsl

import java.io.ByteArrayOutputStream

val outputText: String = ByteArrayOutputStream().use { outputStream ->
  project.exec {
    commandLine("whoami")
    standardOutput = outputStream
  }
  outputStream.toString()
}
yeotifhr

yeotifhr4#

Groovy在很多情况下允许更简单的实现,所以如果你使用基于Groovy的构建脚本,你可以简单地这样做:

def cmdOutput = "command line".execute().text
whlutmcx

whlutmcx5#

摘自Gradle docs for Exec

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()
      }
    }
  }
}
8e2ybdfx

8e2ybdfx6#

kotlin-dsl变体

时髦的风格

在buildSrc中:

import org.codehaus.groovy.runtime.ProcessGroovyMethods

fun String.execute(): Process = ProcessGroovyMethods.execute(this)
fun Process.text(): String = ProcessGroovyMethods.getText(this)

build.gradle.kts:

"any command you want".execute().text().trim()

执行样式

在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()
}

build.gradle.kts

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

//variable project is actually optional

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

相关问题