Skip to content

复制与过滤

Gradle 的 Copy 任务提供强大的文件复制和内容过滤功能。

基本复制

kotlin
tasks.register<Copy>("copyFiles") {
    from("src/config")
    into("$buildDir/config")
}

// 多源目录
tasks.register<Copy>("copyAll") {
    from("src/config") {
        include("*.yml")
        into("config")          // 放入 config 子目录
    }
    from("src/scripts") {
        include("*.sh")
        into("bin")
    }
    from(tasks.named("jar"))    // 来自其他任务的输出
    into("$buildDir/dist")
}

包含与排除

kotlin
tasks.register<Copy>("copyResources") {
    from("src/main/resources")
    into("$buildDir/resources")
    
    // 包含(白名单)
    include("**/*.yml", "**/*.xml", "**/*.properties")
    
    // 排除(黑名单)
    exclude("**/*.bak", "**/test-*")
    
    // 动态排除
    exclude { element ->
        element.file.name.startsWith("temp")
    }
}

内容过滤

kotlin
tasks.register<Copy>("processConfig") {
    from("src/config")
    into("$buildDir/config")
    
    // 替换 @token@ 样式的占位符(Ant 风格)
    filter<org.apache.tools.ant.filters.ReplaceTokens>("tokens" to mapOf(
        "VERSION" to project.version.toString(),
        "BUILD_DATE" to java.time.LocalDate.now().toString()
    ))
    
    // 行级过滤(Lambda)
    filter { line ->
        line.replace("\${version}", project.version.toString())
    }
    
    // 正则替换
    filteringCharset = "UTF-8"
}

文件重命名

kotlin
tasks.register<Copy>("renameFiles") {
    from("src/templates")
    into("$buildDir/output")
    
    // 简单重命名(正则)
    rename("(.+)-template\\.xml", "$1.xml")
    
    // Lambda 重命名
    rename { filename ->
        if (filename.endsWith("-dev.yml")) {
            filename.replace("-dev.yml", ".yml")
        } else {
            filename
        }
    }
}

文件权限

kotlin
tasks.register<Copy>("copyScripts") {
    from("scripts")
    into("$buildDir/bin")
    fileMode = "755".toInt(8)      // rwxr-xr-x
    dirMode = "755".toInt(8)
}

expand - 模板变量替换

kotlin
tasks.register<Copy>("expandTemplate") {
    from("src/template")
    into("$buildDir/output")
    
    // Groovy 模板语法:${variable}
    expand(
        "version" to project.version,
        "appName" to project.name,
        "buildTime" to java.time.LocalDateTime.now()
    )
}
# src/template/build-info.txt
Application: ${appName}
Version: ${version}
Built at: ${buildTime}

Sync 任务

Sync 类似 Copy,但会删除目标目录中多余的文件(保持同步):

kotlin
tasks.register<Sync>("syncDist") {
    from("src/main/resources")
    into("dist")
    preserve {
        include("logs/**")   // 保留 logs 目录不删除
    }
}

下一步