我正在嘗試使用 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執行此操作。
uj5u.com熱心網友回復:
代碼有幾個問題:
- 常規方法,如
.each*,.find*和類似的那些迭代對集合可以在流水線代碼問題。 - 嘗試在與“master”不同的節點上執行時,代碼將失敗。Groovy/Java 代碼總是在 master 上運行,因此它不能直接訪問
WORKSPACE另一個節點上的目錄。代碼將嘗試在主節點上而不是當前節點上查找目錄。
不幸的是,沒有內置的 Jenkins 函式來遍歷目錄(findFiles僅遍歷檔案)。
一個好的解決方法是使用shell 代碼:
// 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步驟,它將回傳命令的標準輸出。用于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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/388730.html
