0

我需要解析文本(svn 命令的输出)以检索数字(svn 修订版)。这是我的代码。请注意,我需要将所有输出流作为文本检索以执行其他操作。

def proc = cmdLine.execute()                 // Call *execute* on the strin
proc.waitFor()                               // Wait for the command to finish
def output = proc.in.text

//这里发生的其他事情

output.eachLine {
    line ->
    def revisionPrefix = "Last Changed Rev: "
    if (line.startsWith(revisionPrefix)) res = new Integer(line.substring(revisionPrefix.length()).trim())
}

这段代码运行良好,但由于我还是 Groovy 的新手,我想知道是否有更好的惯用方法来避免丑陋的 if...

svn 输出示例(当然问题更普遍)

Path: .
Working Copy Root Path: /svn
URL: svn+ssh://svn.company.com/opt/svnserve/repos/project/trunk
Repository Root: svn+ssh://svn.company.com/opt/svnserve/repos
Repository UUID: 516c549e-805d-4d3d-bafa-98aea39579ae
Revision: 25447
Node Kind: directory
Schedule: normal
Last Changed Author: ubi
Last Changed Rev: 25362
Last Changed Date: 2012-11-22 10:27:00 +0000 (Thu, 22 Nov 2012)

我从下面的答案中得到灵感,我使用 find() 解决了。我的解决方案是:

def revisionPrefix = "Last Changed Rev: "
def line = output.readLines().find { line -> line.startsWith(revisionPrefix) }
def res = new Integer(line?.substring(revisionPrefix.length())?.trim()?:"0")

3行,没有如果,很干净

4

1 回答 1

1

一种可能的选择是:

def output = cmdLine.execute().text
Integer res = output.readLines().findResult { line ->
  (line =~ /^Last Changed Rev: (\d+)$/).with { m ->
    if( m.matches() ) {
      m[ 0 ][ 1 ] as Integer
    }
  }
}

不确定它好还是不好。我相信其他人会有不同的选择

编辑:

另外,请注意使用proc.text. 如果你的 proc 输出了很多东西,那么当输入流变满时你最终可能会阻塞......

这是一个被大量评论的替代方案,使用consumeProcessOutput

// Run the command
String output = cmdLine.execute().with { proc ->

  // Then, with a StringWriter
  new StringWriter().with { sw ->

    // Consume the output of the process
    proc.consumeProcessOutput( sw, System.err )

    // Make sure we worked
    assert proc.waitFor() == 0

    // Return the output (goes into `output` var)
    sw.toString()
  }
}

// Extract the version from by looking through all the lines
Integer version = output.readLines().findResult { line ->

  // Pass the line through a regular expression
  (line =~ /Last Changed Rev: (\d+)/).with { m ->

    // And if it matches
    if( m.matches() ) {

      // Return the \d+ part as an Integer
      m[ 0 ][ 1 ] as Integer
    }
  }
}
于 2012-11-26T14:54:30.427 回答