将groovy文件导入到另一个groovy文件

dpiehjr4  于 7个月前  发布在  其他
关注(0)|答案(2)|浏览(97)

我有一个单独的文件,名为 * stagUtils.groovy *,并定义了方法。

def init(def service, def type)
{
    return """
        stage ("Init") {
           //code
       }
"""
}
def Validate_MergeRequest(def type)
{
  return """
            stage('Validate MergeRequest') {
             //code
            }
"""
}
def Merge_Collision_Check()
{
    return """
            stage ('Merge Collision Check') {
              //code
            }
"""
}

我现在想在我的 * jobs.groovy * 文件中使用这些方法

//importing dependencies
import java.io.File
import org.yaml.snakeyaml.Yaml
import java.nio.file.Files
import java.nio.file.Paths
import groovy.transform.Field

//template defnition
def pipelineTemplate(String type) {
 pipelineJob("${service}/${pipeline_name}-${type}-pipeline") {
        definition {
pipeline {
    agent any   
    stages {
         // I want to call init method here
        }
}
}
}
}

许多人建议在管道中使用共享库。但是由于我使用作业管理器执行,这里不支持共享库。我试过评估,但没用。帮帮我。

nhhxz33t

nhhxz33t1#

String sourceFile = readFileFromWorkspace("stagUtils.groovy")
Class stagUtils = new GroovyClassLoader(getClass().getClassLoader()).parseClass(sourceFile)

stagUtils.init()

或者像文件上说的
添加到stagUtils.groovy

package utils

在工作中,Groovy

import utils.stagUtils

def myJob = job('example')
stagUtils.init()
kuuvgm7e

kuuvgm7e2#

在我的例子中,我使用这样的语法:

pipeline {
    agent any   
    stages {
         stage("Load groovy file") {
            pipeline = load 'stagUtils.groovy'
         }
         stage("Call function from groovy file") {
            pipeline.init()
         }
    }
}

相关问题