你知道是什么让 master 如此特别,导致这段代码在那里成功而在其他地方失败吗?接下来我要检查 java 版本和类路径。
如果在 master 上运行,以下代码可以通过以下每种方式正确检测文件存在。如果在任何从属设备上运行,它都会失败。
我正在编写一个共享库并且有很多单元测试。我不想使用 fileExists()
管道代码,因为那样我需要:
- 在我的通用代码中传递脚本对象,使其以 Jenkins 为中心
- 重构单元测试,以在不在 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)
}
请您参考如下方法:
管道在 master 上执行,因此,即使在 shareLibrary 中,您也必须使用管道的 fileExists 方法,而不是 File 或 NIO 对象。