You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在build.gradle.kts中获取已下载依赖与插件的本地路径?

获取gRPC/Protobuf依赖与插件的本地路径(Gradle Kotlin DSL)

1. 获取Implementation依赖的本地路径

对于implementation块中声明的gRPC依赖(如grpc-kotlin-stub、grpc-protobuf),可直接通过Gradle配置对象解析出本地文件路径:

tasks.register("printGrpcDepsPath") {
    doLast {
        // 获取implementation配置下所有已解析的依赖文件
        val implementationDeps = configurations["implementation"].resolve()
        // 筛选出gRPC相关依赖
        val grpcRelatedDeps = implementationDeps.filter { 
            it.name.startsWith("grpc-") 
        }
        // 输出路径
        grpcRelatedDeps.forEach { dep ->
            println("gRPC依赖路径: ${dep.absolutePath}")
        }
    }
}

2. 获取Protobuf插件(protoc、grpc-java、grpc-kotlin)的本地路径

Protobuf插件的artifact声明在protobuf扩展中,需创建可解析的临时配置来拉取并解析这些插件的本地文件:

// 创建临时配置,用于解析Protobuf工具类依赖
val protoToolsConfig = configurations.create("protoTools") {
    isCanBeResolved = true
    isCanBeConsumed = false
}

// 将Protobuf扩展中的工具artifact绑定到临时配置
dependencies {
    protoToolsConfig(protobuf.protoc.artifact)
    protoToolsConfig(protobuf.plugins["grpc"].artifact)
    protoToolsConfig(protobuf.plugins["grpckt"].artifact)
}

// 注册exec任务,获取路径并执行操作
tasks.register("useProtoTools") {
    dependsOn(protoToolsConfig) // 确保依赖先完成解析
    doLast {
        val tools = protoToolsConfig.resolve()
        // 匹配对应工具的本地路径
        val protocPath = tools.first { it.name.startsWith("protoc-") }.absolutePath
        val grpcJavaPluginPath = tools.first { it.name.startsWith("protoc-gen-grpc-java-") }.absolutePath
        val grpcKotlinPluginPath = tools.first { it.name.startsWith("protoc-gen-grpc-kotlin-") }.absolutePath

        println("protoc路径: $protocPath")
        println("grpc-java插件路径: $grpcJavaPluginPath")
        println("grpc-kotlin插件路径: $grpcKotlinPluginPath")

        // 在这里执行你的exec操作,例如调用protoc并传入插件路径
        exec {
            commandLine(
                protocPath,
                "--plugin=protoc-gen-grpc=$grpcJavaPluginPath",
                "--plugin=protoc-gen-grpckt=$grpcKotlinPluginPath",
                // 添加其他protoc参数...
            )
        }
    }
}

关键说明

  • configurations.resolve():触发Gradle下载依赖(未缓存时),返回依赖对应的本地文件列表。
  • 临时配置protoToolsConfig:必须设置isCanBeResolved = true才能解析依赖;isCanBeConsumed = false表示该配置仅内部使用,不对外暴露。
  • 文件筛选的startsWith规则可根据实际artifact名称调整,确保匹配到目标文件。

内容的提问来源于stack exchange,提问作者molecule

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 18:06:01