artifactVersion = getVersion('build.gradle')
println artifactVersion[enter image description here][1]
def getVersion(String fileName) {
readFile(env.WORKSPACE+"/"+fileName).split("\n").each { line ->
if ((line =~ /version (.*)/).count > 0) {
echo line
def m = (line =~ /version (.*)/)[0]
echo m[1].replaceAll('"','').toString()
println m[1].replaceAll('-SNAPSHOT','').toString()
return m[1].replaceAll('-SNAPSHOT','').toString()
}
}
}
from getVersion api am getting the version 1.0 and that am attached in the console
but that 1.0 is not appending to the artifactVersion
One problem in your code is that the return in getVersion does not return out of the function.
The curly braces in list.each{ } create an anonymous function. Calling return inside will only return from the current iteration of the each function. A normal for loop or a combination of find/findAll and collect (map in other languages) would be better.
See also Groovy Closures and list methods.
Related
I am having list of files in a directory.
For Ex:
sample1.properties
sample2.properties
sample3.properties
I am trying to use the groovy code to push these values in the Jenkins Active Choices parameter. How can I populate this list without ".properties" at the end. My list of Active choices parameters needs to be like this:
sample1
sample2
sample3
Code I am using is:
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
def results = new JsonSlurper().parseText(reader.getText());
reader.close()
data= results.tree.path
data.each {
it -> if(it.endsWith(".properties"))
choices.push(it.replace("/","") )
}
choices=choices.sort()
choices.add(0,"SELECT")
return choices
Simply replacing the .properties part will not work?
choices.push(it.replace("/","").replace(".properties", ""))
If my assumption regarding your results.tree.path content is correct, then you should probably use something like that:
def data = [
'some/complex/path/sample1.properties',
'some/complex/path/some_irrelevant_file.txt',
'some/complex/path/sample2.properties',
'some/complex/path/sample3.properties'
]
data.findAll { it.endsWith('.properties') }
.collect { it.split('/').last().replace('.properties', '') }
.each { println it }
so, in your case, you need to do:
results.tree.path.findAll { it.endsWith('.properties') }
.collect { it.split('/').last().replace('.properties', '') }
.each { choices.push(it) }
None of the lines after making httpRequest are getting executed. Everything else works fine in this function. What could be going wrong here?
However, network request is going fine and I am able to see the response in the console. httpRequest is being made via plugin
I've even tried CURL - but lines after curl are not executed.
#NonCPS
def doPRCommentBasedTesting() {
def causes = currentBuild.rawBuild.getCauses()
def commentURL
for(cause in causes) {
if (cause.class.toString().contains("GitHubPullRequestCommentCause")) {
commentURL = cause.getCommentUrl()
commentURL = commentURL.substring(commentURL.lastIndexOf("-") + 1)
println "This job was caused by job " + commentURL
def url1 = "https://<git_url>/api/v3/repos/<owner>/<repo>/issues/comments/" + commentURL
def commentText = httpRequest authentication: '<auth_cred>', url: url1, consoleLogResponseBody: true
println commentText
println commentText.getClass()
println "hello world, how are you doing today?"
}
else {
println "Root cause : " + cause.toString()
}
}
println "==============================="
return 0
}
A non cps function does not have the ability to pause in between because it runs in a go. You need to put network call into a different function that is not marked as nonCPS and then it will work. In general the nonCPS block should be very small and limited to code that cannot be serialised
How can I join strings nicely into a path when programming Jenkins Groovy pipeline? So that I can join('http://example.com/', '/r', 'some.html') -> 'http://example.com/r/some.html'
This note suggests using new File(dir1, dir2) or Paths.get(dir1, dir2) in "pure" Groovy.
However in Jenkins pipeline, import java.nio.file.Paths gives me
No such static method found: staticMethod java.nio.file.Paths get java.lang.String org.codehaus.groovy.runtime.GStringImpl.
and with new File I get
Scripts not permitted to use new java.io.File java.lang.String java.lang.String. Administrators can decide whether to approve or reject this signature.
and I kinda agree with Jenkins on this do not want to allow this. Is there another way?
bad idea to build url with Paths or File objects because under windows you'll get wrong result.
you can build url with simple string concatenation and use URI.normalize() to remove extra slashes:
def u = new URI(['http://example.com/', '/r', 'some.html'].join('/')).normalize().toString()
Try this:
def join_two_urls(url1, url2) {
if (url1 == "" || url2 == "") {
println "Error: must provde two invalid urls."
return ""
}
println "Joining ${url1} and ${url2} ..."
if (url1 ==~ /.*\/$/) {
url1 = url1.substring(0, url1.length() - 1)
}
if (url2 ==~ /^\/.*/) {
url2 = url2.substring(1, url2.length())
}
return url1 + "/" + url2
}
def join_paths(String[] urls) {
if (urls.size() <= 1) {
println "Error: invalid urls."
return ""
}
conbined_url = ""
pre_url = ""
for (url in urls) {
if (pre_url == "") {
pre_url = url
continue
}
conbined_url += join_two_urls(pre_url, url)
}
return conbined_url
}
println join_paths("xx/", "xxx/" , "/fsdsdfsdf")
I am working on Jenkins version 2.32.1 pipeline. I want to extract the parameters that were chosen in the previous build of my job.
In our previous Jenkins instance ( 1.627 ) we were using jenkins.model.Jenkins.instance.getItem(job).lastBuild.getBuildVariables().get(param);
For some reason this is not working in this version (I also tried disabling the sandbox).
Any pointers on how to accomplish it?
Simplified version of the previous script:
def build = Jenkins.get().getItems(org.jenkinsci.plugins.workflow.job.WorkflowJob).find {it.displayName == 'YOUR_JOB_NAME_HERE'}?.getLastBuild()
build.actions.find{ it instanceof ParametersAction }?.parameters.each {echo "${it.name}=${it.value}"}
Actually a little bit shorter version for those who want to get the params for the current build from the previous run and is working on new 2+ Jenkins versions.
To get 1 particular parameter:
def cls = currentBuild.getPreviousBuild().getRawBuild().actions.find{ it instanceof ParametersAction }?.parameters.find{it.name == 'cls'}?.value
Get all params respectfully:
def cls = currentBuild.getPreviousBuild().getRawBuild().actions.find{ it instanceof ParametersAction }?.parameters
Something like this might work, based on https://stackoverflow.com/a/19564602/3920342:
def h = hudson.model.Hudson.instance
def r = null
h.getItems(org.jenkinsci.plugins.workflow.job.WorkflowJob).each {project ->
if (project.displayName.equals('YOUR_JOB_NAME')) {
r = project
}
}
r.getBuilds().findAll { b -> // here we loop over all past builds, apply some filter if necessary
def p = b?.actions.find{ it instanceof ParametersAction }?.parameters
p.each {
echo "parameter ${it.name}: ${it.value}"
}
}
For those who are not able to access getActions() due to admin permissions i.e. facing the following error:
Scripts not permitted to use method hudson.model.Actionable getActions
They can copy the parameter variables to the env and get them using build.previousBuild.buildVariables
stage('Prepare environment') {
steps {
script {
env.MY_PARAM_COPY = "${MY_PARAM}"
}
}
}
println("MY_PARAM in previous build: ${currentBuild.previousBuild.buildVariables["MY_PARAM_COPY"]}")
That's how I made it works, answer from #dan.goriaynov and #jherb caused some CPS closure issues for me.
(the gist of the code is to allow only greater TAG number than the previous one to be deployed)
stage('Validate build number') {
def previous_build = currentBuild.getPreviousBuild().getRawBuild();
def PREVIOUS_TAG = '';
for (int i = 0; i < previous_build.allActions.size(); i++) {
if (previous_build.allActions[i] in hudson.model.ParametersAction) {
PREVIOUS_TAG = previous_build.allActions[i].getParameter("TAG").value
}
}
if (PREVIOUS_TAG.toInteger() > TAG.toInteger()) {
echo PREVIOUS_TAG
error('TAG number needs to be greater than the previous one')
}
}
The script is not iterating through all the values of the 'modules' array.
class Module {
public String name = '';
public Boolean isCustom = false;
public Module(String name, Boolean custom){
this.name = name;
this.isCustom = custom;
}
}
//creates array from the ext_module env var
modules = [];
EXT_MODULE.split(',').each {
modules.add(new Module(it, false));
}
println modules;
modules.each {
println "MODULE NAME ::::: ${it.name}"
if(it.isCustom)
{
println "install custom";
} else {
println "install non custom";
}
};
This is the result of the run. The array shows 4 elements, but the code inside the .each black only executes once.
Running: Print Message
[Module#71f09325, Module#e1ddb41, Module#7069a674, Module#1f68f952]
Running: Print Message
MODULE NAME ::::: puppetlabs-ntp
Running: Print Message
install non custom
Running: End of Workflow
Finished: SUCCESS
The messages "Running: Print Message" and "Running: End of Workflow" indicate that you are using the new workflow plugin: https://wiki.jenkins-ci.org/display/JENKINS/Workflow+Plugin. This plugin currently has a bug causing at least some Groovy iterations involving a closure to be aborted after one iteration: https://issues.jenkins-ci.org/browse/JENKINS-26481
The workaround is to simply use an old school for loop (code below).
Also, NonCPS is another workaround.
There is an open issue for this matter. See here: https://issues.jenkins-ci.org/browse/JENKINS-26481
Update, Oct 24th, 2016
/**
* Dumps environment varibles to the log, using an old school for loop.
*/
import com.cloudbees.groovy.cps.NonCPS
def version = '1.0'
#NonCPS
def dumpEnvVars() {
def str = "Dumping build environment variables...\n"
for (Map.Entry<String, String> entry : currentBuild.build().environment) {
str += " ${entry.key} = ${entry.value}\n"
}
echo str
}
return this;
As of yesterday, the new Pipeline plugin was delivered in version 2.0 and correct this problem.
.each closures now work, but .collect still only iterate once.