如何在 Jenkins 脚本控制台中包含共享库?

Rob*_*loi 6 groovy jenkins

在 Jenkinsfile 中,如果我在 alias 下安装了Jenkins 共享库my-awesome-lib,我可以使用以下语法包含它:

@Library('my-awesome-lib')
import ...
Run Code Online (Sandbox Code Playgroud)

但是如何从Jenkins 脚本控制台引用库?

Tid*_*ach 5

您可以像这样从脚本控制台引用库对象:

// get Jenkins instance
Jenkins jenkins = Jenkins.getInstance()

// get Jenkins Global Libraries
def globalLibraries = jenkins.getDescriptor("org.jenkinsci.plugins.workflow.libs.GlobalLibraries")
globalLibraries.getLibraries()
Run Code Online (Sandbox Code Playgroud)

但是使用共享库代码并不简单,甚至可能是不可能的。

继续上面的代码,假设你这样做:

def lib = globalLibraries[0]
Run Code Online (Sandbox Code Playgroud)

获取猎犬:

def ret = lib.getRetriever()
Run Code Online (Sandbox Code Playgroud)

那么您需要检索源代码,但是为了调用retrieve(),您需要一些脚本控制台中没有的对象:

/**
     * Obtains library sources.
     * @param name the {@link LibraryConfiguration#getName}
     * @param version the version of the library, such as from {@link LibraryConfiguration#getDefaultVersion} or an override
     * @param target a directory in which to check out sources; should create {@code src/**}{@code /*.groovy} and/or {@code vars/*.groovy}, and optionally also {@code resources/}
     * @param run a build which will use the library
     * @param listener a way to report progress
     * @throws Exception if there is any problem (use {@link AbortException} for user errors)
     */
    public abstract void retrieve(@Nonnull String name, @Nonnull String version, @Nonnull FilePath target, @Nonnull Run<?,?> run, @Nonnull TaskListener listener) throws Exception;
Run Code Online (Sandbox Code Playgroud)

所以可能有一种hacky的方式来做到这一点,但IMO不值得。