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

Compose Desktop打包后添加自定义Gradle任务失败求助

解决Compose Desktop打包macOS时自定义权限任务无法加入执行流程的问题

问题分析

你的setExecutablePermission任务存在两个核心问题:

  1. 错误使用Copy任务类型:该任务仅需执行权限设置,不需要复制操作,误用类型可能导致Gradle对任务执行逻辑判断异常。
  2. 任务关联逻辑时机与目标匹配不准确:硬编码任务名createDistributable可能因Compose Desktop版本差异失效,且在任务内部嵌套project.afterEvaluate的写法不符合Gradle配置规范。

修正后的任务代码

将任务改为DefaultTask类型,通过任务类型匹配而非硬编码名称关联打包流程,确保跨版本兼容性:

tasks.register<DefaultTask>("setExecutablePermission") {
    description = "Sets executable permission for the generated .app bundle on macOS"

    doLast {
        val osName = System.getProperty("os.name")
        if (osName.startsWith("Mac OS")) {
            // 使用layout.buildDirectory统一获取构建目录,避免硬编码路径
            val appBundle = layout.buildDirectory.file("compose/binaries/main/app/simple-card-game.app").get().asFile
            if (appBundle.exists()) {
                val executableFile = file("${appBundle}/Contents/MacOS/simple-card-game")
                executableFile.setExecutable(true, false)
                println("Executable permission set for: $executableFile")
            } else {
                println("Warning: .app bundle not found. Skipping setExecutablePermission task.")
            }
        } else {
            println("Not running on macOS. Skipping setExecutablePermission task.")
        }
    }
}

// 在project级别配置任务依赖,而非任务内部
project.afterEvaluate {
    // 匹配Compose Desktop的打包任务类型,兼容版本差异
    val packageTasks = tasks.withType<org.jetbrains.compose.desktop.application.tasks.MakePackageTask>()
    if (packageTasks.isNotEmpty()) {
        packageTasks.forEach { it.finalizedBy(tasks.named("setExecutablePermission")) }
    } else {
        // 兼容旧版本任务名
        val fallbackTask = tasks.findByName("createDistributable") ?: tasks.findByName("packageDistributionForCurrentOS")
        fallbackTask?.let { it.finalizedBy(tasks.named("setExecutablePermission")) } 
            ?: println("Warning: No valid package task found to attach setExecutablePermission.")
    }
}

关键改进点

  • 任务类型修正:用DefaultTask替代Copy,明确任务仅执行权限设置逻辑,符合Gradle任务设计原则。
  • 动态任务匹配:通过tasks.withType<MakePackageTask>()匹配打包任务类型,避免版本升级导致任务名变更的问题。
  • 依赖配置时机:在project级别的afterEvaluate中配置依赖,确保所有打包任务注册完成后再关联自定义任务。

调试建议

  • 查看完整任务列表:执行./gradlew tasks --all,搜索"distribution"或"package"相关任务,确认实际存在的打包任务名称。
  • 检查任务依赖树:执行./gradlew [你的打包任务名] --dry-run,查看任务执行序列中是否包含setExecutablePermission。
  • 启用Gradle日志:添加--info或--debug参数执行打包命令(如./gradlew createDistributable --info),查看任务注册和关联的详细日志。
  • 验证任务存在性:在project.afterEvaluate中添加println("All tasks: ${tasks.map { it.name }}"),确认自定义任务和目标打包任务都已正确注册。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:33:19