无法使用File或nio检查Pipeline,NonCPS或Shared Library中是否存在文件

时间:2017-07-20 21:43:44

标签: java groovy jenkins-pipeline

知道是什么让大师如此特别才能使这段代码在那里取得成功并在其他地方失败?我接下来要检查java版本和类路径。

如果在master上运行,以下代码通过以下每种方式正确检测文件是否存在。如果在任何从属设备上运行,则无法执行此操作。

我正在编写一个共享库并进行了许多单元测试。我不想使用fileExists()管道代码,因为我需要:

  • 在我的通用代码中传递脚本对象,使其成为jenkins centric
  • 重构单元测试在jenkins中运行时假冒fileExists方法。

使用NODE参数的参数化作业的PipelineCode:

import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.Files

import hudson.FilePath




def isreg(def path) {
    Path target = Paths.get(path)
    println "Checking ${target} // ${target.toAbsolutePath()}"
    println "target is reg? ${Files.isRegularFile(target)}"
    println "target is reg? ${Files.isRegularFile(target.toAbsolutePath())}"
}

def exists(def path) {
    Path target = Paths.get(path)
    println "Checking ${target} // ${target.toAbsolutePath()}"
    println "target exists? ${Files.exists(target)}"
    println "target exists? ${Files.exists(target.toAbsolutePath())}"
    println "File exists ${target.toFile().exists()} ${target.toAbsolutePath().toFile().exists()}"

}

def filePathExists(def path) {
    FilePath fPath = new FilePath(new File(path))
    println "FilePath ${fPath} exists? ${fPath.exists()}"
}

def checkFile(def target) {
    println "----------\nnio isReg"
    isreg(target)
    println "----------\nnio exists"
    exists(target)

    println "----------\n FilePath exists"
    filePathExists(target)

}


node(params.NODE) {
    currentBuild.description = "run on ${params.NODE}"
    def target = "${env.WORKSPACE}/target.txt"
    sh "touch ${target}"
    checkFile(target)

}

1 个答案:

答案 0 :(得分:0)

管道在master上执行,因此,即使在shareLibrary中,也必须使用管道的fileExists方法而不是File或NIO对象。

https://support.cloudbees.com/hc/en-us/articles/230922128-Pipeline-Using-java-io-File-in-a-Pipeline-description