Skip to content
This repository was archived by the owner on Jan 7, 2021. It is now read-only.

Commit 09a70e8

Browse files
committed
implement resetting of overview comments
1 parent ab72441 commit 09a70e8

File tree

6 files changed

+115
-56
lines changed

6 files changed

+115
-56
lines changed

src/main/java/org/sonar/plugins/stash/StashPluginUtils.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
import com.google.common.base.CharMatcher;
44
import java.io.IOException;
55
import java.util.Collection;
6+
import java.util.Optional;
67
import java.util.Properties;
8+
import java.util.stream.Stream;
79
import org.sonar.api.batch.fs.InputComponent;
810
import org.sonar.api.batch.fs.InputModule;
911
import org.sonar.api.batch.postjob.issue.PostJobIssue;
@@ -72,4 +74,8 @@ public static String removeEnd(String s, String suffix) {
7274
}
7375
return s;
7476
}
77+
78+
public static <T> Stream<T> removeEmpty(Optional<T> v) {
79+
return v.map(Stream::of).orElse(Stream.empty());
80+
}
7581
}

src/main/java/org/sonar/plugins/stash/StashRequestFacade.java

Lines changed: 32 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -398,39 +398,46 @@ public void resetComments(PullRequestRef pr,
398398
StashUser sonarUser,
399399
StashClient stashClient) {
400400
try {
401-
// Let's call this "diffRep_loop"
402-
for (StashComment comment : diffReport.getComments()) {
403-
404-
// delete comment only if published by the current SQ user
405-
if (sonarUser.getId() != comment.getAuthor().getId()) {
406-
continue;
407-
// Next element in "diffRep_loop"
408-
409-
// comment contains tasks which cannot be deleted => do nothing
410-
} else if (comment.containsPermanentTasks()) {
411-
LOGGER.debug("Comment \"{}\" (path:\"{}\", line:\"{}\")"
412-
+ "CANNOT be deleted because one of its tasks is not deletable.", comment.getId(),
413-
comment.getPath(),
414-
comment.getLine());
415-
continue; // Next element in "diffRep_loop"
416-
}
417-
418-
// delete tasks linked to the current comment
419-
for (StashTask task : comment.getTasks()) {
420-
stashClient.deleteTaskOnComment(task);
421-
}
422-
423-
stashClient.deletePullRequestComment(pr, comment);
424-
}
401+
// FIXME delete tasks on file-wide comments
402+
// resetComments(diffReport.getComments(), pr, sonarUser, stashClient);
403+
resetComments(stashClient.getPullRequestOverviewComments(pr), pr, sonarUser, stashClient);
425404

426405
LOGGER.info("SonarQube issues reported to Stash by user \"{}\" have been reset",
427406
sonarUser.getName());
428-
429407
} catch (StashClientException e) {
430408
LOGGER.error("Unable to reset comment list", e);
431409
}
432410
}
433411

412+
private void resetComments(Collection<StashComment> comments, PullRequestRef pr, StashUser sonarUser, StashClient stashClient)
413+
throws StashClientException {
414+
for (StashComment comment : comments) {
415+
if (comment.getId() == 2079776) {
416+
LOGGER.warn(comment.toString());
417+
LOGGER.warn(comment.getTasks().toString());
418+
}
419+
420+
if (sonarUser.getId() != comment.getAuthor().getId()) {
421+
continue;
422+
}
423+
424+
if (comment.containsPermanentTasks()) {
425+
LOGGER.debug("Comment \"{}\" (path:\"{}\", line:\"{}\")"
426+
+ "CANNOT be deleted because one of its tasks is not deletable.", comment.getId(),
427+
comment.getPath(),
428+
comment.getLine());
429+
continue; // Next element in "diffRep_loop"
430+
}
431+
432+
// delete tasks linked to the current comment
433+
for (StashTask task : comment.getTasks()) {
434+
stashClient.deleteTaskOnComment(task);
435+
}
436+
437+
stashClient.deletePullRequestComment(pr, comment);
438+
}
439+
}
440+
434441
@Override
435442
public String getIssuePath(PostJobIssue issue) {
436443
InputComponent ip = issue.inputComponent();

src/main/java/org/sonar/plugins/stash/client/StashClient.java

Lines changed: 53 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package org.sonar.plugins.stash.client;
22

3+
import java.util.Collection;
34
import java.util.Optional;
5+
import java.util.stream.Collectors;
46
import org.asynchttpclient.AsyncHttpClient;
57
import org.asynchttpclient.BoundRequestBuilder;
68
import org.asynchttpclient.DefaultAsyncHttpClient;
@@ -19,7 +21,6 @@
1921
import org.sonar.plugins.stash.PeekableInputStream;
2022
import org.sonar.plugins.stash.PluginInfo;
2123
import org.sonar.plugins.stash.PullRequestRef;
22-
import org.sonar.plugins.stash.StashPlugin;
2324
import org.sonar.plugins.stash.StashPlugin.IssueType;
2425
import org.sonar.plugins.stash.StashPluginUtils;
2526
import org.sonar.plugins.stash.exceptions.StashClientException;
@@ -64,7 +65,7 @@ public class StashClient implements AutoCloseable {
6465
private static final String API_ONE_PR_ALL_COMMENTS = API_ONE_PR + "/comments";
6566
private static final String API_ONE_PR_DIFF = API_ONE_PR + "/diff?withComments=true";
6667
private static final String API_ONE_PR_APPROVAL = API_ONE_PR + "/approve";
67-
private static final String API_ONE_PR_COMMENT_PATH = API_ONE_PR + "/comments?path={4}&start={5,number,#}";
68+
private static final String API_ONE_PR_COMMENT_PATH = API_ONE_PR + "/comments?path={4}";
6869

6970
private static final String API_ONE_PR_ONE_COMMENT = API_ONE_PR_ALL_COMMENTS + "/{4}?version={5}";
7071

@@ -111,31 +112,29 @@ public void postCommentOnPullRequest(PullRequestRef pr, String report)
111112
postCreate(request, json, MessageFormat.format(COMMENT_POST_ERROR_MESSAGE, pr.repository(), pr.pullRequestId()));
112113
}
113114

115+
public Collection<StashComment> getPullRequestOverviewComments(PullRequestRef pr) throws StashClientException {
116+
return getPaged(
117+
MessageFormat.format(API_ONE_PR + "/activities", baseUrl, pr.project(), pr.repository(), pr.pullRequestId()),
118+
"Error!"
119+
).stream().map(StashCollector::extractCommentFromActivity).flatMap(StashPluginUtils::removeEmpty).collect(Collectors.toList());
120+
}
121+
114122
public StashCommentReport getPullRequestComments(PullRequestRef pr, String path)
115123
throws StashClientException {
116124
StashCommentReport result = new StashCommentReport();
117125

118-
long start = 0;
119-
boolean isLastPage = false;
126+
String url = MessageFormat.format(API_ONE_PR_COMMENT_PATH,
127+
baseUrl,
128+
pr.project(),
129+
pr.repository(),
130+
pr.pullRequestId(),
131+
path
132+
);
120133

121-
while (!isLastPage) {
134+
for (JsonObject jsonComment: getPaged(url,
135+
MessageFormat.format(COMMENT_GET_ERROR_MESSAGE, pr.repository(), pr.pullRequestId()))) {
122136
try {
123-
String request = MessageFormat.format(API_ONE_PR_COMMENT_PATH,
124-
baseUrl,
125-
pr.project(),
126-
pr.repository(),
127-
pr.pullRequestId(),
128-
path,
129-
start);
130-
JsonObject jsonComments = get(request,
131-
MessageFormat.format(COMMENT_GET_ERROR_MESSAGE,
132-
pr.repository(),
133-
pr.pullRequestId()));
134-
result.add(StashCollector.extractComments(jsonComments));
135-
136-
// Stash pagination: check if you get all comments linked to the pull-request
137-
isLastPage = StashCollector.isLastPage(jsonComments);
138-
start = StashCollector.getNextPageStart(jsonComments);
137+
result.add(StashCollector.extractComment(jsonComment));
139138
} catch (StashReportExtractionException e) {
140139
throw new StashClientException(e);
141140
}
@@ -310,6 +309,10 @@ private JsonObject get(String url, String errorMessage) throws StashClientExcept
310309
return performRequest(httpClient.prepareGet(url), null, HttpURLConnection.HTTP_OK, errorMessage);
311310
}
312311

312+
private Collection<JsonObject> getPaged(String url, String errorMessage) throws StashClientException {
313+
return performPagedRequest(httpClient.prepareGet(url), null, HttpURLConnection.HTTP_OK, errorMessage);
314+
}
315+
313316
private JsonObject post(String url, JsonObject body, String errorMessage) throws StashClientException {
314317
return performRequest(httpClient.preparePost(url), body, HttpURLConnection.HTTP_OK, errorMessage);
315318
}
@@ -456,4 +459,33 @@ AsyncHttpClient createHttpClient(String sonarQubeVersion) {
456459
.build()
457460
);
458461
}
462+
463+
private Collection<JsonObject> performPagedRequest(BoundRequestBuilder requestBuilder,
464+
JsonObject body,
465+
int expectedStatusCode,
466+
String errorMessage) throws StashClientException {
467+
468+
Collection<JsonObject> result = new ArrayList<>();
469+
470+
boolean doneLastPage = false;
471+
int nextPageStart = 0;
472+
// FIXME size/limit support
473+
474+
while (!doneLastPage) {
475+
if (nextPageStart > 0) {
476+
requestBuilder.addQueryParam("start", String.valueOf(nextPageStart));
477+
}
478+
479+
JsonObject res = performRequest(requestBuilder, body, expectedStatusCode, errorMessage);
480+
JsonArray values = ((JsonArray) res.get("values"));
481+
if (values == null) {
482+
throw new StashClientException("Paged response did not include values");
483+
}
484+
values.asCollection(result);
485+
doneLastPage = res.getBooleanOrDefault("isLastPage", true);
486+
nextPageStart = res.getIntegerOrDefault("nextPageStart", -1);
487+
}
488+
489+
return result;
490+
}
459491
}

src/main/java/org/sonar/plugins/stash/issue/collector/StashCollector.java

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package org.sonar.plugins.stash.issue.collector;
22

33
import java.math.BigDecimal;
4+
import java.util.Objects;
5+
import java.util.Optional;
46
import org.json.simple.JsonArray;
57
import org.json.simple.JsonObject;
68
import org.sonar.plugins.stash.PullRequestRef;
@@ -20,9 +22,7 @@ public final class StashCollector {
2022
private static final String AUTHOR = "author";
2123
private static final String VERSION = "version";
2224

23-
private StashCollector() {
24-
// Hiding implicit public constructor with an explicit private one (squid:S1118)
25-
}
25+
private StashCollector() {}
2626

2727
public static StashCommentReport extractComments(JsonObject jsonComments) throws StashReportExtractionException {
2828
StashCommentReport result = new StashCommentReport();
@@ -41,8 +41,11 @@ public static StashCommentReport extractComments(JsonObject jsonComments) throws
4141
return result;
4242
}
4343

44-
public static StashComment extractComment(JsonObject jsonComment, String path, Long line) {
44+
public static Optional<StashComment> extractCommentFromActivity(JsonObject json) {
45+
return Optional.ofNullable((JsonObject) json.get("comment")).filter(Objects::nonNull).map(j -> StashCollector.extractComment(j, null, null));
46+
}
4547

48+
public static StashComment extractComment(JsonObject jsonComment, String path, Long line) {
4649
long id = getLong(jsonComment, "id");
4750
String message = (String)jsonComment.get("text");
4851

@@ -51,7 +54,10 @@ public static StashComment extractComment(JsonObject jsonComment, String path, L
5154
JsonObject jsonAuthor = (JsonObject)jsonComment.get(AUTHOR);
5255
StashUser stashUser = extractUser(jsonAuthor);
5356

54-
return new StashComment(id, message, path, line, stashUser, version);
57+
StashComment result = new StashComment(id, message, path, line, stashUser, version);
58+
// FIXME do this at some central place
59+
updateCommentTasks(result, (JsonArray) jsonComment.get("tasks"));
60+
return result;
5561
}
5662

5763
public static StashComment extractComment(JsonObject jsonComment) throws StashReportExtractionException {

src/test/java/org/sonar/plugins/stash/StashRequestFacadeTest.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,7 @@ public void setUp() throws Exception {
246246
comments.add(comment3);
247247

248248
when(diffReport.getComments()).thenReturn(comments);
249+
when(stashClient.getPullRequestOverviewComments(pr)).thenReturn(comments);
249250

250251
stashCommentsReport1 = mock(StashCommentReport.class);
251252
when(stashCommentsReport1.getComments()).thenReturn(comments);

src/test/java/org/sonar/plugins/stash/client/StashClientTest.java

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -150,8 +150,7 @@ public void testGetPullRequestCommentsWithNextPage() throws Exception {
150150
+ "\"author\": {\"id\":1, \"name\":\"SonarQube\", \"slug\":\"sonarqube\", \"email\":\"[email protected]\"}, \"version\": 0}], \"isLastPage\": true}";
151151

152152
wireMock.stubFor(get(
153-
urlPathEqualTo("/rest/api/1.0/projects/Project/repos/Repository/pull-requests/1/comments"))
154-
.withQueryParam("start", equalTo(String.valueOf(0))).willReturn(
153+
urlPathEqualTo("/rest/api/1.0/projects/Project/repos/Repository/pull-requests/1/comments")).willReturn(
155154
aJsonResponse().withStatus(HttpURLConnection.HTTP_OK).withBody(stashJsonComment1)
156155
));
157156

@@ -177,7 +176,7 @@ public void testGetPullRequestCommentsWithNoNextPage() throws Exception {
177176
"{\"values\": [{\"id\":4321, \"text\":\"message2\", \"anchor\": {\"path\":\"path\", \"line\":10},"
178177
+ "\"author\": {\"id\":1, \"name\":\"SonarQube\", \"slug\":\"sonarqube\", \"email\":\"[email protected]\"}, \"version\": 0}], \"isLastPage\": true}";
179178

180-
wireMock.stubFor(get(anyUrl()).withQueryParam("start", equalTo(String.valueOf(0))).willReturn(
179+
wireMock.stubFor(get(anyUrl()).willReturn(
181180
aJsonResponse().withStatus(HttpURLConnection.HTTP_OK).withBody(stashJsonComment1)));
182181

183182
wireMock.stubFor(get(anyUrl()).withQueryParam("start", equalTo(String.valueOf(1))).willReturn(
@@ -371,7 +370,7 @@ public void testPullRequestHugePullRequestId() throws Exception {
371370
// See https://github.com/AmadeusITGroup/sonar-stash/issues/98
372371
int hugePullRequestId = 1234567890;
373372

374-
wireMock.stubFor(any(anyUrl()).willReturn(aJsonResponse()));
373+
wireMock.stubFor(any(anyUrl()).willReturn(aPagedJsonResponse()));
375374

376375
PullRequestRef pr = PullRequestRef.builder()
377376
.setProject("Project")
@@ -424,7 +423,15 @@ private void addErrorResponse(MappingBuilder mapping, int statusCode) {
424423
}
425424

426425
public static ResponseDefinitionBuilder aJsonResponse() {
427-
return aResponse().withHeader("Content-Type", "application/json").withBody("{}");
426+
return aJsonResponse("{}");
427+
}
428+
429+
private ResponseDefinitionBuilder aPagedJsonResponse() {
430+
return aJsonResponse("{\"values\":[]}");
431+
}
432+
433+
public static ResponseDefinitionBuilder aJsonResponse(String body) {
434+
return aResponse().withHeader("Content-Type", "application/json").withBody(body);
428435
}
429436

430437
public static ResponseDefinitionBuilder aXMLResponse() {

0 commit comments

Comments
 (0)