1

我有具有以下结构的 Jenkins 共享库:

resources
  |-> config.yaml
  |-> projects.yaml
src
  |_ com
      |_ rathath
           |_ jenkins
                 |-> Configuration.groovy

在 src/com/rathath/jenkins/Configuration.groovy 中,我想读取资源目录中的 YAML 文件。

我试过了 :

@Grab('org.yaml:snakeyaml:1.17')
import org.yaml.snakeyaml.Yaml
import hudson.FilePath
// ...
def readConfig() {
   def config = [:]
   def cwd = hudson.model.Executor.currentExecutor().getCurrentWorkspace().absolutize()
   new FilePath(cwd, 'resources').list('*.yaml').each {
     config << it.read()
   }
}       

不幸的是,我得到hudson.model.Executor.currentExecutor()的是空的。

我尝试了另一种方法:

@Grab('org.yaml:snakeyaml:1.17')
import org.yaml.snakeyaml.Yaml
import hudson.FilePath
import groovy.transform.SourceURI
import java.nio.file.Paths

// ...
@SourceURI
URI source Uri

def readConfig() {
   def config = [:]
   def cwd = new FilePath(Paths.get(sourceUri).getParent().getParent().getParent().getParent().getParent().getParent().toFile());
   new FilePath(cwd, 'resources').list('*.yaml').each {
     config << it.read()
   }
}  

我遇到了更大的问题,.. Jenkins 无法加载文件:

java.lang.NoClassDefFoundError: Could not initialize class com.rathath.jenkins.Configuration
   at java.io.ObjectStreamClass.hasStaticInitializer(Native Method).
.....
....
4

2 回答 2

1

我猜你正在调用你的文件src/com/rathath/jenkins/Configuration.groovyvars/whateverPipelineFile.groovy所以在调用它时,请确保你传递管道上下文,并且从你的类中你将能够使用context.libraryResource()

例子:

配置.groovy

    class Configuration {
        def context


        Configuration(pipelineContext) {
            this.context = pipelineContext
        }

        def readConfig() {
            this.context.libraryResource("${PATH_OF_YOUR_FILE}")
            ...
        }
}  

/vars/myPipeline.groovy

   import com.rathath.jenkins.configuration.Configuration

   def call() {
      def configuration = new Configuration(this)
      configuration.readConfig()
      ...
   }

libraryResource() 的文档在这里

于 2020-04-27T00:32:39.203 回答
1

让它工作并不容易。但我做到了:

src/com/rathath/jenkins/Configuration.groovy

@Grab(group='org.yaml', module='snakeyaml', version='1.17')
import org.yaml.snakeyaml.Yaml
import java.io.File
import groovy.transform.SourceURI
import java.nio.file.Path
import java.nio.file.Paths
import static groovy.io.FileType.*

class Configuration {

  Map config = [:]
  
  @SourceURI
  URI sourceUri

  Configuration() {
    new File(getRootLocation(), 'resources')
      .eachFileMatch(FILES, ~/.*\.yaml/) {
       this.config << yaml.load(it.text)
      }
  }
  @NonCPS
  File getRootLocation() {
    return Paths.get(sourceUri)
            .getParent() // jenkins
            .getParent() // rathath
            .getParent() // com
            .getParent() // src
            .getParent() // .
            .toFile()

  }

}
于 2020-11-22T04:06:38.290 回答