Last active
August 29, 2015 14:26
-
-
Save cy6erGn0m/05a77be9cf901b9f5fe5 to your computer and use it in GitHub Desktop.
Naive file sync implementation in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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