Skip to content

Instantly share code, notes, and snippets.

@remylavergne
Last active March 3, 2021 09:37
Show Gist options
  • Save remylavergne/dbb3e1d92291b96ca9468e8b5123e3f6 to your computer and use it in GitHub Desktop.
Save remylavergne/dbb3e1d92291b96ca9468e8b5123e3f6 to your computer and use it in GitHub Desktop.
[Kotlin - Coroutines - KScript] Script to copy local files / folders
@file:DependsOnMaven("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2")
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.runBlocking
import java.io.File
import kotlin.system.exitProcess
import kotlin.system.measureTimeMillis
interface ToKeep {
val path: String
val name: String
}
data class MyFile(
override val path: String,
override val name: String,
) : ToKeep
data class MyFolder(
override val path: String,
override val name: String,
) : ToKeep
val files = listOf<ToKeep>(
MyFile("/Downloads/tg_image_1079529249.jpeg", "tg_image_1079529249.jpeg"),
MyFile("/.zshrc", ".zshrc"),
MyFile("/Library/Application Support/JetBrains/IntelliJIdea2020.3/settings.zip", "settings.zip"),
MyFolder("/.ssh", ".ssh"),
)
val backupFolder = "backup"
val rootPath: String = System.getenv()["HOME"] ?: exitProcess(0)
fun createBackupFolder() {
File(backupFolder).mkdir()
}
fun copyFile(path: String, filename: String) {
try {
val file = ProcessBuilder("/bin/cp", "$rootPath$path", "./$backupFolder/$filename")
.redirectOutput(ProcessBuilder.Redirect.INHERIT)
.start()
.waitFor()
println("File process: $file")
} catch (e: Exception) {
println(e.localizedMessage)
}
}
fun copyFolder(path: String, foldername: String) {
try {
val folder = ProcessBuilder("/bin/cp", "-R", "$rootPath$path", "$backupFolder/$foldername")
.redirectOutput(ProcessBuilder.Redirect.INHERIT)
.start()
.waitFor()
println("Folder process: $folder")
} catch (e: Exception) {
println(e.localizedMessage)
}
}
fun copyFiles(files: List<ToKeep>) {
runBlocking {
val timeSpent = measureTimeMillis {
files.map { myFile: ToKeep ->
async(Dispatchers.IO) {
when (myFile) {
is MyFile -> copyFile(myFile.path, myFile.name)
is MyFolder -> copyFolder(myFile.path, myFile.name)
else -> exitProcess(1)
}
}
}.awaitAll()
}
println("Whole copy mapping takes $timeSpent ms")
}
}
// TODO: Choices => Restore or backup
// TODO: Check if backup exist and not empty
val timeSpent = measureTimeMillis {
createBackupFolder()
copyFiles(files)
}
println("Whole operation takes $timeSpent ms")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment