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

Refactor PhabricatorNotifier comment builder #48

Merged
merged 3 commits into from
Jul 20, 2015
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
158 changes: 158 additions & 0 deletions src/main/java/com/uber/jenkins/phabricator/CommentBuilder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
// Copyright (c) 2015 Uber Technologies, 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 com.uber.jenkins.phabricator;

import com.uber.jenkins.phabricator.utils.CommonUtils;
import com.uber.jenkins.phabricator.utils.Logger;
import hudson.model.Result;
import hudson.plugins.cobertura.Ratio;
import hudson.plugins.cobertura.targets.CoverageMetric;
import hudson.plugins.cobertura.targets.CoverageResult;

public class CommentBuilder {
private static final String UBERALLS_TAG = "uberalls";
private final Logger logger;
private final CoverageResult currentCoverage;
private final StringBuilder comment;
private final String buildURL;
private final Result result;

public CommentBuilder(Logger logger, Result result, CoverageResult currentCoverage, String buildURL) {
this.logger = logger;
this.result = result;
this.currentCoverage = currentCoverage;
this.buildURL = buildURL;
this.comment = new StringBuilder();
}

/**
* Get the final comment to post to Phabricator
* @return
*/
public String getComment() {
return comment.toString();
}

/**
* Determine whether to attempt to process coverage
* @return
*/
public boolean hasCoverageAvailable() {
if (currentCoverage == null) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can simplify this to:

return currentCoverage != null && currentCoverage.getCoverage(CoverageMetric.LINE) != null;

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call. Done.

return false;
}

Ratio lineCoverage = currentCoverage.getCoverage(CoverageMetric.LINE);
return lineCoverage != null;
}

/**
* Query uberalls for parent coverage and add appropriate comment
* @param parentCoverage the parent coverage returned from uberalls
* @param branchName the name of the current branch
*/
public void processParentCoverage(CodeCoverageMetrics parentCoverage, String branchName) {
if (parentCoverage == null) {
logger.info(UBERALLS_TAG, "unable to find coverage for parent commit");
return;
}

Ratio lineCoverage = currentCoverage.getCoverage(CoverageMetric.LINE);
Float lineCoveragePercent = lineCoverage.getPercentageFloat();

logger.info(UBERALLS_TAG, "line coverage: " + lineCoveragePercent);
logger.info(UBERALLS_TAG, "found parent coverage as " + parentCoverage.getLineCoveragePercent());

float coverageDelta = lineCoveragePercent - parentCoverage.getLineCoveragePercent();

String coverageDeltaDisplay = String.format("%.3f", coverageDelta);
String lineCoverageDisplay = String.format("%.3f", lineCoveragePercent);

if (coverageDelta > 0) {
comment.append("Coverage increased (+" + coverageDeltaDisplay + "%) to " + lineCoverageDisplay + "%");
} else if (coverageDelta < 0) {
comment.append("Coverage decreased (" + coverageDeltaDisplay + "%) to " + lineCoverageDisplay + "%");
} else {
comment.append("Coverage remained the same (" + lineCoverageDisplay + "%)");
}

comment.append(" when pulling **" + branchName + "** into ");
comment.append(parentCoverage.getSha1().substring(0, 7));
comment.append(". See " + buildURL + "cobertura for the coverage report");
}

public void processBuildResult(boolean commentOnSuccess, boolean commentWithConsoleLinkOnFailure, boolean runHarbormaster) {
if (result == result.SUCCESS) {
if (comment.length() == 0 && (commentOnSuccess || !runHarbormaster)) {
comment.append("Build is green");
}
} else if (result == Result.UNSTABLE) {
comment.append("Build is unstable");
} else if (result == Result.FAILURE) {
if (!runHarbormaster || commentWithConsoleLinkOnFailure) {
comment.append("Build has FAILED");
}
} else if (result == Result.ABORTED) {
comment.append("Build was aborted");
} else {
logger.info(UBERALLS_TAG, "Unknown build status " + result.toString());
}
}

/**
* Add user-defined content via a .phabricator-comment file
* @param customComment the contents of the file
*/
public void addUserComment(String customComment) {
if (CommonUtils.isBlank(customComment)) {
return;
}

// Ensure we separate previous parts of the comment with newlines
if (hasComment()) {
comment.append("\n\n");
}
comment.append(String.format("```\n%s\n```\n\n", customComment));
}

/**
* Determine if there exists a comment already
* @return
*/
public boolean hasComment() {
return comment.length() > 0;
}

/**
* Add a build link to the comment
*/
public void addBuildLink() {
comment.append(String.format(" %s for more details.", buildURL));
}

/**
* Add a build failure message to the comment
*/
public void addBuildFailureMessage() {
comment.append(String.format("\n\nLink to build: %s", buildURL));
comment.append(String.format("\nSee console output for more information: %sconsole", buildURL));
}
}
90 changes: 18 additions & 72 deletions src/main/java/com/uber/jenkins/phabricator/PhabricatorNotifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.plugins.cobertura.CoberturaBuildAction;
import hudson.plugins.cobertura.Ratio;
import hudson.plugins.cobertura.targets.CoverageMetric;
import hudson.plugins.cobertura.targets.CoverageResult;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
Expand Down Expand Up @@ -128,42 +126,29 @@ public final boolean perform(final AbstractBuild<?, ?> build, final Launcher lau

String phid = environment.get(PhabricatorPlugin.PHID_FIELD);

boolean runHarbormaster = phid != null && !"".equals(phid);
boolean runHarbormaster = !CommonUtils.isBlank(phid);
boolean harbormasterSuccess = false;

String comment = null;
CommentBuilder commenter = new CommentBuilder(logger, build.getResult(), coverage, environment.get("BUILD_URL"));

if (coverage != null) {
Ratio lineCoverage = coverage.getCoverage(CoverageMetric.LINE);
if (lineCoverage == null) {
logger.info("uberalls", "no line coverage found, skipping...");
// First add in info about the change in coverage, if applicable
if (commenter.hasCoverageAvailable()) {
if (uberallsConfigured) {
commenter.processParentCoverage(uberalls.getParentCoverage(diff), diff.getBranch());
} else {
if (uberallsConfigured) {
comment = getCoverageComment(lineCoverage, uberalls, diff, logger.getStream(), environment.get("BUILD_URL"));
} else {
logger.info("uberalls", "no backend configured, skipping...");
}
logger.info("uberalls", "no backend configured, skipping...");
}
} else {
logger.info("uberalls", "no line coverage found, skipping...");
}

if (build.getResult().isBetterOrEqualTo(Result.SUCCESS)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we just remove this entire thing and set the flag when the variable is instantiated?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome. Really appreciate your fine-toothed-comb reviews :D

harbormasterSuccess = true;
if (comment == null && (this.commentOnSuccess || !runHarbormaster)) {
comment = "Build is green";
}
} else if (build.getResult() == Result.UNSTABLE) {
comment = "Build is unstable";
} else if (build.getResult() == Result.FAILURE) {
// TODO look for message here.
if (!runHarbormaster || this.commentWithConsoleLinkOnFailure) {
comment = "Build has FAILED";
}
} else if (build.getResult() == Result.ABORTED) {
comment = "Build was aborted";
} else {
logger.info("uberalls", "Unknown build status " + build.getResult().toString());
}

// Add in comments about the build result
commenter.processBuildResult(this.commentOnSuccess, this.commentWithConsoleLinkOnFailure, runHarbormaster);

String commentAction = "none";
if (runHarbormaster) {
logger.info("uberalls", "Sending build result to Harbormaster with PHID '" + phid + "', success: " + harbormasterSuccess);
Expand All @@ -182,33 +167,25 @@ public final boolean perform(final AbstractBuild<?, ?> build, final Launcher lau
}
}

String customComment;
try {
customComment = getRemoteComment(build, logger.getStream(), this.commentFile, this.commentSize);

if (!CommonUtils.isBlank(customComment)) {
if (comment == null) {
comment = String.format("```\n%s\n```\n\n", customComment);
} else {
comment = String.format("%s\n\n```\n%s\n```\n", comment, customComment);
}
}
String customComment = getRemoteComment(build, logger.getStream(), this.commentFile, this.commentSize);
commenter.addUserComment(customComment);
} catch (InterruptedException e) {
e.printStackTrace(logger.getStream());
} catch (IOException e) {
Util.displayIOException(e, listener);
}

if (comment != null) {
if (commenter.hasComment()) {
boolean silent = false;
if (this.commentWithConsoleLinkOnFailure && build.getResult().isWorseOrEqualTo(Result.UNSTABLE)) {
comment += String.format("\n\nLink to build: %s", environment.get("BUILD_URL"));
comment += String.format("\nSee console output for more information: %sconsole", environment.get("BUILD_URL"));
commenter.addBuildFailureMessage();
} else {
comment += String.format(" %s for more details.", environment.get("BUILD_URL"));
commenter.addBuildLink();
}

JSONObject result = null;
String comment = commenter.getComment();
try {
result = diffClient.postComment(comment, silent, commentAction);
} catch (ArcanistUsageException e) {
Expand All @@ -228,37 +205,6 @@ public final boolean perform(final AbstractBuild<?, ?> build, final Launcher lau
return true;
}

private String getCoverageComment(Ratio lineCoverage, UberallsClient uberalls, Differential diff,
PrintStream logger, String buildUrl) {
Float lineCoveragePercent = lineCoverage.getPercentageFloat();
logger.println("[uberalls] line coverage: " + lineCoveragePercent);
logger.println("[uberalls] fetching coverage from " + uberalls.getBaseURL());
CodeCoverageMetrics parentCoverage = uberalls.getParentCoverage(diff);
if (parentCoverage == null) {
logger.println("[uberalls] unable to find coverage for parent commit (" + diff.getBaseCommit() + ")");
return null;
} else {
logger.println("[uberalls] found parent coverage as " + parentCoverage.getLineCoveragePercent());
String coverageComment;
float coverageDelta = lineCoveragePercent - parentCoverage.getLineCoveragePercent();
String coverageDeltaDisplay = String.format("%.3f", coverageDelta);
String lineCoverageDisplay = String.format("%.3f", lineCoveragePercent);
if (coverageDelta > 0) {
coverageComment = "Coverage increased (+" + coverageDeltaDisplay + "%) to " + lineCoverageDisplay + "%";
} else if (coverageDelta < 0) {
coverageComment = "Coverage decreased (" + coverageDeltaDisplay + "%) to " + lineCoverageDisplay + "%";
} else {
coverageComment = "Coverage remained the same (" + lineCoverageDisplay + "%)";
}

final String coberturaUrl = buildUrl + "cobertura";
coverageComment += " when pulling **" + diff.getBranch() + "** into " +
parentCoverage.getSha1().substring(0, 7) + ". See " + coberturaUrl + " for the coverage report";

return coverageComment;
}
}

/**
* Attempt to read a remote comment file
* @param build the build
Expand Down