Home > front end >  Understanding groovy code in jenkins file
Understanding groovy code in jenkins file

Time:10-12

I'm absolutely new to Groovy and Jenskins, please ignore if question sounds noob. Following is a code snippet from a jenkins file containing groovy code.

def boolean hasChanged(String searchText) {
    return sh(
        returnStatus: true,
        script: "git diff --name-only ${GIT_PREVIOUS_COMMIT} ${GIT_COMMIT} | grep \"${searchText}\""
    ) == 0
}

Questions:

  1. Is the above snippet is function/method written in groovy?
  2. what does return sh do?
  3. Per my understanding script: "git diff --name-only ${GIT_PREVIOUS_COMMIT} ${GIT_COMMIT} | grep \"${searchText}\"" the output of grep \"${searchText}\"" is fed into it diff --name-only ${GIT_PREVIOUS_COMMIT} ${GIT_COMMIT}, is the understanding correct?

Please assist.

CodePudding user response:

It is looks like a Groovy with Jenkins plugins (sh)
Here I Added comments to explain this code.

// hasChanged method return boolean value
def boolean hasChanged(String searchText) {
// Insted of 
// def shResult = sh(...); return shResult
// the sh results is returned 
return sh(
        // Preform the sh script and return the script exist code
        returnStatus: true,
        script: "git diff --name-only ${GIT_PREVIOUS_COMMIT} ${GIT_COMMIT} | grep \"${searchText}\""
    ) == 0 // check script exist code status
}

The output of git diff is piped to grep command that searches for given text in the git diff output

CodePudding user response:

  1. Yes
  2. In this case, the entire Groovy function returns True if grep finds ${searchText} in the output of command git diff --name-only ${GIT_PREVIOUS_COMMIT} ${GIT_COMMIT}, or else False.
  • Related