-
-
Notifications
You must be signed in to change notification settings - Fork 255
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add support for publishing maven-metadata.xml #1260
Open
fzakaria
wants to merge
1
commit into
bazel-contrib:master
Choose a base branch
from
fzakaria:upload-maven-metadata
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -31,6 +31,7 @@ | |
import com.google.cloud.storage.Storage; | ||
import com.google.cloud.storage.StorageOptions; | ||
import com.google.common.base.Splitter; | ||
|
||
import java.io.IOException; | ||
import java.io.InputStream; | ||
import java.io.OutputStream; | ||
|
@@ -57,8 +58,33 @@ | |
import java.util.concurrent.Executors; | ||
import java.util.concurrent.TimeoutException; | ||
import java.util.logging.Logger; | ||
|
||
import com.google.common.io.CharStreams; | ||
import software.amazon.awssdk.services.s3.S3Client; | ||
import software.amazon.awssdk.services.s3.model.PutObjectRequest; | ||
import com.google.api.client.http.javanet.NetHttpTransport; | ||
import com.google.api.client.http.HttpTransport; | ||
import com.google.api.client.http.HttpRequest; | ||
import com.google.api.client.http.HttpResponse; | ||
import com.google.api.client.http.HttpResponseException; | ||
import com.google.api.client.http.GenericUrl; | ||
|
||
import java.io.UncheckedIOException; | ||
|
||
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 java.nio.charset.StandardCharsets; | ||
import java.net.URISyntaxException; | ||
import java.util.Optional; | ||
import java.io.StringReader; | ||
import java.io.ByteArrayOutputStream; | ||
import java.util.stream.Collectors; | ||
import java.text.SimpleDateFormat; | ||
import java.util.Date; | ||
import java.io.InputStreamReader; | ||
|
||
public class MavenPublisher { | ||
|
||
|
@@ -108,8 +134,10 @@ public static void main(String[] args) | |
futures.add(upload(repo, credentials, coords, "." + ext, mainArtifact, signingMetadata)); | ||
} | ||
|
||
if (args.length > 3 && !args[3].isEmpty()) { | ||
List<String> extraArtifactTuples = Splitter.onPattern(",").splitToList(args[3]); | ||
boolean publishMavenMetadata = Boolean.valueOf(args[3]); | ||
|
||
if (args.length > 4 && !args[4].isEmpty()) { | ||
List<String> extraArtifactTuples = Splitter.onPattern(",").splitToList(args[4]); | ||
for (String artifactTuple : extraArtifactTuples) { | ||
String[] splits = artifactTuple.split("="); | ||
String classifier = splits[0]; | ||
|
@@ -128,6 +156,16 @@ public static void main(String[] args) | |
|
||
CompletableFuture<Void> all = | ||
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); | ||
|
||
// uploading the maven-metadata.xml signals to cut over to the new version, so it must be at the end. | ||
if (publishMavenMetadata) { | ||
all = all.thenCompose(Void -> uploadMavenMetadata( | ||
repo, | ||
credentials, | ||
coords | ||
)); | ||
} | ||
|
||
all.get(30, MINUTES); | ||
} finally { | ||
EXECUTOR.shutdown(); | ||
|
@@ -150,6 +188,92 @@ private static boolean isSchemeSupported(String repo) { | |
return false; | ||
} | ||
|
||
/** | ||
* Download the pre-existing maven-metadata.xml file if it exists. | ||
* If no such file exists, create a default Metadata with the Coordinates provided. | ||
*/ | ||
private static CompletableFuture<Metadata> downloadExistingMavenMetadata( | ||
String repo, | ||
Credentials credentials, | ||
Coordinates coords | ||
) { | ||
String mavenMetadataUrl = | ||
String.format( | ||
"%s/%s/%s/maven-metadata.xml", | ||
repo.replaceAll("/$", ""), | ||
coords.groupId.replace('.', '/'), | ||
coords.artifactId); | ||
|
||
return download(mavenMetadataUrl, credentials).thenApply( optionalFileContents -> { | ||
try { | ||
if (optionalFileContents.isEmpty()) { | ||
// no file so just upload a new one | ||
// we must bootstrap | ||
Metadata metadata = new Metadata(); | ||
metadata.setGroupId(coords.groupId); | ||
metadata.setArtifactId(coords.artifactId); | ||
metadata.setVersioning(new Versioning()); | ||
return metadata; | ||
} | ||
return new MetadataXpp3Reader().read(new StringReader(optionalFileContents.get()), false); | ||
} catch (Exception e) { | ||
throw new RuntimeException(e); | ||
} | ||
|
||
}); | ||
} | ||
|
||
/** | ||
* Upload the new maven-metadata.xml with the new version included in the version list & | ||
* set the latest and release tags in the Metadata XML object. | ||
* This function will first download the pre-existing metadata-xml and augment. | ||
* If no maven-metadata.xml exists, a new one will be hydrated. | ||
*/ | ||
private static CompletableFuture<Void> uploadMavenMetadata( | ||
String repo, | ||
Credentials credentials, | ||
Coordinates coords | ||
) { | ||
|
||
String mavenMetadataUrl = | ||
String.format( | ||
"%s/%s/%s/maven-metadata.xml", | ||
repo.replaceAll("/$", ""), | ||
coords.groupId.replace('.', '/'), | ||
coords.artifactId); | ||
return downloadExistingMavenMetadata(repo, credentials, coords).thenCompose( | ||
metadata -> { | ||
try { | ||
|
||
// There is a chance versioning is null; handle it by creating the empty object. | ||
Versioning versioning = Optional.ofNullable(metadata.getVersioning()).orElse(new Versioning()); | ||
versioning.setLatest(coords.version); | ||
versioning.setRelease(coords.version); | ||
// This may be needed for SNAPSHOT support | ||
String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); | ||
versioning.setLastUpdated("20200731090423"); | ||
versioning.getVersions() | ||
.add(coords.version); | ||
// Let's handle adding multiple versions many times by turning it back to a set | ||
versioning.setVersions( | ||
versioning.getVersions() | ||
.stream() | ||
.distinct() | ||
.collect(Collectors.toList()) | ||
); | ||
metadata.setVersioning(versioning); | ||
|
||
Path newMavenMetadataXml = Files.createTempFile("maven-metadata", ".xml"); | ||
ByteArrayOutputStream os = new ByteArrayOutputStream(); | ||
new MetadataXpp3Writer().write(os, metadata); | ||
Files.write(newMavenMetadataXml, os.toByteArray()); | ||
return upload(mavenMetadataUrl, credentials, newMavenMetadataXml); | ||
} catch (Exception e) { | ||
throw new RuntimeException(e); | ||
} | ||
}); | ||
} | ||
|
||
private static CompletableFuture<Void> upload( | ||
String repo, | ||
Credentials credentials, | ||
|
@@ -261,6 +385,60 @@ private static String toHexS(String fmt, String algorithm, byte[] toHash) { | |
} | ||
} | ||
|
||
/** | ||
* Attempts to download the file at the given targetUrl. | ||
* Valid protocols are: http(s) & file at the moment. | ||
*/ | ||
private static CompletableFuture<Optional<String>> download( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: could move this to a separate file |
||
String targetUrl, Credentials credentials | ||
) { | ||
if (targetUrl.startsWith("http")) { | ||
return CompletableFuture.supplyAsync( () -> { | ||
try { | ||
HttpTransport httpTransport = new NetHttpTransport(); | ||
HttpRequest request = httpTransport.createRequestFactory(initRequest -> { | ||
Map<String, List<String>> authHeaders = credentials.getRequestMetadata(); | ||
// Add the authorization headers to the HTTP request | ||
if (authHeaders != null) { | ||
for (Map.Entry<String, List<String>> entry : authHeaders.entrySet()) { | ||
initRequest.getHeaders().put(entry.getKey(), entry.getValue()); | ||
} | ||
} | ||
}).buildGetRequest(new GenericUrl(targetUrl)); | ||
HttpResponse response = request.execute(); | ||
return Optional.of( | ||
CharStreams.toString(new InputStreamReader(response.getContent(), StandardCharsets.UTF_8)) | ||
); | ||
} | ||
catch (HttpResponseException e) { | ||
if (e.getStatusCode() == 404) { | ||
return Optional.empty(); | ||
} else { | ||
throw new UncheckedIOException(e); | ||
} | ||
} catch (IOException e) { | ||
throw new UncheckedIOException(e); | ||
} | ||
}); | ||
} else if (targetUrl.startsWith("file://")) { | ||
return CompletableFuture.supplyAsync( () -> { | ||
try { | ||
Path path = Paths.get(new URL(targetUrl).toURI()); | ||
if (!Files.exists(path)) { | ||
return Optional.empty(); | ||
} | ||
return Optional.of(com.google.common.io.Files.asCharSource(path.toFile(), StandardCharsets.UTF_8).read()); | ||
} catch (IOException e) { | ||
throw new UncheckedIOException(e); | ||
} catch (URISyntaxException e) { | ||
throw new RuntimeException(e); | ||
} | ||
}); | ||
} else { | ||
throw new IllegalArgumentException("Unsupported protocol for download."); | ||
} | ||
} | ||
|
||
private static CompletableFuture<Void> upload( | ||
String targetUrl, Credentials credentials, Path toUpload) { | ||
Callable<Void> callable; | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: upload could probably take InputStream but I didn't want to change too much of the code;
Open to doing another pass after on this file if you are open to it.