How do I check if an artifact exists in a remote repository using gradle?
I haven't been able to find any plugins for gradle that accomplish this.
I've had an idea of creating a function in build.gradle that checks if the url of the repository exists. But this doesn't seem like the right way of doing it.
Boolean ifExists = new URL(url).openConnection().with {
requestMethod = 'HEAD'
connect()
responseCode == 200
}
Any suggestions would be much appreciated.
Using Kotlin DSL you may check if the artifact exists in any of registered repositories in the following way:
import com.github.kittinunf.fuel.httpGet
buildscript {
dependencies {
"classpath"("com.github.kittinunf.fuel:fuel:2.3.1") // you may use any other HTTP-client if you want
}
}
tasks {
register("checkDependencies") {
doFirst {
project.configurations["implementation"].dependencies.forEach { dependency ->
project.repositories.forEach { repository ->
val repositoryURL = (repository as MavenArtifactRepository).url
val artifactURL = "$repositoryURL${dependency.group?.replace('.', '/')}/${dependency.name}/${dependency.version}/${dependency.name}-${dependency.version}.jar"
val (_, response, _) = artifactURL.httpGet().response()
println("$dependency: ${response.statusCode}")
}
}
}
}
}
It doesn't appear there is an official Gradle plugin to support checking for an artifact's existence. However, you should be able to accomplish this by executing a curl command in a Java process: Curl flags explanation:
-I flag for headers only.
-s for silent mode. (No prog meter or error messages)
Your command may look slightly different than the one below if you need to authenticate to the artifact resource, but I am assuming you have already accounted for that in your url:
String curlCommand= "curl -I -s " + url + " | grep HTTP";
Process process = Runtime.getRuntime().exec(curlCommand);
process.getInputStream();
If your artifact is found, the process will print "HTTP/1.1 200 OK"
Otherwise, "HTTP/1.1 404 Not Found"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With