fun getTargetFile()

in src/download-file/src.main.kts [30:55]


fun getTargetFile(url: String, outputDir: String, targetFileName: String): File {
    val targetDir = outputDir
        .ifBlank { File(".").absolutePath }
        .let { File(it) }
        .normalize()

    val filePath = targetDir.let {
        when {
            it.isDirectory -> it
            !it.exists() -> {
                if (!it.mkdirs()) throw IllegalArgumentException("Failed to create directory: ${it.absolutePath}")
                it
            }

            else -> throw IllegalArgumentException("Destination already exists and is not a directory: ${it.absolutePath}")
        }
    }

    val fileName = sequenceOf(
        targetFileName,
        url.substringAfterLast('/'),
        "downloaded_file"
    ).first { it.isNotEmpty() }

    return File(filePath, fileName).normalize()
}