Skip to content

Instantly share code, notes, and snippets.

@cy6erGn0m
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cy6erGn0m/05a77be9cf901b9f5fe5 to your computer and use it in GitHub Desktop.
Save cy6erGn0m/05a77be9cf901b9f5fe5 to your computer and use it in GitHub Desktop.
Naive file sync implementation in Kotlin
fun sync(from: File, to: File, detectChange: (File, File) -> Boolean, filePredicate : (File) -> Boolean = {true}) {
require(from.isDirectory)
require(to.isDirectory)
from.walkTopDown()
.filter { it.isDirectory || filePredicate(it) }
.asSequence()
.forEach { file ->
val relative = file.relativeTo(from)
val destFile = File(to, relative)
if (file.isDirectory) {
if (destFile.isFile) {
destFile.delete()
}
destFile.mkdirsOrFail()
} else if (destFile.isDirectory) {
destFile.deleteRecursively()
}
if (file.isFile && (!destFile.exists() || detectChange(file, destFile))) {
file.copyTo(destFile, true)
}
}
to.walkTopDown()
.filter { it.isDirectory || filePredicate(it) }
.asSequence()
.forEach { file ->
val relative = file.relativeTo(to)
val fromFile = File(from, relative)
if (!fromFile.exists()) {
file.deleteRecursively()
}
}
}
private fun File.mkdirsOrFail() {
if (!mkdirs() && !exists()) {
throw IOException("Failed to create directory $this")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment