forked from jutzig/github-release-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UploadMojo.java
370 lines (325 loc) · 12.1 KB
/
UploadMojo.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
package de.jutzig.github.release.plugin;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.FileSet;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.project.MavenProject;
import org.apache.maven.settings.Server;
import org.apache.maven.settings.Settings;
import org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest;
import org.apache.maven.settings.crypto.SettingsDecrypter;
import org.apache.maven.settings.crypto.SettingsDecryptionResult;
import org.codehaus.plexus.PlexusConstants;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.context.Context;
import org.codehaus.plexus.context.ContextException;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable;
import org.codehaus.plexus.util.FileUtils;
import org.kohsuke.github.GHAsset;
import org.kohsuke.github.GHRelease;
import org.kohsuke.github.GHReleaseBuilder;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;
/**
* Goal which attaches a file to a GitHub release
*/
@Mojo( name="release", defaultPhase = LifecyclePhase.DEPLOY)
public class UploadMojo extends AbstractMojo implements Contextualizable{
private final static String DEFAULT_GITHUBHOSTNAME = "github.com";
private final static String DEFAULT_GITAPIURLPREFIX = "https://api.github.com";
/**
*
* //@parameter default-value="github" expression="github"
* Server id for github access.
*/
@Parameter( defaultValue = "github")
private String serverId;
/**
* The tag name this release is based on.
*
* //@parameter expression="${project.version}"
*/
@Parameter( property = "project.version" )
private String tag;
/**
* The name of the release
*
* //@parameter expression="${release.name}"
*/
@Parameter( property = "release.name" )
private String releaseName;
/**
* The release description
*
* //@parameter expression="${project.description}"
*/
@Parameter( property = "project.description" )
private String description;
/**
* The github id of the project. By default initialized from the project scm connection
*
* //@parameter default-value="${project.scm.connection}" expression="${release.repositoryId}"
* @required
*/
@Parameter( defaultValue = "${project.scm.connection}", property = "release.repositoryId")
private String repositoryId;
/**
* The Maven settings
*
* //@parameter expression="${settings}
*/
@Parameter( defaultValue = "${settings}", readonly = true)
private Settings settings;
/**
* The Maven session
*
* //@parameter expression="${session}"
*/
@Parameter( defaultValue = "${session}", readonly = true)
private MavenSession session;
/**
* The file to upload to the release. Default is ${project.build.directory}/${project.artifactId}-${project.version}.${project.packaging} (the main artifact)
*
* //@parameter default-value="${project.build.directory}/${project.artifactId}-${project.version}.${project.packaging}" expression="${release.artifact}"
*/
@Parameter( defaultValue = "${project.build.directory}/${project.artifactId}-${project.version}.${project.packaging}",
property = "release.artifact")
private String artifact;
/**
* A specific <code>fileSet</code> rule to select files and directories for upload to the release.
*
* //@parameter
*/
private FileSet fileSet;
/**
* A list of <code>fileSet</code> rules to select files and directories for upload to the release.
*
* //@parameter
*/
private List<FileSet> fileSets;
/**
* Flag to indicate to overwrite the asset in the release if it already exists. Default is false
*
* //@parameter default-value=false
*/
@Parameter( defaultValue = "false" )
private Boolean overwriteArtifact;
/**
* Github (Enterprise) hostname. Default is 'github.com'
*
* ////@parameter default-value="github.com"
*/
@Parameter( defaultValue = DEFAULT_GITHUBHOSTNAME )
private String githubHostname;
/**
* Github (Enterprise) API URL (prefix). Default is 'https://api.github.com'
*/
@Parameter( defaultValue = DEFAULT_GITAPIURLPREFIX )
private String githubApiUrlPrefix;
/**
* URL prefix to upload the release to Github. Default is 'https://uploads.github.com/'
*
* ////@parameter default-value="https://uploads.github.com/"
*/
@Parameter( defaultValue = "https://uploads.github.com/")
private String githubApiUploadUrlPrefix;
@Requirement
private PlexusContainer container;
/**
* If this is a prerelease. By default it will use <code>true</code> if the tag ends in -SNAPSHOT
*
* //@parameter
*
*/
@Parameter
private Boolean prerelease;
public void execute() throws MojoExecutionException {
if(releaseName==null)
releaseName = tag;
if(prerelease==null)
prerelease = tag.endsWith("-SNAPSHOT");
repositoryId = computeRepositoryId(repositoryId);
GHRelease release = null;
try {
GitHub gitHub = createGithub(serverId);
GHRepository repository = gitHub.getRepository(repositoryId);
release = findRelease(repository,releaseName);
if(release==null) {
getLog().info("Creating release "+releaseName);
GHReleaseBuilder builder = repository.createRelease(tag);
if(description!=null)
builder.body(description);
builder.prerelease(prerelease);
builder.name(releaseName);
release = builder.create();
}
else {
getLog().info("Release "+releaseName+" already exists. Not creating");
}
} catch (IOException e) {
getLog().error(e);
throw new MojoExecutionException("Failed to create release", e);
}
try {
if(artifact != null && !artifact.trim().isEmpty()) {
File asset = new File(artifact);
if(asset.exists())
uploadAsset(release, asset);
}
if(fileSet != null)
uploadAssets(release, fileSet);
if(fileSets != null)
for (FileSet set : fileSets)
uploadAssets(release, set);
} catch (IOException e) {
getLog().error(e);
throw new MojoExecutionException("Failed to upload assets", e);
}
}
private void uploadAsset(GHRelease release, File asset) throws IOException {
getLog().info("Processing asset "+asset.getPath());
List<GHAsset> existingAssets = release.getAssets();
for ( GHAsset a : existingAssets ){
if (a.getName().equals( asset.getName() )){
if(overwriteArtifact) {
getLog().info(" Deleting existing asset");
a.delete();
}
else
{
getLog().warn("Asset "+asset.getName()+" already exists. Skipping");
return;
}
}
}
getLog().info(" Upload asset");
// for some reason this doesn't work currently
release.uploadAsset(asset, "application/zip", ensureNoTrailingSlash(githubApiUploadUrlPrefix));
}
private void uploadAssets(GHRelease release, FileSet fileset) throws IOException {
List<File> assets = FileUtils.getFiles(
new File(fileset.getDirectory()),
StringUtils.join(fileset.getIncludes(), ','),
StringUtils.join(fileset.getExcludes(), ',')
);
for (File asset : assets)
uploadAsset(release, asset);
}
private GHRelease findRelease(GHRepository repository, String releaseName2) throws IOException {
List<GHRelease> releases = repository.getReleases();
for (GHRelease ghRelease : releases) {
if(ghRelease.getName().equals(releaseName2)) {
return ghRelease;
}
}
return null;
}
public String computeRepositoryId(String id) {
String githubHostnameForRegexp = githubHostname.replace(".", "\\.");
final Pattern REPOSITORY_PATTERN = Pattern.compile(
"^(scm:git[:|])?" + //Maven prefix for git SCM
"(https?://" + githubHostnameForRegexp + "/|git@" + githubHostnameForRegexp + ":)" + //GitHub prefix for HTTP/HTTPS/SSH/Subversion scheme
"([^/]+/[^/]*?)" + //Repository ID
"(\\.git)?$" //Optional suffix ".git"
, Pattern.CASE_INSENSITIVE);
getLog().debug("using following repository pattern: " + REPOSITORY_PATTERN.toString());
Matcher matcher = REPOSITORY_PATTERN.matcher(id);
if (matcher.matches()) {
return matcher.group(3);
} else {
return id;
}
}
public GitHub createGithub(String serverId) throws MojoExecutionException, IOException {
String usernameProperty = System.getProperty("username");
String passwordProperty = System.getProperty("password");
if(usernameProperty!=null && passwordProperty!=null)
{
getLog().debug("Using server credentials from system properties 'username' and 'password'");
return GitHub.connectUsingPassword(usernameProperty, passwordProperty);
}
Server server = getServer(settings, serverId);
if (server == null)
throw new MojoExecutionException(MessageFormat.format("Server ''{0}'' not found in settings", serverId));
getLog().debug(MessageFormat.format("Using ''{0}'' server credentials", serverId));
try {
SettingsDecrypter settingsDecrypter = container.lookup(SettingsDecrypter.class);
SettingsDecryptionResult result = settingsDecrypter.decrypt(new DefaultSettingsDecryptionRequest(server));
server = result.getServer();
} catch (ComponentLookupException cle) {
throw new MojoExecutionException("Unable to lookup SettingsDecrypter: " + cle.getMessage(), cle);
}
String serverUsername = server.getUsername();
String serverPassword = server.getPassword();
String serverAccessToken = server.getPrivateKey();
if (StringUtils.isNotEmpty(serverUsername) && StringUtils.isNotEmpty(serverPassword))
return DEFAULT_GITHUBHOSTNAME.equals(githubHostname) ? GitHub.connectUsingPassword(serverUsername, serverPassword)
: GitHub.connectToEnterprise(githubApiUrlPrefix, serverUsername, serverPassword);
else if (StringUtils.isNotEmpty(serverAccessToken))
return DEFAULT_GITHUBHOSTNAME.equals(githubHostname) ? GitHub.connectUsingOAuth(serverAccessToken)
: GitHub.connectToEnterprise(githubApiUrlPrefix, serverAccessToken);
else
throw new MojoExecutionException("Configuration for server " + serverId + " has no login credentials");
}
/**
* Get server with given id
*
* @param settings
* @param serverId
* must be non-null and non-empty
* @return server or null if none matching
*/
protected Server getServer(final Settings settings, final String serverId) {
if (settings == null)
return null;
List<Server> servers = settings.getServers();
if (servers == null || servers.isEmpty())
return null;
for (Server server : servers)
if (serverId.equals(server.getId()))
return server;
return null;
}
public void contextualize(Context context) throws ContextException {
container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY );
}
/**
* @param str
* @return trimmed str minus the trailing '/', if any
*/
String ensureNoTrailingSlash(String str) {
if(str == null || str.isEmpty()) {
return str;
}
String strTrimmed = str.trim();
return strTrimmed.endsWith("/") ? strTrimmed.substring(0, strTrimmed.length() - 1) : strTrimmed;
}
}