-
Notifications
You must be signed in to change notification settings - Fork 131
/
StashRepository.java
378 lines (321 loc) · 16.6 KB
/
StashRepository.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
package stashpullrequestbuilder.stashpullrequestbuilder;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.model.Result;
import stashpullrequestbuilder.stashpullrequestbuilder.stash.StashApiClient;
import stashpullrequestbuilder.stashpullrequestbuilder.stash.StashPullRequestComment;
import stashpullrequestbuilder.stashpullrequestbuilder.stash.StashPullRequestMergableResponse;
import stashpullrequestbuilder.stashpullrequestbuilder.stash.StashPullRequestResponseValue;
import stashpullrequestbuilder.stashpullrequestbuilder.stash.StashPullRequestResponseValueRepository;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.String.format;
/**
* Created by Nathan McCarthy
*/
@SuppressFBWarnings("WMI_WRONG_MAP_ITERATOR")
public class StashRepository {
private static final Logger logger = Logger.getLogger(StashRepository.class.getName());
public static final String BUILD_START_MARKER = "[*BuildStarted* **%s**] %s into %s";
public static final String BUILD_FINISH_MARKER = "[*BuildFinished* **%s**] %s into %s";
public static final String BUILD_START_REGEX = "\\[\\*BuildStarted\\* \\*\\*%s\\*\\*\\] ([0-9a-fA-F]+) into ([0-9a-fA-F]+)";
public static final String BUILD_FINISH_REGEX = "\\[\\*BuildFinished\\* \\*\\*%s\\*\\*\\] ([0-9a-fA-F]+) into ([0-9a-fA-F]+)";
public static final String BUILD_FINISH_SENTENCE = BUILD_FINISH_MARKER + " %n%n **[%s](%s)** - Build *#%d* which took *%s*";
public static final String BUILD_START_SENTENCE = BUILD_START_MARKER + " %n%n **[%s](%s)** - Build *#%d*";
public static final String BUILD_SUCCESS_COMMENT = "✓ BUILD SUCCESS";
public static final String BUILD_FAILURE_COMMENT = "✕ BUILD FAILURE";
public static final String BUILD_RUNNING_COMMENT = "BUILD RUNNING...";
public static final String BUILD_UNSTABLE_COMMENT = "⁉ BUILD UNSTABLE";
public static final String BUILD_ABORTED_COMMENT = "‼ BUILD ABORTED";
public static final String BUILD_NOTBUILT_COMMENT = "✕ BUILD INCOMPLETE";
public static final String ADDITIONAL_PARAMETER_REGEX = "^p:(([A-Za-z_0-9])+)=(.*)";
public static final Pattern ADDITIONAL_PARAMETER_REGEX_PATTERN = Pattern.compile(ADDITIONAL_PARAMETER_REGEX);
private String projectPath;
private StashPullRequestsBuilder builder;
private StashBuildTrigger trigger;
private StashApiClient client;
public StashRepository(String projectPath, StashPullRequestsBuilder builder) {
this.projectPath = projectPath;
this.builder = builder;
}
public void init() {
trigger = this.builder.getTrigger();
client = new StashApiClient(
trigger.getStashHost(),
trigger.getUsername(),
trigger.getPassword(),
trigger.getProjectCode(),
trigger.getRepositoryName(),
trigger.isIgnoreSsl());
}
public Collection<StashPullRequestResponseValue> getTargetPullRequests() {
logger.info(format("Fetch PullRequests (%s).", builder.getJob().getName()));
List<StashPullRequestResponseValue> pullRequests = client.getPullRequests();
List<StashPullRequestResponseValue> targetPullRequests = new ArrayList<StashPullRequestResponseValue>();
for(StashPullRequestResponseValue pullRequest : pullRequests) {
if (isBuildTarget(pullRequest)) {
targetPullRequests.add(pullRequest);
}
}
return targetPullRequests;
}
public String postBuildStartCommentTo(StashPullRequestResponseValue pullRequest) {
String sourceCommit = pullRequest.getFromRef().getLatestCommit();
String destinationCommit = pullRequest.getToRef().getLatestCommit();
String comment = format(BUILD_START_MARKER, builder.getJob().getDisplayName(), sourceCommit, destinationCommit);
StashPullRequestComment commentResponse = this.client.postPullRequestComment(pullRequest.getId(), comment);
return commentResponse.getCommentId().toString();
}
public static AbstractMap.SimpleEntry<String,String> getParameter(String content){
if(content.isEmpty()){
return null;
}
Matcher parameterMatcher = ADDITIONAL_PARAMETER_REGEX_PATTERN.matcher(content);
if(parameterMatcher.find(0)){
String parameterName = parameterMatcher.group(1);
String parameterValue = parameterMatcher.group(3);
return new AbstractMap.SimpleEntry<String,String>(parameterName, parameterValue);
}
return null;
}
public static Map<String, String> getParametersFromContent(String content){
Map<String, String> result = new TreeMap<String, String>();
String lines[] = content.split("\\r?\\n|\\r");
for(String line : lines){
AbstractMap.SimpleEntry<String,String> parameter = getParameter(line);
if(parameter != null){
result.put(parameter.getKey(), parameter.getValue());
}
}
return result;
}
public Map<String, String> getAdditionalParameters(StashPullRequestResponseValue pullRequest){
StashPullRequestResponseValueRepository destination = pullRequest.getToRef();
String owner = destination.getRepository().getProjectName();
String repositoryName = destination.getRepository().getRepositoryName();
String id = pullRequest.getId();
List<StashPullRequestComment> comments = client.getPullRequestComments(owner, repositoryName, id);
if (comments != null) {
Collections.sort(comments);
// Collections.reverse(comments);
Map<String, String> result = new TreeMap<String, String>();
for (StashPullRequestComment comment : comments) {
String content = comment.getText();
if (content == null || content.isEmpty()) {
continue;
}
Map<String,String> parameters = getParametersFromContent(content);
for(String key : parameters.keySet()){
result.put(key, parameters.get(key));
}
}
return result;
}
return null;
}
public void addFutureBuildTasks(Collection<StashPullRequestResponseValue> pullRequests) {
for(StashPullRequestResponseValue pullRequest : pullRequests) {
Map<String, String> additionalParameters = getAdditionalParameters(pullRequest);
if (trigger.getDeletePreviousBuildFinishComments()) {
deletePreviousBuildFinishedComments(pullRequest);
}
String commentId = postBuildStartCommentTo(pullRequest);
StashCause cause = new StashCause(
trigger.getStashHost(),
pullRequest.getFromRef().getBranch().getName(),
pullRequest.getToRef().getBranch().getName(),
pullRequest.getFromRef().getRepository().getProjectName(),
pullRequest.getFromRef().getRepository().getRepositoryName(),
pullRequest.getId(),
pullRequest.getToRef().getRepository().getProjectName(),
pullRequest.getToRef().getRepository().getRepositoryName(),
pullRequest.getTitle(),
pullRequest.getFromRef().getLatestCommit(),
pullRequest.getToRef().getLatestCommit(),
commentId,
pullRequest.getVersion(),
additionalParameters);
this.builder.getTrigger().startJob(cause);
}
}
public void deletePullRequestComment(String pullRequestId, String commentId) {
this.client.deletePullRequestComment(pullRequestId, commentId);
}
private String getMessageForBuildResult(Result result) {
String message = BUILD_FAILURE_COMMENT;
if (result == Result.SUCCESS) {
message = BUILD_SUCCESS_COMMENT;
}
if (result == Result.UNSTABLE) {
message = BUILD_UNSTABLE_COMMENT;
}
if (result == Result.ABORTED) {
message = BUILD_ABORTED_COMMENT;
}
if (result == Result.NOT_BUILT) {
message = BUILD_NOTBUILT_COMMENT;
}
return message;
}
public void postFinishedComment(String pullRequestId, String sourceCommit, String destinationCommit, Result buildResult, String buildUrl, int buildNumber, String additionalComment, String duration) {
String message = getMessageForBuildResult(buildResult);
String comment = format(BUILD_FINISH_SENTENCE, builder.getJob().getDisplayName(), sourceCommit, destinationCommit, message, buildUrl, buildNumber, duration);
comment = comment.concat(additionalComment);
this.client.postPullRequestComment(pullRequestId, comment);
}
public boolean mergePullRequest(String pullRequestId, String version)
{
return this.client.mergePullRequest(pullRequestId, version);
}
private Boolean isPullRequestMergable(StashPullRequestResponseValue pullRequest) {
if (trigger.isCheckMergeable() || trigger.isCheckNotConflicted()) {
StashPullRequestMergableResponse mergable = client.getPullRequestMergeStatus(pullRequest.getId());
boolean res = true;
if (trigger.isCheckMergeable())
res = res && mergable.getCanMerge();
if (trigger.isCheckNotConflicted())
res = res && !mergable.getConflicted();
return res;
}
return true;
}
private void deletePreviousBuildFinishedComments(StashPullRequestResponseValue pullRequest) {
StashPullRequestResponseValueRepository destination = pullRequest.getToRef();
String owner = destination.getRepository().getProjectName();
String repositoryName = destination.getRepository().getRepositoryName();
String id = pullRequest.getId();
List<StashPullRequestComment> comments = client.getPullRequestComments(owner, repositoryName, id);
if (comments != null) {
Collections.sort(comments);
Collections.reverse(comments);
for (StashPullRequestComment comment : comments) {
String content = comment.getText();
if (content == null || content.isEmpty()) {
continue;
}
String project_build_finished = format(BUILD_FINISH_REGEX, builder.getJob().getDisplayName());
Matcher finishMatcher = Pattern.compile(project_build_finished, Pattern.CASE_INSENSITIVE).matcher(content);
if (finishMatcher.find()) {
deletePullRequestComment(pullRequest.getId(), comment.getCommentId().toString());
}
}
}
}
private boolean isBuildTarget(StashPullRequestResponseValue pullRequest) {
boolean shouldBuild = true;
if (pullRequest.getState() != null && pullRequest.getState().equals("OPEN")) {
if (isSkipBuild(pullRequest.getTitle())) {
logger.info("Skipping PR: " + pullRequest.getId() + " as title contained skip phrase");
return false;
}
if (!isForTargetBranch(pullRequest)) {
logger.info("Skipping PR: " + pullRequest.getId() + " as targeting branch: " + pullRequest.getToRef().getBranch().getName());
return false;
}
if(!isPullRequestMergable(pullRequest)) {
logger.info("Skipping PR: " + pullRequest.getId() + " as cannot be merged");
return false;
}
boolean isOnlyBuildOnComment = trigger.isOnlyBuildOnComment();
if (isOnlyBuildOnComment) {
shouldBuild = false;
}
String sourceCommit = pullRequest.getFromRef().getLatestCommit();
StashPullRequestResponseValueRepository destination = pullRequest.getToRef();
String owner = destination.getRepository().getProjectName();
String repositoryName = destination.getRepository().getRepositoryName();
String destinationCommit = destination.getLatestCommit();
String id = pullRequest.getId();
List<StashPullRequestComment> comments = client.getPullRequestComments(owner, repositoryName, id);
if (comments != null) {
Collections.sort(comments);
Collections.reverse(comments);
for (StashPullRequestComment comment : comments) {
String content = comment.getText();
if (content == null || content.isEmpty()) {
continue;
}
//These will match any start or finish message -- need to check commits
String escapedBuildName = Pattern.quote(builder.getJob().getDisplayName());
String project_build_start = String.format(BUILD_START_REGEX, escapedBuildName);
String project_build_finished = String.format(BUILD_FINISH_REGEX, escapedBuildName);
Matcher startMatcher = Pattern.compile(project_build_start, Pattern.CASE_INSENSITIVE).matcher(content);
Matcher finishMatcher = Pattern.compile(project_build_finished, Pattern.CASE_INSENSITIVE).matcher(content);
if (startMatcher.find() ||
finishMatcher.find()) {
//in build only on comment, we should stop parsing comments as soon as a PR builder comment is found.
if(isOnlyBuildOnComment) {
assert !shouldBuild;
break;
}
String sourceCommitMatch;
String destinationCommitMatch;
if (startMatcher.find(0)) {
sourceCommitMatch = startMatcher.group(1);
destinationCommitMatch = startMatcher.group(2);
} else {
sourceCommitMatch = finishMatcher.group(1);
destinationCommitMatch = finishMatcher.group(2);
}
//first check source commit -- if it doesn't match, just move on. If it does, investigate further.
if (sourceCommitMatch.equalsIgnoreCase(sourceCommit)) {
// if we're checking destination commits, and if this doesn't match, then move on.
if (this.trigger.getCheckDestinationCommit()
&& (!destinationCommitMatch.equalsIgnoreCase(destinationCommit))) {
continue;
}
shouldBuild = false;
break;
}
}
if(isSkipBuild(content)) {
shouldBuild = false;
break;
} if (isPhrasesContain(content, this.trigger.getCiBuildPhrases())) {
shouldBuild = true;
break;
}
}
}
}
if (shouldBuild) {
logger.info("Building PR: " + pullRequest.getId());
}
return shouldBuild;
}
private boolean isForTargetBranch(StashPullRequestResponseValue pullRequest) {
String targetBranchesToBuild = this.trigger.getTargetBranchesToBuild();
if (targetBranchesToBuild !=null && !"".equals(targetBranchesToBuild)) {
String[] branches = targetBranchesToBuild.split(",");
for(String branch : branches) {
if (pullRequest.getToRef().getBranch().getName().matches(branch.trim())) {
return true;
}
}
return false;
}
return true;
}
private boolean isSkipBuild(String pullRequestContentString) {
String skipPhrases = this.trigger.getCiSkipPhrases();
if (skipPhrases != null && !"".equals(skipPhrases)) {
String[] phrases = skipPhrases.split(",");
for(String phrase : phrases) {
if (isPhrasesContain(pullRequestContentString, phrase)) {
return true;
}
}
}
return false;
}
private boolean isPhrasesContain(String text, String phrase) {
return text != null && text.toLowerCase().contains(phrase.trim().toLowerCase());
}
}