Как получить доступ к файлу stati c в папке ресурсов общей библиотеки из класса в каталоге sr c - PullRequest
0 голосов
/ 07 апреля 2020

У меня есть общая библиотека 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()
   }
}  

У меня возникла большая проблема, .. Дженкинс не смог загрузить файл:

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

1 Ответ

0 голосов
/ 27 апреля 2020

Полагаю, вы вызываете свой файл src/com/rathath/jenkins/Configuration.groovy из vars/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 () здесь

...