如何访问共享库中的文件?

red*_*888 7 jenkins jenkins-plugins jenkins-pipeline

我有一个带有.groovy脚本的共享库,我在这样的jenkins文件中调用:

MySharedLibFunction{ .. some args}
Run Code Online (Sandbox Code Playgroud)

我的共享库中还有一个.ps1文件,我想执行.但是当我powershell pwd从我的共享库函数中执行时,当我从我的jenkinsfile调用该函数时,当前工作目录是jenkins文件所在的管道的jenkins工作目录(通常是你想要的).

有没有办法访问共享库中的文件?我想要做powershell -File ps1FileInMySharedLibVarsFolder.ps1

Ste*_*ing 13

您只能使用内置步骤获取内容libraryResource.这就是为什么在我的共享库中有以下函数将它复制到临时目录并返回文件的路径:

/**
  * Generates a path to a temporary file location, ending with {@code path} parameter.
  * 
  * @param path path suffix
  * @return path to file inside a temp directory
  */
@NonCPS
String createTempLocation(String path) {
  String tmpDir = pwd tmp: true
  return tmpDir + File.separator + new File(path).getName()
}

/**
  * Returns the path to a temp location of a script from the global library (resources/ subdirectory)
  *
  * @param srcPath path within the resources/ subdirectory of this repo
  * @param destPath destination path (optional)
  * @return path to local file
  */
String copyGlobalLibraryScript(String srcPath, String destPath = null) {
  destPath = destPath ?: createTempLocation(srcPath)
  writeFile file: destPath, text: libraryResource(srcPath)
  echo "copyGlobalLibraryScript: copied ${srcPath} to ${destPath}"
  return destPath
}
Run Code Online (Sandbox Code Playgroud)

当它返回临时文件的路径时,您可以将其传递给期望文件名的任何步骤:

sh(copyGlobalLibraryScript('test.sh'))
Run Code Online (Sandbox Code Playgroud)

对于驻留在resources/test.sh共享库中的文件.


Bra*_*ram 5

斯蒂芬金的答案更完整,但对于简单的情况,可以执行以下操作:

writeFile file: 'ps1FileInMySharedLibVarsFolder.ps1', text: libraryResource('ps1FileInMySharedLibVarsFolder.ps1')
powershell ".\\ps1FileInMySharedLibVarsFolder.ps1"
Run Code Online (Sandbox Code Playgroud)