Search code examples
jenkinsgroovyjenkins-pipeline

How do I write multiple functions in one file?


I am writing my own Jenkins shared library. Currently my lib looks like this:

root
|
|- vars
   |---function1.groovy
   |---function2.groovy
   |---function3.groovy

Each function file contains a call() method and the code that it is executing. How can I combine all those functions in one file?


Solution

  • Put all functions into single file:

    root
    |
    |- vars
       |---allFunctions.groovy
    

    Rename functions from call() to:

    function1(string) {
      echo "function1 - $string"
    }
    
    function2(string) {
      echo "function2 - $string"
    }
    
    

    Call them from different file (e.g. vars/buildRepo.groovy) as:

    allFunctions.function1('Hello world via function1')
    allFunctions.function2('Hello world via function2')
    

    Call them from withing same file (e.g. vars/allFunctions.groovy) as:

    function1('Hello world via function1')
    function2('Hello world via function2')
    

    As @matt-schuchard noted, it is described in https://www.jenkins.io/doc/book/pipeline/shared-libraries/#defining-global-variables on log.groovy example.