-
Notifications
You must be signed in to change notification settings - Fork 21
/
JvctbPerformer.java
303 lines (282 loc) · 14.5 KB
/
JvctbPerformer.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
package org.jenkinsci.plugins.jvctb.perform;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.logging.Level.SEVERE;
import static org.jenkinsci.plugins.jvctb.config.CredentialsHelper.findCredentials;
import static org.jenkinsci.plugins.jvctb.config.ViolationsToBitbucketServerConfigHelper.FIELD_BITBUCKETSERVERURL;
import static org.jenkinsci.plugins.jvctb.config.ViolationsToBitbucketServerConfigHelper.FIELD_COMMENTONLYCHANGEDCONTENT;
import static org.jenkinsci.plugins.jvctb.config.ViolationsToBitbucketServerConfigHelper.FIELD_COMMENTONLYCHANGEDCONTENTCONTEXT;
import static org.jenkinsci.plugins.jvctb.config.ViolationsToBitbucketServerConfigHelper.FIELD_CREATECOMMENTWITHALLSINGLEFILECOMMENTS;
import static org.jenkinsci.plugins.jvctb.config.ViolationsToBitbucketServerConfigHelper.FIELD_CREATESINGLEFILECOMMENTS;
import static org.jenkinsci.plugins.jvctb.config.ViolationsToBitbucketServerConfigHelper.FIELD_CREDENTIALSID;
import static org.jenkinsci.plugins.jvctb.config.ViolationsToBitbucketServerConfigHelper.FIELD_KEEP_OLD_COMMENTS;
import static org.jenkinsci.plugins.jvctb.config.ViolationsToBitbucketServerConfigHelper.FIELD_MINSEVERITY;
import static org.jenkinsci.plugins.jvctb.config.ViolationsToBitbucketServerConfigHelper.FIELD_PROJECTKEY;
import static org.jenkinsci.plugins.jvctb.config.ViolationsToBitbucketServerConfigHelper.FIELD_PULLREQUESTID;
import static org.jenkinsci.plugins.jvctb.config.ViolationsToBitbucketServerConfigHelper.FIELD_REPOSLUG;
import static se.bjurr.violations.comments.bitbucketserver.lib.ViolationCommentsToBitbucketServerApi.violationCommentsToBitbucketServerApi;
import static se.bjurr.violations.lib.ViolationsApi.violationsApi;
import static se.bjurr.violations.lib.util.Filtering.withAtLEastSeverity;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.remoting.VirtualChannel;
import hudson.util.Secret;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jenkinsci.plugins.jvctb.ProxyConfigDetails;
import org.jenkinsci.plugins.jvctb.config.ViolationConfig;
import org.jenkinsci.plugins.jvctb.config.ViolationsToBitbucketServerConfig;
import org.jenkinsci.plugins.plaincredentials.StringCredentials;
import org.jenkinsci.remoting.RoleChecker;
import se.bjurr.violations.comments.bitbucketserver.lib.ViolationCommentsToBitbucketServerApi;
import se.bjurr.violations.lib.ViolationsLogger;
import se.bjurr.violations.lib.model.SEVERITY;
import se.bjurr.violations.lib.model.Violation;
import se.bjurr.violations.lib.reports.Parser;
public class JvctbPerformer {
private static Logger LOG = Logger.getLogger(JvctbPerformer.class.getSimpleName());
@VisibleForTesting
public static void doPerform(
final ProxyConfigDetails proxyConfigDetails,
final ViolationsToBitbucketServerConfig config,
final File workspace,
final StandardCredentials credentials,
final TaskListener listener)
throws MalformedURLException {
if (isNullOrEmpty(config.getPullRequestId())) {
listener
.getLogger()
.println(
"No pull request id defined, will not send violation comments to Bitbucket Server.");
return;
}
final Integer pullRequestIdInt = Integer.valueOf(config.getPullRequestId());
final ViolationsLogger violationsLogger =
new ViolationsLogger() {
@Override
public void log(final Level level, final String string, final Throwable e) {
Logger.getLogger(JvctbPerformer.class.getName()).log(level, string, e);
final StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
listener.getLogger().println(string + "\n" + sw.toString());
}
@Override
public void log(final Level level, final String string) {
Logger.getLogger(JvctbPerformer.class.getName()).log(level, string);
if (level != Level.FINE) {
listener.getLogger().println(string);
}
}
};
final Set<Violation> allParsedViolations = new TreeSet<>();
for (final ViolationConfig violationConfig : config.getViolationConfigs()) {
if (!isNullOrEmpty(violationConfig.getPattern())) {
Set<Violation> parsedViolations =
violationsApi() //
.withViolationsLogger(violationsLogger) //
.findAll(violationConfig.getParser()) //
.withReporter(violationConfig.getReporter()) //
.inFolder(workspace.getAbsolutePath()) //
.withPattern(violationConfig.getPattern()) //
.withIgnorePaths(config.getIgnorePathStrings())
.violations();
final SEVERITY minSeverity = config.getMinSeverity();
if (minSeverity != null) {
parsedViolations = withAtLEastSeverity(parsedViolations, minSeverity);
}
allParsedViolations.addAll(parsedViolations);
listener
.getLogger()
.println(
"Found " + parsedViolations.size() + " violations from " + violationConfig + ".");
}
}
listener
.getLogger()
.println(
"PR: "
+ config.getProjectKey()
+ "/"
+ config.getRepoSlug()
+ "/"
+ config.getPullRequestId()
+ " on "
+ config.getBitbucketServerUrl());
final ViolationCommentsToBitbucketServerApi violationCommentsToBitbucketServerApi =
violationCommentsToBitbucketServerApi();
if (proxyConfigDetails != null) {
violationCommentsToBitbucketServerApi //
.withProxyHostNameOrIp(proxyConfigDetails.getHost()) //
.withProxyHostPort(proxyConfigDetails.getPort()) //
.withProxyUser(proxyConfigDetails.getUser()) //
.withProxyPassword(proxyConfigDetails.getPass());
}
try {
if (credentials instanceof StandardUsernamePasswordCredentials) {
final StandardUsernamePasswordCredentials usernamePassword =
(StandardUsernamePasswordCredentials) credentials;
violationCommentsToBitbucketServerApi //
.withUsername(usernamePassword.getUsername()) //
.withPassword(Secret.toString(usernamePassword.getPassword()));
} else if (credentials instanceof StringCredentials) {
final StringCredentials personalAccessToken = (StringCredentials) credentials;
violationCommentsToBitbucketServerApi //
.withPersonalAccessToken(Secret.toString(personalAccessToken.getSecret()));
}
final String commentTemplate = config.getCommentTemplate();
violationCommentsToBitbucketServerApi //
.withBitbucketServerUrl(config.getBitbucketServerUrl()) //
.withPullRequestId(pullRequestIdInt) //
.withProjectKey(config.getProjectKey()) //
.withRepoSlug(config.getRepoSlug()) //
.withViolations(allParsedViolations) //
.withIgnorePaths(config.getIgnorePathStrings())
.withCreateCommentWithAllSingleFileComments(
config.getCreateCommentWithAllSingleFileComments()) //
.withCreateSingleFileComments(config.getCreateSingleFileComments()) //
.withCreateSingleFileCommentsTasks(config.getCreateSingleFileCommentsTasks()) //
.withCommentOnlyChangedContent(config.getCommentOnlyChangedContent()) //
.withCommentOnlyChangedContentContext(config.getCommentOnlyChangedContentContext()) //
.withShouldCommentOnlyChangedFiles(config.getCommentOnlyChangedFiles()) //
.withShouldKeepOldComments(config.isKeepOldComments()) //
.withCommentTemplate(commentTemplate) //
.withMaxNumberOfViolations(config.getMaxNumberOfViolations()) //
.withViolationsLogger(violationsLogger) //
.toPullRequest();
} catch (final Exception e) {
Logger.getLogger(JvctbPerformer.class.getName()).log(SEVERE, "", e);
final StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
listener.getLogger().println(sw.toString());
}
}
/** Makes sure any Jenkins variable, used in the configuration fields, are evaluated. */
@VisibleForTesting
static ViolationsToBitbucketServerConfig expand(
final ViolationsToBitbucketServerConfig config, final EnvVars environment) {
final ViolationsToBitbucketServerConfig expanded = new ViolationsToBitbucketServerConfig();
expanded.setBitbucketServerUrl(environment.expand(config.getBitbucketServerUrl()));
expanded.setPullRequestId(environment.expand(config.getPullRequestId()));
expanded.setProjectKey(environment.expand(config.getProjectKey()));
expanded.setRepoSlug(environment.expand(config.getRepoSlug()));
expanded.setCreateCommentWithAllSingleFileComments(
config.getCreateCommentWithAllSingleFileComments());
expanded.setCreateSingleFileComments(config.getCreateSingleFileComments());
expanded.setCreateSingleFileCommentsTasks(config.getCreateSingleFileCommentsTasks());
expanded.setCredentialsId(config.getCredentialsId());
expanded.setCommentOnlyChangedContent(config.getCommentOnlyChangedContent());
expanded.setCommentOnlyChangedContentContext(config.getCommentOnlyChangedContentContext());
expanded.setCommentOnlyChangedFiles(config.getCommentOnlyChangedFiles());
expanded.setMinSeverity(config.getMinSeverity());
expanded.setKeepOldComments(config.isKeepOldComments());
expanded.setCommentTemplate(config.getCommentTemplate());
expanded.setMaxNumberOfViolations(config.getMaxNumberOfViolations());
expanded.setIgnorePaths(config.getIgnorePaths());
for (final ViolationConfig violationConfig : config.getViolationConfigs()) {
final String pattern = environment.expand(violationConfig.getPattern());
final String reporter = violationConfig.getReporter();
final Parser parser = violationConfig.getParser();
if (isNullOrEmpty(pattern) || parser == null) {
LOG.fine("Ignoring violationConfig because of null/empty -values: " + violationConfig);
continue;
}
final ViolationConfig p = new ViolationConfig();
p.setPattern(pattern);
p.setReporter(reporter);
p.setParser(parser);
expanded.getViolationConfigs().add(p);
}
return expanded;
}
public static void jvctsPerform(
final ProxyConfigDetails proxyConfigDetails,
final ViolationsToBitbucketServerConfig configUnexpanded,
final FilePath fp,
final Run<?, ?> build,
final TaskListener listener) {
try {
final EnvVars env = build.getEnvironment(listener);
final ViolationsToBitbucketServerConfig configExpanded = expand(configUnexpanded, env);
listener.getLogger().println("---");
listener.getLogger().println("--- Jenkins Violation Comments to Bitbucket Server ---");
listener.getLogger().println("---");
logConfiguration(configExpanded, build, listener);
final Optional<StandardCredentials> credentials =
findCredentials(
build.getParent(),
configExpanded.getCredentialsId(),
configExpanded.getBitbucketServerUrl());
if (!credentials.isPresent()) {
listener.getLogger().println("Credentials not found!");
return;
}
listener.getLogger().println("Pull request: " + configExpanded.getPullRequestId());
fp.act(
new FileCallable<Void>() {
private static final long serialVersionUID = 6166111757469534436L;
@Override
public void checkRoles(final RoleChecker checker) throws SecurityException {}
@Override
public Void invoke(final File workspace, final VirtualChannel channel)
throws IOException, InterruptedException {
listener.getLogger().println("Workspace: " + workspace.getAbsolutePath());
doPerform(
proxyConfigDetails, configExpanded, workspace, credentials.orNull(), listener);
return null;
}
});
} catch (final Exception e) {
Logger.getLogger(JvctbPerformer.class.getName()).log(SEVERE, "", e);
final StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
listener.getLogger().println(sw.toString());
return;
}
}
private static void logConfiguration(
final ViolationsToBitbucketServerConfig config,
final Run<?, ?> build,
final TaskListener listener) {
final PrintStream logger = listener.getLogger();
logger.println(FIELD_BITBUCKETSERVERURL + ": " + config.getBitbucketServerUrl());
logger.println(FIELD_PROJECTKEY + ": " + config.getProjectKey());
logger.println(FIELD_REPOSLUG + ": " + config.getRepoSlug());
logger.println(FIELD_PULLREQUESTID + ": " + config.getPullRequestId());
logger.println(FIELD_CREDENTIALSID + ": " + !isNullOrEmpty(config.getCredentialsId()));
logger.println(FIELD_CREATESINGLEFILECOMMENTS + ": " + config.getCreateSingleFileComments());
logger.println("createSingleFileCommentsTasks: " + config.getCreateSingleFileCommentsTasks());
logger.println(
FIELD_CREATECOMMENTWITHALLSINGLEFILECOMMENTS
+ ": "
+ config.getCreateCommentWithAllSingleFileComments());
logger.println(FIELD_COMMENTONLYCHANGEDCONTENT + ": " + config.getCommentOnlyChangedContent());
logger.println(
FIELD_COMMENTONLYCHANGEDCONTENTCONTEXT
+ ": "
+ config.getCommentOnlyChangedContentContext());
logger.println("commentOnlyChangedFiles: " + config.getCommentOnlyChangedFiles());
logger.println(FIELD_MINSEVERITY + ": " + config.getMinSeverity());
logger.println(FIELD_KEEP_OLD_COMMENTS + ": " + config.isKeepOldComments());
logger.println("commentTemplate: " + config.getCommentTemplate());
logger.println("maxNumberOfViolations: " + config.getMaxNumberOfViolations());
logger.println("ignorePaths: " + config.getIgnorePathStrings());
for (final ViolationConfig violationConfig : config.getViolationConfigs()) {
logger.println(
violationConfig.getReporter() + " with pattern " + violationConfig.getPattern());
}
}
}