groovyjenkins-pipeline

How to push a Jenkins shared library file(s) to the Git repo?


I have a follow up question to Where does the jenkins shared library files get stored? I have a pipeline where I do the following.

@Library("my-library") _
import com.company.builders.BuildDirector

node("linux-nodes") {
    def obj = new BuildDirector(this, env.CONFIRM.toBoolean(), env.DEBUG_LEVEL.toInteger())
    obj.buildBranch('master')
}

The script does our Gradle builds and pushes the appropriate artifacts to our Maven and Docker repos.

But it also updates 2 files in our pipeline's resources directory, like this (I only show one file in the code below).

    writeFile file: "DependencyCheckerFullReport.txt",
              text: libraryResource("path/to/DependencyCheckerFullReport.txt")

How can I then commit and push the changes in path/to/DependencyCheckerFullReport.txt to my pipepline's Git repo?


Solution

  • The Git integrations with Jenkins Pipeline through the high level git step, or the lower level scm step, both only permit read operations. To perform write operations, such as committing to a local repository or pushing to a remote repository, one must use custom steps. There are basically two options here:

    Basic sh step methods to execute the git CLI with authentication via e.g. withCredentials block (high level interface).

    withCredentials(...) {
      sh(script: 'git commit -m "my message"', label: 'Commit to Local Git Repo')
    }
    

    Shared library leveraging Java/Groovy SDK bindings (low level interface). You clearly already know how to develop shared libraries, and so you can import Git SDK bindings from a package repository, and then develop code for authentication and Git write operations. I cannot really recommend any of the packages as I do not have experience with them, and also do not want to appear to be advertising, but a quick search reveals they definitely exist.

    As an addendum to the above: you can also interact with the remote repo via its REST API (those usually exist). There are http packages for Groovy to perform that also.