Add MergeRequestNotifier that provides common used methods for GitLabVotePublisher and GitLabMessagePublisher

This commit is contained in:
Robin Müller 2016-09-04 18:15:27 +02:00
parent f9577ca03a
commit 1cae833f60
5 changed files with 97 additions and 117 deletions

View File

@ -1,38 +1,29 @@
package com.dabsquared.gitlabjenkins.publisher;
import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause;
import com.dabsquared.gitlabjenkins.gitlab.api.GitLabApi;
import hudson.Extension;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.DataBoundConstructor;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.WebApplicationException;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty.getClient;
/**
* @author Nikolay Ustinov
*/
public class GitLabMessagePublisher extends Notifier {
public class GitLabMessagePublisher extends MergeRequestNotifier {
private static final Logger LOGGER = Logger.getLogger(GitLabMessagePublisher.class.getName());
private boolean replaceSuccessNote = false;
private boolean replaceFailureNote = false;
@ -78,16 +69,6 @@ public class GitLabMessagePublisher extends Notifier {
return this.abortNoteText == null ? "" : this.abortNoteText;
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
addNoteOnMergeRequest(build, listener);
return true;
}
@Extension
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
@ -107,34 +88,16 @@ public class GitLabMessagePublisher extends Notifier {
}
}
private void addNoteOnMergeRequest(Run<?, ?> build, TaskListener listener) {
String projectId = getProjectId(build);
Integer mergeRequestId = getMergeRequestId(build);
if (projectId != null && mergeRequestId != null) {
try {
GitLabApi client = getClient(build);
if (client == null) {
listener.getLogger().println("No GitLab connection configured");
} else {
client.createMergeRequestNote(projectId, mergeRequestId, getNote(build, listener));
}
} catch (WebApplicationException | ProcessingException e) {
listener.getLogger().printf("Failed to add comment on Merge Request for project '%s': %s%n", projectId, e.getMessage());
LOGGER.log(Level.SEVERE, String.format("Failed to add comment on Merge Request for project '%s'", projectId), e);
}
@Override
protected void perform(Run<?, ?> build, TaskListener listener, GitLabApi client, Integer projectId, Integer mergeRequestId) {
try {
client.createMergeRequestNote(projectId, mergeRequestId, getNote(build, listener));
} catch (WebApplicationException | ProcessingException e) {
listener.getLogger().printf("Failed to add comment on Merge Request for project '%s': %s%n", projectId, e.getMessage());
LOGGER.log(Level.SEVERE, String.format("Failed to add comment on Merge Request for project '%s'", projectId), e);
}
}
String getProjectId(Run<?, ?> build) {
GitLabWebHookCause cause = build.getCause(GitLabWebHookCause.class);
return cause == null ? null : cause.getData().getTargetProjectId().toString();
}
Integer getMergeRequestId(Run<?, ?> build) {
GitLabWebHookCause cause = build.getCause(GitLabWebHookCause.class);
return cause == null ? null : cause.getData().getMergeRequestId();
}
private String getResultIcon(Result result) {
if (result == Result.SUCCESS) {
return ":white_check_mark:";

View File

@ -1,33 +1,25 @@
package com.dabsquared.gitlabjenkins.publisher;
import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause;
import com.dabsquared.gitlabjenkins.gitlab.api.GitLabApi;
import hudson.Extension;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;
import org.kohsuke.stapler.DataBoundConstructor;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.WebApplicationException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty.getClient;
/**
* @author Robin Müller
*/
public class GitLabVotePublisher extends Notifier {
public class GitLabVotePublisher extends MergeRequestNotifier {
private static final Logger LOGGER = Logger.getLogger(GitLabVotePublisher.class.getName());
@DataBoundConstructor
@ -37,12 +29,6 @@ public class GitLabVotePublisher extends Notifier {
return BuildStepMonitor.NONE;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
addVoteOnMergeRequest(build, listener);
return true;
}
@Extension
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
@ -57,34 +43,16 @@ public class GitLabVotePublisher extends Notifier {
}
}
private void addVoteOnMergeRequest(Run<?, ?> build, TaskListener listener) {
String projectId = getProjectId(build);
Integer mergeRequestId = getMergeRequestId(build);
if (projectId != null && mergeRequestId != null) {
try {
GitLabApi client = getClient(build);
if (client == null) {
listener.getLogger().println("No GitLab connection configured");
} else {
client.createMergeRequestNote(projectId, mergeRequestId, getResultIcon(build.getResult()));
}
} catch (WebApplicationException | ProcessingException e) {
listener.getLogger().printf("Failed to add vote on Merge Request for project '%s': %s%n", projectId, e.getMessage());
LOGGER.log(Level.SEVERE, String.format("Failed to add vote on Merge Request for project '%s'", projectId), e);
}
@Override
protected void perform(Run<?, ?> build, TaskListener listener, GitLabApi client, Integer projectId, Integer mergeRequestId) {
try {
client.createMergeRequestNote(projectId, mergeRequestId, getResultIcon(build.getResult()));
} catch (WebApplicationException | ProcessingException e) {
listener.getLogger().printf("Failed to add vote on Merge Request for project '%s': %s%n", projectId, e.getMessage());
LOGGER.log(Level.SEVERE, String.format("Failed to add vote on Merge Request for project '%s'", projectId), e);
}
}
String getProjectId(Run<?, ?> build) {
GitLabWebHookCause cause = build.getCause(GitLabWebHookCause.class);
return cause == null ? null : cause.getData().getTargetProjectId().toString();
}
Integer getMergeRequestId(Run<?, ?> build) {
GitLabWebHookCause cause = build.getCause(GitLabWebHookCause.class);
return cause == null ? null : cause.getData().getMergeRequestId();
}
private String getResultIcon(Result result) {
if (result == Result.SUCCESS) {
return ":+1:";

View File

@ -0,0 +1,51 @@
package com.dabsquared.gitlabjenkins.publisher;
import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause;
import com.dabsquared.gitlabjenkins.gitlab.api.GitLabApi;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import java.io.IOException;
import static com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty.getClient;
/**
* @author Robin Müller
*/
public abstract class MergeRequestNotifier extends Notifier {
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
GitLabApi client = getClient(build);
if (client == null) {
listener.getLogger().println("No GitLab connection configured");
return true;
}
Integer projectId = getProjectId(build);
Integer mergeRequestId = getMergeRequestId(build);
if (projectId != null && mergeRequestId != null) {
perform(build, listener, client, projectId, mergeRequestId);
}
return true;
}
protected abstract void perform(Run<?, ?> build, TaskListener listener, GitLabApi client, Integer projectId, Integer mergeRequestId);
Integer getProjectId(Run<?, ?> build) {
GitLabWebHookCause cause = build.getCause(GitLabWebHookCause.class);
return cause == null ? null : cause.getData().getTargetProjectId();
}
Integer getMergeRequestId(Run<?, ?> build) {
GitLabWebHookCause cause = build.getCause(GitLabWebHookCause.class);
return cause == null ? null : cause.getData().getMergeRequestId();
}
}

View File

@ -33,7 +33,6 @@ import org.mockserver.model.HttpRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.Arrays;
@ -94,15 +93,15 @@ public class GitLabMessagePublisherTest {
@Test
public void canceled() throws IOException, InterruptedException {
Integer buildNumber = 1;
String projectId = "3";
Integer projectId = 3;
Integer mergeRequestId = 1;
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.ABORTED, buildNumber, projectId);
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.ABORTED, buildNumber);
String buildUrl = Jenkins.getInstance().getRootUrl() + build.getUrl();
String defaultNote = MessageFormat.format(":point_up: Jenkins Build {0}\n\nResults available at: [Jenkins [{1} #{2}]]({3})",
Result.ABORTED, build.getParent().getDisplayName(), buildNumber, buildUrl);
HttpRequest[] requests = new HttpRequest[] {
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId.toString(), defaultNote)
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId, defaultNote)
};
GitLabMessagePublisher publisher = spy(new GitLabMessagePublisher(false, false, false, null, null, null));
@ -116,15 +115,15 @@ public class GitLabMessagePublisherTest {
@Test
public void success() throws IOException, InterruptedException {
Integer buildNumber = 1;
String projectId = "3";
Integer projectId = 3;
Integer mergeRequestId = 1;
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.SUCCESS, buildNumber, projectId);
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.SUCCESS, buildNumber);
String buildUrl = Jenkins.getInstance().getRootUrl() + build.getUrl();
String defaultNote = MessageFormat.format(":white_check_mark: Jenkins Build {0}\n\nResults available at: [Jenkins [{1} #{2}]]({3})",
Result.SUCCESS, build.getParent().getDisplayName(), buildNumber, buildUrl);
HttpRequest[] requests = new HttpRequest[] {
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId.toString(), defaultNote)
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId, defaultNote)
};
GitLabMessagePublisher publisher = spy(new GitLabMessagePublisher(false, false, false, null, null, null));
@ -138,15 +137,15 @@ public class GitLabMessagePublisherTest {
@Test
public void failed() throws IOException, InterruptedException {
Integer buildNumber = 1;
String projectId = "3";
Integer projectId = 3;
Integer mergeRequestId = 1;
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.FAILURE, buildNumber, projectId);
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.FAILURE, buildNumber);
String buildUrl = Jenkins.getInstance().getRootUrl() + build.getUrl();
String defaultNote = MessageFormat.format(":negative_squared_cross_mark: Jenkins Build {0}\n\nResults available at: [Jenkins [{1} #{2}]]({3})",
Result.FAILURE, build.getParent().getDisplayName(), buildNumber, buildUrl);
HttpRequest[] requests = new HttpRequest[] {
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId.toString(), defaultNote)
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId, defaultNote)
};
GitLabMessagePublisher publisher = spy(new GitLabMessagePublisher(false, false, false, null, null, null));
@ -160,13 +159,13 @@ public class GitLabMessagePublisherTest {
@Test
public void canceledWithCustomNote() throws IOException, InterruptedException {
Integer buildNumber = 1;
String projectId = "3";
Integer projectId = 3;
Integer mergeRequestId = 1;
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.ABORTED, buildNumber, projectId);
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.ABORTED, buildNumber);
String defaultNote = "abort";
HttpRequest[] requests = new HttpRequest[] {
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId.toString(), defaultNote)
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId, defaultNote)
};
GitLabMessagePublisher publisher = spy(new GitLabMessagePublisher(false, false, true, null, null, defaultNote));
@ -180,13 +179,13 @@ public class GitLabMessagePublisherTest {
@Test
public void successWithCustomNote() throws IOException, InterruptedException {
Integer buildNumber = 1;
String projectId = "3";
Integer projectId = 3;
Integer mergeRequestId = 1;
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.SUCCESS, buildNumber, projectId);
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.SUCCESS, buildNumber);
String defaultNote = "success";
HttpRequest[] requests = new HttpRequest[] {
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId.toString(), defaultNote)
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId, defaultNote)
};
GitLabMessagePublisher publisher = spy(new GitLabMessagePublisher(true, false, false, defaultNote, null, null));
@ -200,13 +199,13 @@ public class GitLabMessagePublisherTest {
@Test
public void failedWithCustomNote() throws IOException, InterruptedException {
Integer buildNumber = 1;
String projectId = "3";
Integer projectId = 3;
Integer mergeRequestId = 1;
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.FAILURE, buildNumber, projectId);
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.FAILURE, buildNumber);
String defaultNote = "failure";
HttpRequest[] requests = new HttpRequest[] {
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId.toString(), defaultNote)
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId, defaultNote)
};
GitLabMessagePublisher publisher = spy(new GitLabMessagePublisher(false, true, false, null, defaultNote, null));
@ -217,15 +216,15 @@ public class GitLabMessagePublisherTest {
mockServerClient.verify(requests);
}
private HttpRequest prepareSendMessageWithSuccessResponse(String projectId, String mergeRequestId, String body) throws UnsupportedEncodingException {
private HttpRequest prepareSendMessageWithSuccessResponse(Integer projectId, Integer mergeRequestId, String body) throws UnsupportedEncodingException {
HttpRequest updateCommitStatus = prepareSendMessageStatus(projectId, mergeRequestId, body);
mockServerClient.when(updateCommitStatus).respond(response().withStatusCode(200));
return updateCommitStatus;
}
private HttpRequest prepareSendMessageStatus(String projectId, String mergeRequestId, String body) throws UnsupportedEncodingException {
private HttpRequest prepareSendMessageStatus(Integer projectId, Integer mergeRequestId, String body) throws UnsupportedEncodingException {
return request()
.withPath("/gitlab/api/v3/projects/" + URLEncoder.encode(projectId, "UTF-8") + "/merge_requests/" + URLEncoder.encode(mergeRequestId, "UTF-8") + "/notes")
.withPath("/gitlab/api/v3/projects/" + projectId + "/merge_requests/" + mergeRequestId + "/notes")
.withMethod("POST")
.withHeader("PRIVATE-TOKEN", "secret")
.withQueryStringParameter("body", body);

View File

@ -29,7 +29,6 @@ import org.mockserver.model.HttpRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.Arrays;
@ -88,15 +87,15 @@ public class GitLabVotePublisherTest {
@Test
public void success() throws IOException, InterruptedException {
Integer buildNumber = 1;
String projectId = "3";
Integer projectId = 3;
Integer mergeRequestId = 1;
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.SUCCESS, buildNumber, projectId);
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.SUCCESS, buildNumber);
String buildUrl = Jenkins.getInstance().getRootUrl() + build.getUrl();
String defaultNote = MessageFormat.format(":+1:",
Result.SUCCESS, build.getParent().getDisplayName(), buildNumber, buildUrl);
HttpRequest[] requests = new HttpRequest[] {
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId.toString(), defaultNote)
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId, defaultNote)
};
GitLabVotePublisher publisher = spy(new GitLabVotePublisher());
@ -110,15 +109,15 @@ public class GitLabVotePublisherTest {
@Test
public void failed() throws IOException, InterruptedException {
Integer buildNumber = 1;
String projectId = "3";
Integer projectId = 3;
Integer mergeRequestId = 1;
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.FAILURE, buildNumber, projectId);
AbstractBuild build = mockBuild("/build/123", GIT_LAB_CONNECTION, Result.FAILURE, buildNumber);
String buildUrl = Jenkins.getInstance().getRootUrl() + build.getUrl();
String defaultNote = MessageFormat.format(":-1:",
Result.FAILURE, build.getParent().getDisplayName(), buildNumber, buildUrl);
HttpRequest[] requests = new HttpRequest[] {
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId.toString(), defaultNote)
prepareSendMessageWithSuccessResponse(projectId, mergeRequestId, defaultNote)
};
GitLabVotePublisher publisher = spy(new GitLabVotePublisher());
@ -129,15 +128,15 @@ public class GitLabVotePublisherTest {
mockServerClient.verify(requests);
}
private HttpRequest prepareSendMessageWithSuccessResponse(String projectId, String mergeRequestId, String body) throws UnsupportedEncodingException {
private HttpRequest prepareSendMessageWithSuccessResponse(Integer projectId, Integer mergeRequestId, String body) throws UnsupportedEncodingException {
HttpRequest updateCommitStatus = prepareSendMessageStatus(projectId, mergeRequestId, body);
mockServerClient.when(updateCommitStatus).respond(response().withStatusCode(200));
return updateCommitStatus;
}
private HttpRequest prepareSendMessageStatus(String projectId, String mergeRequestId, String body) throws UnsupportedEncodingException {
private HttpRequest prepareSendMessageStatus(Integer projectId, Integer mergeRequestId, String body) throws UnsupportedEncodingException {
return request()
.withPath("/gitlab/api/v3/projects/" + URLEncoder.encode(projectId, "UTF-8") + "/merge_requests/" + URLEncoder.encode(mergeRequestId, "UTF-8") + "/notes")
.withPath("/gitlab/api/v3/projects/" + projectId + "/merge_requests/" + mergeRequestId + "/notes")
.withMethod("POST")
.withHeader("PRIVATE-TOKEN", "secret")
.withQueryStringParameter("body", body);