Verify FSEntry name

This commit is contained in:
Gleb Koval 2024-01-05 17:45:35 +00:00
parent efc11deb6e
commit 18b9dac09d
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
2 changed files with 20 additions and 6 deletions

View File

@ -2,8 +2,10 @@ package filesystem
import java.nio.file.FileAlreadyExistsException import java.nio.file.FileAlreadyExistsException
import java.nio.file.FileSystemException import java.nio.file.FileSystemException
import java.nio.file.Files
import java.nio.file.Path import java.nio.file.Path
import kotlin.io.path.createDirectory
import kotlin.io.path.createFile
import kotlin.io.path.writeText
class FSCreator { class FSCreator {
/** /**
@ -22,13 +24,13 @@ class FSCreator {
val path = dest.resolve(entry.name) val path = dest.resolve(entry.name)
try { try {
when (entry) { when (entry) {
is FSFile -> Files.createFile(path) is FSFile -> path.createFile()
is FSFolder -> Files.createDirectory(path) is FSFolder -> path.createDirectory()
} }
} catch (_: FileAlreadyExistsException) { } catch (_: FileAlreadyExistsException) {
} // Allow files/folders to already exist. } // Allow files/folders to already exist.
when (entry) { when (entry) {
is FSFile -> Files.write(path, entry.content.toByteArray()) is FSFile -> path.writeText(entry.content)
is FSFolder -> queue.addAll(entry.entries.map { it to path }) is FSFolder -> queue.addAll(entry.entries.map { it to path })
} }
} }

View File

@ -1,9 +1,21 @@
package filesystem package filesystem
import kotlin.io.path.Path
// Note sealed allows for simpler logic in FSCreator by guaranteeing FSFile and FSFolder are the only possible FSEntries // Note sealed allows for simpler logic in FSCreator by guaranteeing FSFile and FSFolder are the only possible FSEntries
// (as we expect), and it also implicitly makes the class abstract as required. // (as we expect), and it also implicitly makes the class abstract as required.
sealed class FSEntry(val name: String) sealed class FSEntry(val name: String) {
init {
val p = Path(name)
// Only allow single filenames (no paths or relative references (e.g. ".."))
if (p.toList().size != 1 || p.fileName != p.toFile().canonicalFile.toPath().fileName) {
throw InvalidEntryNameException(name)
}
}
}
class FSFile(name: String, val content: String) : FSEntry(name) class FSFile(name: String, val content: String) : FSEntry(name)
class FSFolder(name: String, val entries: List<FSEntry>) : FSEntry(name) class FSFolder(name: String, val entries: List<FSEntry>) : FSEntry(name)
class InvalidEntryNameException(name: String) : Exception("Invalid FSEntry name: '$name'")