【问题标题】:Find if an artifact exists in remote repository查找远程存储库中是否存在工件
【发布时间】:2021-12-11 18:23:56
【问题描述】:

如何使用 gradle 检查远程仓库中是否存在工件?

我还没有找到任何 gradle 插件来完成这个。

我想在 build.gradle 中创建一个函数来检查存储库的 url 是否存在。但这似乎不是正确的做法。

Boolean ifExists = new URL(url).openConnection().with {
        requestMethod = 'HEAD'
        connect()
        responseCode == 200
}

任何建议将不胜感激。

【问题讨论】:

  • 你为什么要这个?你想解决哪个问题?
  • 本质上我的问题是,我希望我的构建首先检查存储库中是否存在具有特定名称的工件(该工件可能存在也可能不存在),如果存在则使用它.如果它不存在,我希望我的构建默认为另一个我知道总是存在的工件。
  • 您要使用最新版本还是?

标签: java gradle build artifactory dependency-management


【解决方案1】:

似乎没有官方 Gradle 插件来支持检查工件的存在。但是,您应该能够通过在 Java 进程中执行 curl 命令来完成此操作: 卷曲标志说明:

-I 标志仅用于标头。

-s 用于静音模式。 (没有进度表或错误消息)

如果您需要对工件资源进行身份验证,您的命令可能看起来与以下命令略有不同,但我假设您已经在 url 中考虑了这一点:

String curlCommand= "curl -I -s " + url + " | grep HTTP";
Process process = Runtime.getRuntime().exec(curlCommand);
process.getInputStream();

如果找到您的工件,该过程将打印"HTTP/1.1 200 OK"

否则,"HTTP/1.1 404 Not Found"

【讨论】:

  • 或者没有 curl:``` def conn = (HttpURLConnection) new URL(artifactUrl).openConnection() conn.setRequestMethod("HEAD") def rc = conn.getResponseCode() if (rc.等于(200))...```
【解决方案2】:

使用 Kotlin DSL,您可以通过以下方式检查工件是否存在于任何已注册的存储库中:

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}")
                }
            }
        }
    }
}

【讨论】:

    【解决方案3】:

    不确定这是否有帮助,https://github.com/ben-manes/gradle-versions-plugin。您可以重新连线以指定要丢弃的不稳定版本。

    或通过始终查看最新版本来强制执行此操作 https://github.com/patrikerdes/gradle-use-latest-versions-plugin

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 2016-05-11
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多