Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JENKINS-41272] Sketch of an APIStep #71

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@
<jenkins.version>2.121.1</jenkins.version>
<java.level>8</java.level>
<workflow-step-api-plugin.version>2.15</workflow-step-api-plugin.version>
<workflow-cps-plugin.version>2.32</workflow-cps-plugin.version>
<workflow-support-plugin.version>2.14</workflow-support-plugin.version>
<workflow-cps-plugin.version>2.55</workflow-cps-plugin.version>
<workflow-support-plugin.version>2.20</workflow-support-plugin.version>
<workflow-api-plugin.version>2.28</workflow-api-plugin.version>
<useBeta>true</useBeta>
</properties>
Expand Down Expand Up @@ -182,7 +182,7 @@
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>script-security</artifactId>
<version>1.28</version>
<version>1.46</version>
<scope>test</scope>
</dependency>
<dependency>
Expand All @@ -205,4 +205,13 @@
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>scm-api</artifactId>
<version>2.2.7</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
153 changes: 153 additions & 0 deletions src/main/java/org/jenkinsci/plugins/workflow/steps/APIStep.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/*
* The MIT License
*
* Copyright 2018 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

package org.jenkinsci.plugins.workflow.steps;

import hudson.Extension;
import hudson.model.Run;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.export.DataWriter;
import org.kohsuke.stapler.export.Flavor;
import org.kohsuke.stapler.export.ModelBuilder;
import org.kohsuke.stapler.export.NamedPathPruner;
import org.kohsuke.stapler.export.TreePruner;

/**
* Uses {@link DataWriter} to produce information about model objects.
*/
public final class APIStep extends Step {

public enum Format {
JSON,
STRUCTURE;
// TODO add XML, JSON pretty-print, etc.
public String getDisplayName() {
return name(); // TODO
}
}

private final String tree;
// TODO optional field for alternate job name (relativizable?) + Run.number
// TODO optional field for a (context-relative) URL to an arbitrary model object, if there were any way for Stapler dispatching to return this without actually running web methods or serving an index view
private Format format = DescriptorImpl.getDefaultFormat();

@DataBoundConstructor public APIStep(String tree) {
this.tree = tree;
}

public Format getFormat() {
return format;
}

@DataBoundSetter public void setFormat(Format format) {
this.format = format;
}

@Override public StepExecution start(StepContext context) throws Exception {
return new Execution(this, context);
}

private static final class Execution extends SynchronousStepExecution<Object> {

private static final long serialVersionUID = 1;

private transient final APIStep step;

Execution(APIStep step, StepContext context) {
super(context);
this.step = step;
}

@Override protected Object run() throws Exception {
StringWriter w = new StringWriter();
Run build = getContext().get(Run.class);
DataWriter writer = Flavor.JSON.createDataWriter(build, w);
TreePruner pruner = new NamedPathPruner(step.tree);
new ModelBuilder().get(Run.class).writeTo(build, pruner, writer);
String json = w.toString();
switch (step.format) {
case JSON:
return json;
case STRUCTURE:
return translate(JSONObject.fromObject(json));
default:
throw new IllegalStateException();
}
}
}


private static Object translate(Object o) {
if (o instanceof JSONObject) {
Map<String, Object> r = new LinkedHashMap<>();
for (Object _entry : ((JSONObject) o).entrySet()) {
Map.Entry<?, ?> entry = (Map.Entry) _entry;
r.put((String) entry.getKey(), translate(entry.getValue()));
}
return r;
} else if (o instanceof JSONArray) {
List<Object> r = new ArrayList<>();
for (Object element : (JSONArray) o) {
r.add(translate(element));
}
return r;
} else if (o instanceof JSONNull) {
return null;
} else {
return o;
}
}

@Extension public static final class DescriptorImpl extends StepDescriptor {

@Override public String getFunctionName() {
return "api";
}

@Override public String getDisplayName() {
return "Retrieve API metadata from a Jenkins model object";
}

@Override public Set<? extends Class<?>> getRequiredContext() {
return Collections.singleton(Run.class);
}

public static Format getDefaultFormat() {
return Format.STRUCTURE;
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
The MIT License

Copyright 2018 CloudBees, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->

<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:f="/lib/form">
<f:entry field="tree" title="Tree expression">
<f:textbox/>
</f:entry>
<f:enum field="format" default="${descriptor.defaultFormat}">
${it.displayName}
</f:enum>
</j:jelly>
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<div>
<code>tree</code> expression as it would be passed in HTTP query parameters.
See the <b>REST API</b> section of a build or other model object for more.
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<div>
Retrieves information about a model object such as the current build.
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* The MIT License
*
* Copyright 2018 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

package org.jenkinsci.plugins.workflow.steps;

import hudson.model.Cause;
import hudson.model.CauseAction;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.Rule;
import org.jvnet.hudson.test.BuildWatcher;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;

public class APIStepTest {

@ClassRule public static BuildWatcher buildWatcher = new BuildWatcher();

@Rule public JenkinsRule r = new JenkinsRule();

@Issue("JENKINS-41272")
@Test public void buildCauses() throws Exception {
WorkflowJob p = r.createProject(WorkflowJob.class, "p");
// .action*.causes notation not yet supported in groovy-cps:
p.setDefinition(new CpsFlowDefinition("echo(/looks like this was started by ${api('actions[causes[userId]]').actions.collect {it.causes.collect {it.userId}}.flatten()[0]}/)", true));
WorkflowRun b = r.assertBuildStatusSuccess(p.scheduleBuild2(0, new CauseAction(new Cause.UserIdCause("tester"))));
r.assertLogContains("looks like this was started by tester", b);
}

}