This repository has been archived on 2024-02-08. You can view files and clone it, but cannot push or open issues or pull requests.
2024-01-05 17:48:07 +00:00

38 lines
1.2 KiB
Kotlin

package filesystem
import java.nio.file.FileAlreadyExistsException
import java.nio.file.FileSystemException
import java.nio.file.Path
import kotlin.io.path.createDirectory
import kotlin.io.path.createFile
import kotlin.io.path.writeText
class FSCreator {
/**
* Create entry, leaving existing folders' contents, but overwriting existing files.
*/
@Throws(FileSystemException::class)
fun create(
entryToCreate: FSEntry,
destination: String,
) {
val queue = ArrayDeque<Pair<FSEntry, Path>>()
queue.add(entryToCreate to Path.of(destination))
while (queue.isNotEmpty()) {
val (entry, dest) = queue.removeFirst()
val path = dest.resolve(entry.name)
try {
when (entry) {
is FSFile -> path.createFile()
is FSFolder -> path.createDirectory()
}
} catch (_: FileAlreadyExistsException) {
} // Allow files/folders to already exist.
when (entry) {
is FSFile -> path.writeText(entry.content)
is FSFolder -> queue.addAll(entry.entries.map { it to path })
}
}
}
}