Last active
December 24, 2024 14:59
-
-
Save mosamman/eaa92795b300225c6e499c0fb3d6ef6f to your computer and use it in GitHub Desktop.
A Simple gradle task to check if the artifact version exists before publishing to maven server.
This file contains hidden or 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
publish.dependsOn lookForArtifacts | |
task lookForArtifacts { | |
group "upload" | |
doLast { | |
def pomFileName = "${ARTIFACT_ID}-${ARTIFACT_VERSION}.pom" | |
def artifactPath = "${ARTIFACT_GROUP.replace(".", "/")}/${ARTIFACT_ID}/${ARTIFACT_VERSION}/${pomFileName}" | |
def repositoryUrl = "$MAVEN_SERVER/${artifactPath}" | |
println("# searching for existing artifact wit id ${ARTIFACT_VERSION}") | |
println("") | |
if (urlExists(repositoryUrl)) { | |
println("# Existing artifact found") | |
println("") | |
throw new RuntimeException("Artifact with version $ARTIFACT_VERSION already exist - increase the verion to publish") | |
} else { | |
println("# No existing artifact found. Preceding to publish") | |
println("") | |
} | |
} | |
} | |
def urlExists(String repositoryUrl) { | |
try { | |
def connection = (HttpURLConnection) new URL(repositoryUrl).openConnection() | |
connection.setRequestProperty("Authorization", "Basic " + getBase64EncodedCredentials()) | |
connection.setConnectTimeout(10000) | |
connection.setReadTimeout(10000) | |
connection.setRequestMethod("HEAD") | |
def responseCode = connection.getResponseCode() | |
if (responseCode == 401) { | |
throw new RuntimeException("Unauthorized MavenUser user. Please provide valid username and password.") | |
} | |
return (200 == responseCode) | |
} catch (IOException ignored) { | |
println(ignored) | |
return false | |
} | |
} | |
def getBase64EncodedCredentials() { | |
def s = "$MAVEN_USERNAME" + ":" + "$MAVEN_PASSWORD" | |
return s.bytes.encodeBase64().toString() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note : if you use different auth schema you need to change
urlExists
method.