/
Updater.java
executable file
·420 lines (376 loc) · 15.2 KB
/
Updater.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
package hudson.plugins.jira;
import static java.lang.String.format;
import com.atlassian.jira.rest.client.api.RestClientException;
import com.atlassian.jira.rest.client.api.domain.Issue;
import hudson.Util;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.plugins.jira.model.JiraIssue;
import hudson.plugins.jira.selector.AbstractIssueSelector;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.AffectedFile;
import hudson.scm.ChangeLogSet.Entry;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
/**
* Actual Jira update logic.
*
* @author Kohsuke Kawaguchi
*/
class Updater {
private SCM scm;
private List<String> labels;
private static final Logger LOGGER = Logger.getLogger(Updater.class.getName());
/**
* Debug flag.
*/
public static boolean debug = false;
public Updater(SCM scm) {
this(scm, new ArrayList<>());
}
public Updater(SCM scm, List<String> labels) {
super();
this.scm = scm;
if (labels == null) {
this.labels = new ArrayList<>();
} else {
this.labels = labels;
}
}
boolean perform(Run<?, ?> run, TaskListener listener, AbstractIssueSelector selector) {
PrintStream logger = listener.getLogger();
Set<JiraIssue> issues = null;
try {
JiraSite site = JiraSite.get(run.getParent());
if (site == null) {
logger.println(Messages.NoJiraSite());
run.setResult(Result.FAILURE);
return true;
}
String rootUrl = Jenkins.get().getRootUrl();
if (rootUrl == null) {
logger.println(Messages.NoJenkinsUrl());
run.setResult(Result.FAILURE);
return true;
}
Set<String> ids = selector.findIssueIds(run, site, listener);
if (ids.isEmpty()) {
if (debug) {
logger.println("No Jira issues found.");
}
return true; // nothing found here.
}
JiraSession session = site.getSession(run.getParent());
if (session == null) {
logger.println(Messages.NoRemoteAccess());
run.setResult(Result.FAILURE);
return true;
}
boolean doUpdate = false;
// in case of workflow, it may be null
if (site.updateJiraIssueForAllStatus || run.getResult() == null) {
doUpdate = true;
} else {
doUpdate = run.getResult().isBetterOrEqualTo(Result.UNSTABLE);
}
boolean useWikiStyleComments = site.supportsWikiStyleComment;
issues = getJiraIssues(ids, session, logger);
run.addAction(new JiraBuildAction(issues));
if (doUpdate) {
submitComments(
run,
logger,
rootUrl,
issues,
session,
useWikiStyleComments,
site.recordScmChanges,
site.groupVisibility,
site.roleVisibility);
} else {
// this build didn't work, so carry forward the issues to the next build
run.addAction(new JiraCarryOverAction(issues));
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Error updating Jira issues. Saving issues for next build.", e);
logger.println("Error updating Jira issues. Saving issues for next build.\n" + e);
if (issues != null && !issues.isEmpty()) {
// updating issues failed, so carry forward issues to the next build
run.addAction(new JiraCarryOverAction(issues));
}
}
return true;
}
/**
* Submits comments for the given issues.
* Removes from <code>issues</code> issues which have been successfully updated or are invalid
*
* @param build
* @param logger
* @param jenkinsRootUrl
* @param session
* @param useWikiStyleComments
* @param recordScmChanges
* @param groupVisibility
* @throws RestClientException
*/
void submitComments(
Run<?, ?> build,
PrintStream logger,
String jenkinsRootUrl,
Set<JiraIssue> issues,
JiraSession session,
boolean useWikiStyleComments,
boolean recordScmChanges,
String groupVisibility,
String roleVisibility)
throws RestClientException {
// copy to prevent ConcurrentModificationException
Set<JiraIssue> copy = new HashSet<>(issues);
for (JiraIssue issue : copy) {
logger.println(Messages.UpdatingIssue(issue.getKey()));
try {
session.addComment(
issue.getKey(),
createComment(build, useWikiStyleComments, jenkinsRootUrl, recordScmChanges, issue),
groupVisibility,
roleVisibility);
if (!labels.isEmpty()) {
session.addLabels(issue.getKey(), labels);
}
} catch (RestClientException e) {
if (e.getStatusCode().or(0).equals(404)) {
logger.println(issue.getKey() + " - Jira issue not found. Dropping comment from update queue.");
}
if (e.getStatusCode().or(0).equals(403)) {
logger.println(
issue.getKey()
+ " - Jenkins Jira user does not have permissions to comment on this issue. Preserving comment for future update.");
continue;
}
if (e.getStatusCode().or(0).equals(401)) {
logger.println(issue.getKey()
+ " - Jenkins Jira authentication problem. Preserving comment for future update.");
continue;
}
logger.println(Messages.FailedToUpdateIssueWithCarryOver(issue.getKey()));
logger.println(e.getLocalizedMessage());
}
// if no exception is thrown during update, remove from the list as successfully updated
issues.remove(issue);
}
}
private static Set<JiraIssue> getJiraIssues(Set<String> ids, JiraSession session, PrintStream logger)
throws RemoteException {
Set<JiraIssue> issues = new LinkedHashSet<>(ids.size());
for (String id : ids) {
Issue issue = session.getIssue(id);
if (issue == null) {
logger.println(id + " issue doesn't exist in Jira");
continue;
}
issues.add(new JiraIssue(issue));
}
return issues;
}
/**
* Creates a comment to be used in Jira for the build.
* For example:
* <pre>
* SUCCESS: Integrated in Job #nnnn (See [http://jenkins.domain/job/Job/nnnn/])\r
* JIRA-XXXX: Commit message. (Author _author@email.domain_:
* [https://bitbucket.org/user/repo/changeset/9af8e4c4c909/])\r
* </pre>
*/
private String createComment(
Run<?, ?> build, boolean wikiStyle, String jenkinsRootUrl, boolean recordScmChanges, JiraIssue jiraIssue) {
Result result = build.getResult();
// if we run from workflow we dont known final result
if (result == null) {
return format(
wikiStyle
? "Integrated in [%2$s|%3$s]\n%4$s"
: "Integrated in Jenkins build %2$s (See [%3$s])\n%4$s",
jenkinsRootUrl,
build.getFullDisplayName(),
Util.encode(jenkinsRootUrl + build.getUrl()),
getScmComments(wikiStyle, build, recordScmChanges, jiraIssue));
} else {
return format(
wikiStyle
? "%6$s: Integrated in !%1$simages/16x16/%3$s! [%2$s|%4$s]\n%5$s"
: "%6$s: Integrated in Jenkins build %2$s (See [%4$s])\n%5$s",
jenkinsRootUrl,
build.getFullDisplayName(),
result != null ? result.color.getImage() : null,
Util.encode(jenkinsRootUrl + build.getUrl()),
getScmComments(wikiStyle, build, recordScmChanges, jiraIssue),
result.toString());
}
}
private String getScmComments(boolean wikiStyle, Run<?, ?> run, boolean recordScmChanges, JiraIssue jiraIssue) {
StringBuilder comment = new StringBuilder();
for (ChangeLogSet<? extends Entry> set : RunScmChangeExtractor.getChanges(run)) {
for (Entry change : set) {
if (jiraIssue != null && !StringUtils.containsIgnoreCase(change.getMsg(), jiraIssue.getKey())) {
continue;
}
comment.append(createScmChangeEntryDescription(run, change, wikiStyle, recordScmChanges));
}
}
if (jiraIssue != null) {
final Run<?, ?> prev = run.getPreviousCompletedBuild();
if (prev != null) {
final JiraCarryOverAction a = prev.getAction(JiraCarryOverAction.class);
if (a != null && a.getIDs().contains(jiraIssue.getKey())) {
comment.append(getScmComments(wikiStyle, prev, recordScmChanges, jiraIssue));
}
}
}
return comment.toString();
}
protected String createScmChangeEntryDescription(
Run<?, ?> run, Entry change, boolean wikiStyle, boolean recordScmChanges) {
StringBuilder description = new StringBuilder();
RepositoryBrowser repoBrowser = getRepositoryBrowser(run);
JiraSite site = JiraSite.get(run.getParent());
if (change.getMsg() != null) {
description.append(change.getMsg());
}
String revision = getRevision(change);
if (revision != null) {
description.append(" (");
appendAuthorToDescription(change, description);
if (site.isAppendChangeTimestamp() && change.getTimestamp() > 0) {
appendChangeTimestampToDescription(description, site, change.getTimestamp());
description.append(" ");
}
appendRevisionToDescription(change, wikiStyle, description, repoBrowser, revision);
description.append(")");
}
description.append("\n");
if (recordScmChanges) {
appendAffectedFilesToDescription(change, description);
}
return description.toString();
}
protected void appendAuthorToDescription(Entry change, StringBuilder description) {
if (change.getAuthor() != null) {
change.getAuthor();
String uid = change.getAuthor().getId();
if (StringUtils.isNotBlank(uid)) {
description.append(uid).append(": ");
}
}
}
protected void appendRevisionToDescription(
Entry change,
boolean wikiStyle,
StringBuilder description,
RepositoryBrowser repoBrowser,
String revision) {
URL url = null;
if (repoBrowser != null) {
try {
url = repoBrowser.getChangeSetLink(change);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to calculate SCM repository browser link", e);
}
}
if (url != null && StringUtils.isNotBlank(url.toExternalForm())) {
if (wikiStyle) {
description.append("[").append(revision).append("|");
description.append(url.toExternalForm()).append("]");
} else {
description.append("[").append(url.toExternalForm()).append("]");
}
} else {
description.append("rev ").append(revision);
}
}
protected void appendAffectedFilesToDescription(Entry change, StringBuilder description) {
// see http://issues.jenkins-ci.org/browse/JENKINS-2508
// added additional try .. catch; getAffectedFiles is not supported
// by all SCM implementations
try {
for (AffectedFile affectedFile : change.getAffectedFiles()) {
description.append("* ");
if (affectedFile.getEditType() != null) {
description
.append("(")
.append(affectedFile.getEditType().getName())
.append(") ");
}
if (affectedFile.getPath() != null) {
description.append(affectedFile.getPath());
}
description.append("\n");
}
} catch (UnsupportedOperationException e) {
LOGGER.warning("Unsupported SCM operation 'getAffectedFiles'. Fall back to getAffectedPaths.");
for (String affectedPath : change.getAffectedPaths()) {
description.append("* ").append(affectedPath).append("\n");
}
}
}
protected void appendChangeTimestampToDescription(StringBuilder description, JiraSite site, long timestamp) {
DateFormat df = null;
if (StringUtils.isBlank(site.getDateTimePattern())) {
// default format for current locale
df = new SimpleDateFormat("d/M/yy hh:mm a", Locale.getDefault());
} else {
df = new SimpleDateFormat(site.getDateTimePattern());
}
Date changeDate = new Date(timestamp);
String dateTimeString = df.format(changeDate);
description.append(dateTimeString);
}
private RepositoryBrowser<?> getRepositoryBrowser(Run<?, ?> run) {
SCM scm = getScm();
if (scm != null) {
return scm.getEffectiveBrowser();
}
return null;
}
private static String getRevision(Entry entry) {
String commitId = entry.getCommitId();
if (commitId != null) {
return commitId;
}
// fall back to old SVN-specific solution, if we have only installed an old subversion-plugin
// which doesn't implement getCommitId, yet
try {
Class<?> clazz = entry.getClass();
Method method = clazz.getMethod("getRevision", (Class[]) null);
if (method == null) {
return null;
}
Object revObj = method.invoke(entry, (Object[]) null);
return (revObj != null) ? revObj.toString() : null;
} catch (Exception e) {
return null;
}
}
private SCM getScm() {
return scm;
}
}