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

如何在Gradle任务中执行仓库托管的protoc工具?(Android场景)

解决方案:使用Maven Central的预编译protoc替代系统安装版本

我来帮你解决这个问题——你遇到的核心问题是protoc在Maven Central上是按不同操作系统/架构分artifact发布的,直接依赖不带classifier的坐标不会自动下载对应你构建主机的二进制文件。下面是完整的可运行配置:

1. 完整配置代码

repositories {
    mavenCentral()
}

// 定义用于获取protoc的配置
configurations {
    proto_encode
}

// 动态匹配当前构建主机的protoc二进制包
def getProtocClassifier() {
    def os = org.gradle.nativeplatform.platform.internal.DefaultNativePlatform.currentOperatingSystem
    def arch = System.getProperty("os.arch")
    
    if (os.isLinux()) {
        return "linux-x86_64"
    } else if (os.isMacOsX()) {
        return arch == "aarch64" ? "osx-aarch_64" : "osx-x86_64"
    } else if (os.isWindows()) {
        return "windows-x86_64"
    }
    throw new GradleException("Unsupported operating system for protoc")
}

dependencies {
    proto_encode "com.google.protobuf:protoc:3.0.0:${getProtocClassifier()}"
}

task encodeData {
    ext.resDir = file("$buildDir/binary_proto")
    def inputDir = 'text_pb'
    def outputDir = "$resDir/raw"
    
    inputs.dir inputDir
    outputs.dir outputDir
    
    // 确保先下载protoc再执行任务
    dependsOn configurations.proto_encode
    
    doLast {
        file(outputDir).mkdirs()
        def protocPath = configurations.proto_encode.singleFile.absolutePath
        
        file(inputDir).eachFile { inputFile ->
            def outputFile = new File(outputDir, inputFile.name)
            exec {
                commandLine protocPath,
                    "--encode=MyMessage",
                    "src/main/proto/my_proto.proto",
                    "--input_path=${inputFile.absolutePath}",
                    "--output_path=${outputFile.absolutePath}"
            }
        }
    }
}

android {
    applicationVariants.all { variant ->
        variant.registerResGeneratingTask(encodeData, encodeData.resDir)
    }
}

2. 关键修改说明

  • 动态选择protoc artifact:通过getProtocClassifier()方法自动识别当前构建主机的系统和架构,匹配Maven Central上对应的预编译protoc包(支持Linux、macOS(包括Intel/M1)、Windows)。
  • 依赖下载优先级:给encodeData任务添加dependsOn configurations.proto_encode,确保Gradle先完成protoc的下载再执行编码逻辑。
  • 跨平台执行优化:直接调用下载好的protoc二进制文件,替代原来的sh -c命令,避免shell转义问题,同时保证在Windows系统上也能正常运行。
  • 明确路径参数:使用--input_path和--output_path参数替代重定向,让命令逻辑更清晰,减少出错概率。

3. 版本更新提示

如果你需要使用更高版本的protoc,只需要修改依赖中的版本号(比如3.25.3),classifier的匹配逻辑不需要调整,因为Google保持了一致的artifact命名规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:37:45