All Downloads are FREE. Search and download functionalities are using the official Maven repository.

name.remal.gradle_plugins.dsl.artifact.Artifact.kt Maven / Gradle / Ivy

package name.remal.gradle_plugins.dsl.artifact

import java.io.BufferedInputStream
import java.io.File
import java.io.FileNotFoundException
import java.io.InputStream
import java.util.zip.ZipException
import java.util.zip.ZipFile

class Artifact(private val file: File) : BaseHasEntries() {

    override val entryNames: Set by lazy {
        val result = sortedSetOf()
        if (file.isFile) {
            try {
                ZipFile(file).use { zipFile ->
                    val entries = zipFile.entries()
                    while (entries.hasMoreElements()) {
                        val entry = entries.nextElement()
                        if (entry.isDirectory) continue
                        result += entry.name
                    }
                }

            } catch (e: ZipException) {
                // do nothing
            }

        } else if (file.isDirectory) {
            file.walk().filter(File::isFile).forEach { resourceFile ->
                result += resourceFile.relativeTo(file).path.replace(File.separatorChar, '/')
            }
        }
        return@lazy result
    }

    override fun openStream(entryName: String): InputStream {
        if (file.isFile) {
            val zipFile = ZipFile(file)
            val entry = zipFile.getEntry(entryName) ?: throw ArtifactEntryNotFoundException("Artifact entry not found: $entryName")
            val inputStream = zipFile.getInputStream(entry)
            return object : BufferedInputStream(inputStream) {
                override fun close() {
                    super.close()
                    zipFile.close()
                }
            }

        } else if (file.isDirectory) {
            try {
                return File(file, entryName).inputStream()
            } catch (e: FileNotFoundException) {
                throw ArtifactEntryNotFoundException("Artifact entry not found: $entryName", e)
            }

        } else {
            throw ArtifactFileNotFoundException("Artifact file not found: $file")
        }
    }

    override fun toString(): String {
        return file.path
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy