gradle 缓存转maven仓库

// Top-level build file where you can add configuration options common to all sub-projects/modules.
import java.io.FileInputStream
import java.security.MessageDigest
import java.text.SimpleDateFormat
import java.util.Date

plugins {
    id("com.android.application") version "8.1.4" apply false
    id("org.jetbrains.kotlin.android") version "1.9.21" apply false
    id("com.android.library") version "8.1.4" apply false
    id("com.google.dagger.hilt.android") version "2.48.1" apply false

    alias(libs.plugins.navigation.safe.args.kotlin) apply false
}
buildscript{
    dependencies{
        classpath(libs.protobuf.gradle.plugin)
        classpath(libs.google.java.format.gradle.plugin)
        classpath(libs.didi.drouter.plugin)
        classpath(libs.objectbox.gradle.plugin)
        classpath(libs.apmplus.upload.plugin)
        classpath(libs.walle.plugin)
        classpath(libs.sensorsdata.gradle.plugin)
        classpath(libs.hms.agconnect)
        //fcm 推送
//        classpath(libs.google.services)
    }

}

tasks.register("gradleCacheToMaven", Delete::class) {
    val gradleUserHomeDir = gradle.gradleUserHomeDir
    val gradleCacheDir = File(gradleUserHomeDir, "caches/modules-2/files-2.1")
    val mavenTargetDir = File(gradleUserHomeDir, "caches${File.separator}m2-repository")

    gradleCacheDir.listFiles()?.forEach { groupDir ->
        if (groupDir.isDirectory) { //只关心文件夹
            groupDir.listFiles().forEach { artifactDir ->
                if (artifactDir.isDirectory) { //只关心文件夹
                    artifactDir.listFiles().forEach { versionDir ->
                        println("------------------------------groupDir:${groupDir.name} artifactDir:${artifactDir.name} versionDir:${versionDir.name}------------------------------")
                        val tagetDir = File(mavenTargetDir,
                            "${
                                groupDir.name.replace(
                                    ".",
                                    File.separator
                                )
                            }${File.separator}${artifactDir.name}${File.separator}${versionDir.name}"
                        )
                        val allFiles = listFilesRecursively(versionDir)
                        val hasCode =
                            allFiles.any { it.name == "${artifactDir.name}-${versionDir.name}.jar" || it.name == "${artifactDir.name}-${versionDir.name}.aar" }
                        val hasPom = allFiles.any { it.name.endsWith(".pom") }

                        if (hasCode && hasPom) {
                            allFiles.filter {
                                it.name != ".DS_Store"
                            }.forEach {
                                println("copy ${it.name} to $tagetDir")
                                val targetFile = File(tagetDir, it.name)
                                it.copyTo(targetFile, overwrite = true)
                                println("复制文件${it.name} 到 $tagetDir")
                            }
                            println("writeMetadata ${tagetDir} ")
                            writeMetadata(tagetDir.parentFile)
                        } else {
                            println("groupDir:${groupDir.name} artifactDir:${artifactDir.name} versionDir:${versionDir.name} no code or pom code=$hasCode pom=$hasPom")
                        }
                    }
                }
            }
        }
    }


}

// 递归函数,用于遍历文件夹及其子文件夹
fun listFilesRecursively(file: File): List<File> {
    val files = mutableListOf<File>()
    if (file.isDirectory) {
        file.listFiles()?.forEach { childFile ->
            files += listFilesRecursively(childFile)
        }
    } else {
        files += file
    }
    return files
}

/**
 * 获取文件MD5/SHA-1/SHA-256/SHA-512哈希值
 */
fun getFileHash(file: File, algorithm: String): String? {
    if (!file.exists()) return null
    val buffer = ByteArray(1024)
    val digest = MessageDigest.getInstance(algorithm)
    FileInputStream(file).use { fis ->
        var bytesRead = fis.read(buffer)
        while (bytesRead > -1) {
            digest.update(buffer, 0, bytesRead)
            bytesRead = fis.read(buffer)
        }
    }
    val hashBytes = digest.digest()
    return hashBytes.joinToString(separator = "") { "%02x".format(it) }
}

/**
 * 生成文件的MD5/SHA-1/SHA-256/SHA-512哈希值,并将结果写入文件
 */
fun writeFileHash(targetFile: File) {
    listOf("MD5", "SHA-1", "SHA-256", "SHA-512").forEach { algorithm ->
        getFileHash(targetFile, algorithm)?.let { hash ->
            File(targetFile.parent, "${targetFile.name}.${algorithm.lowercase()}").writeText(hash)
        }
    }
}
/**
 * 生成metadata文件,并将结果写入文件
 */
fun writeMetadata(artifactFile: File) {
    val versionsDirs = artifactFile.listFiles().filter { it.isDirectory }.map { it.name }
    val sortedVersions=versionsDirs.sortedWith(versionComparator)
   val versionXml= sortedVersions.joinToString("\n") { "<version>$it</version>" }
val metadata = """<metadata>
<groupId>${artifactFile.parentFile.name}</groupId>
<artifactId>${artifactFile.name}</artifactId>
<versioning>
<latest>${sortedVersions.last()}</latest>
<release>${sortedVersions.last()}</release>
<versions>
$versionXml
</versions>
<lastUpdated>${SimpleDateFormat("yyyyMMddHHmmss").format(Date())}</lastUpdated>
</versioning>
</metadata>"""
    File(artifactFile, "maven-metadata.xml").apply {
        println("写metadata 到 $absolutePath")
        writeText(metadata)
    }

}


/**
 * 版本号比较器
 */
val versionComparator = Comparator<String> { v1, v2 ->
    val splitV1 = v1.split("[.-]".toRegex()).map { it.toIntOrNull() ?: it }
    val splitV2 = v2.split("[.-]".toRegex()).map { it.toIntOrNull() ?: it }
    // 逐部分比较版本号
    for (i in 0 until maxOf(splitV1.size, splitV2.size)) {
        val part1 = splitV1.getOrNull(i) ?: 0
        val part2 = splitV2.getOrNull(i) ?: 0
        val comparison = when {
            part1 is Int && part2 is Int ->{
               val maxLen= kotlin.math.max(part1.toInt().toString().length,part2.toInt().toString().length )
                val new1 =   part1.toString().padEnd(maxLen, '0').toInt()
                val new2 =   part2.toString().padEnd(maxLen, '0').toInt()
                new1.compareTo(new2)
            }
            part1 is String && part2 is String -> part1.compareTo(part2)
            part1 is Int -> -1
            else -> 1
        }
        if (comparison != 0) return@Comparator comparison
    }
    0
}

posted @ 2024-12-18 14:56  烟花易冷心易碎  阅读(130)  评论(0)    收藏  举报