如何在不知道文件名(或编号)的情况下从共享库的资源文件夹中加载文件? [英] How to load files from resources folder in Shared library without knowing their names (or number)?
问题描述
您知道,在Jenkins的共享库中,可以通过执行以下操作来加载资源(位于资源文件夹中):
As you know, in Shared libraries in Jenkins, it is possible to load a resource (located in resources folder) by doing:
libraryResource("script.sh")
现在,我的用例是我想在资源下的文件夹中加载文件数量:
Now my use case is that I want to load number of files inside a folder under resources :
+ resources
+ teamA
+ script1.sh
+ script2.sh
我想在做任何事情之前先加载所有这些文件: 我在共享库中做了一个方法:
And I want to load all those files before doing anything : I did a method in the shared library:
new File(scriptsFolder).eachFile() { file->
writeFile([file:"${env.workspace}/${file.getName()}",text:libraryResource("$scriptsFolder/${file.getName()}")])
sh("chmod +x ${env.workspace}/${file.getName()}")
}
其中scriptsFolder= "teamA"
当然,我会得到java.io.IOException: Is a directory
因为libraryResource
必须获取文件路径参数.
Of cource I'm getting java.io.IOException: Is a directory
Because libraryResource
must get a file path parameter.
那么,有什么方法可以加载所有这些文件而无需知道它们的名称或编号吗?
So is, there a way to load all those files without knowing their names or their number?
推荐答案
您可以使用Groovy @SourceURI批注获取共享库的绝对路径:
You can get absolute path of your shared library using Groovy @SourceURI annotation:
// vars/get_resource_dir.groovy
import groovy.transform.SourceURI
import java.nio.file.Path
import java.nio.file.Paths
class ScriptSourceUri {
@SourceURI
static URI uri
}
def call() {
Path scriptLocation = Paths.get(ScriptSourceUri.uri)
return scriptLocation.getParent().getParent().resolve('resources').toString()
}
使用该路径,您可以照常调用脚本:
Using the path you can invoke your scripts as usual:
sh "${get_resource_dir()}/com/example/test.sh"
这篇关于如何在不知道文件名(或编号)的情况下从共享库的资源文件夹中加载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!