Skip to content

Instantly share code, notes, and snippets.

@mosamman
Last active June 5, 2023 03:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mosamman/eaa92795b300225c6e499c0fb3d6ef6f to your computer and use it in GitHub Desktop.
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.
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()
}
@mosamman
Copy link
Author

mosamman commented Dec 15, 2019

Variable Example
ARTIFACT_GROUP com.foo.bar
ARTIFACT_ID plugin
ARTIFACT_VERSION 0.0.1
MAVEN_SERVER https://[your-host]/
MAVEN_USERNAME user
MAVEN_PASSWORD secret

Note : if you use different auth schema you need to change urlExists method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment