Groovy 获取目录方法不return 所有目录

Groovy get directory method does not return all the directories

我正在尝试使用 groovy(在 Jenkins 管道中)获取一个目录(部署)下的所有目录。为此,我使用了以下代码片段。

def currentDir = new File("${WORKSPACE}/deployment")
currentDir.eachFile FileType.DIRECTORIES, {
  println it.name
}

执行此操作后,即使有多个目录,我也只收到一个目录。

我尝试了另一个代码片段,它给了我目录的完整路径。但仍然在这里,即使有多个目录,我也只得到一个目录路径。

def dir = new File("${WORKSPACE}/deployment")
dir.eachFileRecurse (FileType.DIRECTORIES) { directory ->
  println directory
}

我真正想要的是第一个解决方案,但包含所有目录。我在这里做错了什么吗? Jenkins 管道上是否有设置以确保所有目录都可见?请注意,我还允许 In Script Approval 来执行此操作。

代码有几个问题:

  • Groovy 方法,如 .each*.find* 和迭代集合的类似方法可以是 .
  • 当尝试在与“master”不同的节点上执行时,代码将失败。 Groovy/Java 代码总是在 master 上运行,所以它不能直接访问另一个节点上的 WORKSPACE 目录。该代码将尝试在主节点而不是当前节点上查找目录。

不幸的是,没有内置的 Jenkins 函数可以遍历目录(findFiles 只能遍历文件)。

一个好的解决方法是使用 shell code:

// Get directory names by calling shell command
def shOutput = sh( returnStdout: true, script: 'find * -maxdepth 0 -type d' )

// Split output lines into an array
def directories = shOutput.trim().split('\r?\n')

// Make sure to use "for" instead of ".each" to work around Jenkins bugs
for( name in directories ) {
    println name
} 

通过将 returnStdout: true 传递到 sh 步骤,它将 return 命令的标准输出。使用 trim() 从末尾去除任何无关的换行符,并使用 split() 从输出行创建一个数组。


这是该代码的 PowerShell 版本(除第一行外大部分相同):

// Get directory names by calling shell command
def shOutput = powershell( returnStdout: true, script: '(Get-ChildItem -Directory).Name' )

// Split output lines into an array
def directories = shOutput.trim().split('\r?\n')

// Make sure to use "for" instead of ".each" to work around Jenkins bugs
for( name in directories ) {
    println name
}