/
AbstractMavenPublisher.java
255 lines (220 loc) · 11.5 KB
/
AbstractMavenPublisher.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
/*
* Copyright 2019 the original author or authors.
*
* 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.
*/
package org.gradle.api.publish.maven.internal.publisher;
import com.google.common.collect.ImmutableSet;
import org.apache.maven.artifact.repository.metadata.Metadata;
import org.apache.maven.artifact.repository.metadata.Versioning;
import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader;
import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer;
import org.gradle.api.UncheckedIOException;
import org.gradle.api.internal.artifacts.repositories.transport.NetworkOperationBackOffAndRetry;
import org.gradle.api.publish.maven.MavenArtifact;
import org.gradle.internal.Factory;
import org.gradle.internal.UncheckedException;
import org.gradle.internal.hash.HashUtil;
import org.gradle.internal.hash.HashValue;
import org.gradle.internal.resource.ExternalResourceName;
import org.gradle.internal.resource.ExternalResourceReadResult;
import org.gradle.internal.resource.ExternalResourceRepository;
import org.gradle.internal.resource.ReadableContent;
import org.gradle.internal.resource.local.ByteArrayReadableContent;
import org.gradle.internal.resource.local.FileReadableContent;
import org.gradle.internal.xml.XmlTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import static org.apache.maven.artifact.ArtifactUtils.isSnapshot;
abstract class AbstractMavenPublisher implements MavenPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(MavenPublisher.class);
private static final Set<String> JAR_PACKAGINGS = ImmutableSet.of("jar", "ejb", "bundle", "maven-plugin", "eclipse-plugin");
private static final String POM_FILE_ENCODING = "UTF-8";
private final Factory<File> temporaryDirFactory;
private final XmlTransformer xmlTransformer = new XmlTransformer();
AbstractMavenPublisher(Factory<File> temporaryDirFactory) {
this.temporaryDirFactory = temporaryDirFactory;
}
protected void publish(MavenNormalizedPublication publication, ExternalResourceRepository repository, URI rootUri, boolean localRepo) {
String groupId = publication.getGroupId();
String artifactId = publication.getArtifactId();
String version = publication.getVersion();
ModuleArtifactPublisher artifactPublisher = new ModuleArtifactPublisher(repository, localRepo, rootUri, groupId, artifactId, version);
if (isSnapshot(version)) {
ExternalResourceName snapshotMetadataPath = artifactPublisher.getSnapshotMetadataLocation();
Metadata snapshotMetadata = createSnapshotMetadata(publication, groupId, artifactId, version, repository, snapshotMetadataPath);
artifactPublisher.publish(snapshotMetadataPath, writeMetadataToTmpFile(snapshotMetadata, "snapshot-maven-metadata.xml"));
if (!localRepo) {
// Use the timestamped version for all published artifacts:
// The timestamped version is hidden deep in `Metadata.versioning.snapshotVersions`
artifactPublisher.artifactVersion = snapshotMetadata.getVersioning().getSnapshotVersions().get(0).getVersion();
}
}
if (publication.getMainArtifact() != null) {
String packaging = publication.getPackaging();
String extension = packaging == null || JAR_PACKAGINGS.contains(packaging) ? publication.getMainArtifact().getExtension() : packaging;
artifactPublisher.publish(null, extension, publication.getMainArtifact().getFile());
}
artifactPublisher.publish(null, "pom", publication.getPomArtifact().getFile());
for (MavenArtifact artifact : publication.getAdditionalArtifacts()) {
artifactPublisher.publish(artifact.getClassifier(), artifact.getExtension(), artifact.getFile());
}
ExternalResourceName externalResource = artifactPublisher.getMetadataLocation();
Metadata metadata = createMetadata(groupId, artifactId, version, repository, externalResource);
artifactPublisher.publish(externalResource, writeMetadataToTmpFile(metadata, "module-maven-metadata.xml"));
}
private Metadata createMetadata(String groupId, String artifactId, String version, ExternalResourceRepository repository, ExternalResourceName metadataResource) {
Versioning versioning = getExistingVersioning(repository, metadataResource);
if (!versioning.getVersions().contains(version)) {
versioning.addVersion(version);
}
versioning.setLatest(version);
if (!isSnapshot(version)) {
versioning.setRelease(version);
}
versioning.updateTimestamp();
Metadata metadata = new Metadata();
metadata.setGroupId(groupId);
metadata.setArtifactId(artifactId);
metadata.setVersioning(versioning);
return metadata;
}
private Versioning getExistingVersioning(ExternalResourceRepository repository, ExternalResourceName metadataResource) {
ExternalResourceReadResult<Metadata> existing = readExistingMetadata(repository, metadataResource);
if (existing != null) {
Metadata recessive = existing.getResult();
if (recessive.getVersioning() != null) {
return recessive.getVersioning();
}
}
return new Versioning();
}
private File writeMetadataToTmpFile(Metadata metadata, String fileName) {
File metadataFile = new File(temporaryDirFactory.create(), fileName);
xmlTransformer.transform(metadataFile, POM_FILE_ENCODING, writer -> {
try {
new MetadataXpp3Writer().write(writer, metadata);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
return metadataFile;
}
ExternalResourceReadResult<Metadata> readExistingMetadata(ExternalResourceRepository repository, ExternalResourceName metadataResource) {
return repository.resource(metadataResource).withContentIfPresent(inputStream -> {
try {
return new MetadataXpp3Reader().read(inputStream, false);
} catch (Exception e) {
throw UncheckedException.throwAsUncheckedException(e);
}
});
}
protected abstract Metadata createSnapshotMetadata(MavenNormalizedPublication publication, String groupId, String artifactId, String version, ExternalResourceRepository repository, ExternalResourceName metadataResource);
/**
* Publishes artifacts for a single Maven module.
*/
private static class ModuleArtifactPublisher {
private final NetworkOperationBackOffAndRetry networkOperationRunner = new NetworkOperationBackOffAndRetry();
private final ExternalResourceRepository repository;
private final boolean localRepo;
private final URI rootUri;
private final String groupPath;
private final String artifactId;
private final String moduleVersion;
private String artifactVersion;
ModuleArtifactPublisher(ExternalResourceRepository repository, boolean localRepo, URI rootUri, String groupId, String artifactId, String moduleVersion) {
this.repository = repository.withProgressLogging();
this.localRepo = localRepo;
this.rootUri = rootUri;
this.groupPath = groupId.replace('.', '/');
this.artifactId = artifactId;
this.moduleVersion = moduleVersion;
this.artifactVersion = moduleVersion;
}
/**
* Return the location of the module `maven-metadata.xml`, which lists all published versions for a Maven module.
*/
ExternalResourceName getMetadataLocation() {
String path = groupPath + '/' + artifactId + '/' + getMetadataFileName();
return new ExternalResourceName(rootUri, path);
}
/**
* Return the location of the snapshot `maven-metadata.xml`, which contains details of the latest published snapshot for a Maven module.
*/
ExternalResourceName getSnapshotMetadataLocation() {
String path = groupPath + '/' + artifactId + '/' + moduleVersion + '/' + getMetadataFileName();
return new ExternalResourceName(rootUri, path);
}
private String getMetadataFileName() {
if (localRepo) {
return "maven-metadata-local.xml";
}
return "maven-metadata.xml";
}
/**
* Publishes a single module artifact, based on classifier and extension.
*/
void publish(String classifier, String extension, File content) {
StringBuilder path = new StringBuilder(128);
path.append(groupPath).append('/');
path.append(artifactId).append('/');
path.append(moduleVersion).append('/');
path.append(artifactId).append('-').append(artifactVersion);
if (classifier != null) {
path.append('-').append(classifier);
}
if (extension.length() > 0) {
path.append('.').append(extension);
}
ExternalResourceName externalResource = new ExternalResourceName(rootUri, path.toString());
publish(externalResource, content);
}
void publish(ExternalResourceName externalResource, File content) {
if (!localRepo) {
LOGGER.info("Uploading {} to {}", externalResource.getShortDisplayName(), externalResource.getPath());
}
putResource(externalResource, new FileReadableContent(content));
if (!localRepo) {
publishChecksums(externalResource, content);
}
}
private void publishChecksums(ExternalResourceName destination, File content) {
byte[] sha1 = createChecksumFile(content, "SHA1", 40);
putResource(destination.append(".sha1"), new ByteArrayReadableContent(sha1));
byte[] md5 = createChecksumFile(content, "MD5", 32);
putResource(destination.append(".md5"), new ByteArrayReadableContent(md5));
}
private byte[] createChecksumFile(File src, String algorithm, int checksumLength) {
HashValue hash = HashUtil.createHash(src, algorithm);
String formattedHashString = hash.asZeroPaddedHexString(checksumLength);
return formattedHashString.getBytes(StandardCharsets.US_ASCII);
}
private void putResource(ExternalResourceName externalResource, ReadableContent readableContent) {
networkOperationRunner.withBackoffAndRetry(new Runnable() {
@Override
public void run() {
repository.resource(externalResource).put(readableContent);
}
@Override
public String toString() {
return "PUT " + externalResource.getDisplayName();
}
});
}
}
}