Compare commits

..

2 Commits

Author SHA1 Message Date
e53d96a74b FSFolder.isCyclic() tests
All checks were successful
Test Workflow / Lint and test library (pull_request) Successful in 3m56s
2024-01-05 16:59:29 +00:00
4fa2ad53b0 Explicitly handle cyclic folders 2024-01-05 16:59:00 +00:00
4 changed files with 32 additions and 200 deletions

View File

@@ -1,36 +1,28 @@
package filesystem package filesystem
import java.nio.file.FileAlreadyExistsException import java.nio.file.FileAlreadyExistsException
import kotlin.io.path.Path import java.nio.file.Files
import kotlin.io.path.createDirectory import java.nio.file.Path
import kotlin.io.path.createFile
import kotlin.io.path.writeText
class FSCreator { class FSCreator {
/** /**
* Create entry, leaving existing folders' contents, but overwriting existing files. * Create entry, leaving existing folders' contents, but overwriting existing files.
* @throws CyclicFolderException Cyclic folders cannot be created. * @throws CyclicFolderException Cyclic folders cannot be created.
* @throws DuplicateEntryNameException A folder or sub-folder contains entries with duplicate names.
*/ */
@Throws(CyclicFolderException::class, DuplicateEntryNameException::class) @Throws(CyclicFolderException::class)
fun create( fun create(
entryToCreate: FSEntry, entryToCreate: FSEntry,
destination: String, destination: String,
) { ) {
// No point in running anything if we know the input is invalid. // No point in running anything if we know the input is invalid.
if (entryToCreate is FSFolder) { if (entryToCreate is FSFolder && entryToCreate.isCyclic()) {
if (entryToCreate.isCyclic()) {
throw CyclicFolderException() throw CyclicFolderException()
} }
if (entryToCreate.deepHasDuplicateNames()) {
throw DuplicateEntryNameException()
}
}
val queue = val queue =
ArrayDeque( ArrayDeque(
listOf( listOf(
entryToCreate to Path(destination), entryToCreate to Path.of(destination),
), ),
) )
@@ -39,13 +31,13 @@ class FSCreator {
val path = dest.resolve(entry.name) val path = dest.resolve(entry.name)
try { try {
when (entry) { when (entry) {
is FSFile -> path.createFile() is FSFile -> Files.createFile(path)
is FSFolder -> path.createDirectory() is FSFolder -> Files.createDirectory(path)
} }
} catch (_: FileAlreadyExistsException) { } catch (_: FileAlreadyExistsException) {
} // Allow files/folders to already exist. } // Allow files/folders to already exist.
when (entry) { when (entry) {
is FSFile -> path.writeText(entry.content) is FSFile -> Files.write(path, entry.content.toByteArray())
is FSFolder -> queue.addAll(entry.entries.map { it to path }) is FSFolder -> queue.addAll(entry.entries.map { it to path })
} }
} }
@@ -53,5 +45,3 @@ class FSCreator {
} }
class CyclicFolderException : Exception("Cyclic FSFolders are not supported") class CyclicFolderException : Exception("Cyclic FSFolders are not supported")
class DuplicateEntryNameException : Exception("Folder contains entries with duplicate names")

View File

@@ -1,18 +1,8 @@
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)
@@ -34,26 +24,4 @@ class FSFolder(name: String, val entries: List<FSEntry>) : FSEntry(name) {
} }
return false return false
} }
/**
* Check whether a folder contains multiple entries with the same name.
*/
fun hasDuplicateNames(): Boolean {
val seen = HashSet<String>()
return entries.any { !seen.add(it.name) }
}
internal fun deepHasDuplicateNames(): Boolean {
val queue = ArrayDeque(listOf(this))
while (queue.isNotEmpty()) {
val entry = queue.removeFirst()
if (entry.hasDuplicateNames()) {
return true
}
queue.addAll(entry.entries.mapNotNull { it as? FSFolder })
}
return false
}
} }
class InvalidEntryNameException(name: String) : Exception("Invalid FSEntry name: '$name'")

View File

@@ -1,10 +1,9 @@
package filesystem package filesystem
import org.junit.jupiter.api.* import org.junit.jupiter.api.*
import java.io.File import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import kotlin.io.path.Path
import kotlin.io.path.createDirectory
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertEquals import kotlin.test.assertEquals
@@ -14,26 +13,17 @@ class FSCreatorTest {
@BeforeEach @BeforeEach
fun `before each`() { fun `before each`() {
assertDoesNotThrow("should create _tmp directory") { assertDoesNotThrow("should create _tmp directory") {
Path("_tmp").createDirectory() Files.createDirectory(Path.of("_tmp"))
} }
} }
@AfterEach @AfterEach
fun `after each`() { fun `after each`() {
assertDoesNotThrow("should delete _tmp directory") { assertDoesNotThrow("should delete _tmp directory") {
File("_tmp").deleteRecursively() deleteRecursive(Path.of("_tmp"))
} }
} }
@Test
fun `create file`() {
val file = FSFile("test.txt", "This is a file")
assertDoesNotThrow("should create file") {
creator.create(file, "_tmp")
}
assertEquals(file.content, File("_tmp/", file.name).readText())
}
@Test @Test
fun `create entries`() { fun `create entries`() {
val readme = FSFile("README", "Hello World!") val readme = FSFile("README", "Hello World!")
@@ -71,10 +61,10 @@ class FSCreatorTest {
} }
// If objects don't exist, these functions will throw anyway, so don't explicitly check for existence. // If objects don't exist, these functions will throw anyway, so don't explicitly check for existence.
// Similarly, don't explicitly check if an object is a directory. // Similarly, don't explicitly check if an object is a directory.
assertEquals(readme.content, File("_tmp/folder", readme.name).readText()) assertEquals(readme.content, Files.readString(Path.of("_tmp/folder", readme.name)))
assertEquals(gomod.content, File("_tmp/folder", gomod.name).readText()) assertEquals(gomod.content, Files.readString(Path.of("_tmp/folder", gomod.name)))
assertEquals(maingo.content, File("_tmp/folder", maingo.name).readText()) assertEquals(maingo.content, Files.readString(Path.of("_tmp/folder", maingo.name)))
assertEquals(helloworldgo.content, File("_tmp/folder/utils", helloworldgo.name).readText()) assertEquals(helloworldgo.content, Files.readString(Path.of("_tmp/folder/utils", helloworldgo.name)))
} }
@Test @Test
@@ -104,7 +94,6 @@ class FSCreatorTest {
"folder", "folder",
listOf( listOf(
FSFolder( FSFolder(
// Repeated name should be fine here (not throw)
"folder", "folder",
listOf( listOf(
FSFolder( FSFolder(
@@ -122,11 +111,11 @@ class FSCreatorTest {
"_tmp", "_tmp",
) )
} }
assertEquals("hi", File("_tmp/folder/sub-folder/hi").readText()) assertEquals("hi", Files.readString(Path.of("_tmp/folder/sub-folder/hi")))
assertEquals("P4ssW0rd", File("_tmp/folder/folder/secrets/secret").readText()) assertEquals("P4ssW0rd", Files.readString(Path.of("_tmp/folder/folder/secrets/secret")))
assertEquals("One is a good number", File("_tmp/folder/1.txt").readText()) assertEquals("One is a good number", Files.readString(Path.of("_tmp/folder/1.txt")))
assertEquals("Two!", File("_tmp/folder/2.txt").readText()) assertEquals("Two!", Files.readString(Path.of("_tmp/folder/2.txt")))
assertEquals("Three!", File("_tmp/folder/3.txt").readText()) assertEquals("Three!", Files.readString(Path.of("_tmp/folder/3.txt")))
} }
@Test @Test
@@ -153,34 +142,13 @@ class FSCreatorTest {
creator.create(folder4, "_tmp") creator.create(folder4, "_tmp")
} }
} }
}
@Test
fun `create throws on folder with duplicate names`() { fun deleteRecursive(path: Path) {
val folder = if (Files.isDirectory(path)) {
FSFolder( for (child in Files.list(path)) {
"folder", deleteRecursive(child)
listOf( }
FSFile("README.md", "# Test File"), }
FSFile("hello-world.txt", "Hello World!"), Files.delete(path)
FSFolder(
"src",
listOf(
FSFile("README.md", "# Source files"),
FSFolder(
"solution",
listOf(
FSFile("solution.py", "print('1 + 1 = 1')"),
FSFile("tmp", "A temporary file"),
FSFolder("tmp", listOf()),
),
),
),
),
FSFolder("tmp", listOf()),
),
)
assertThrows<DuplicateEntryNameException> {
creator.create(folder, "_tmp")
}
}
} }

View File

@@ -1,34 +1,10 @@
package filesystem package filesystem
import org.junit.jupiter.api.* import org.junit.jupiter.api.Test
import kotlin.test.assertFalse import kotlin.test.assertFalse
import kotlin.test.assertTrue import kotlin.test.assertTrue
class FSEntryTest { class FSEntryTest {
@Test
fun `valid name entries`() {
assertDoesNotThrow("should construct FSFile and FSFolder without throwing") {
FSFile("A file with a name.tar.xz", "Contents")
FSFolder(".a folder with a name", listOf())
}
}
@Test
fun `invalid name entries`() {
assertThrows<InvalidEntryNameException> {
FSFile("File/here", "Contents")
}
assertThrows<InvalidEntryNameException> {
FSFolder("Folder/here", listOf())
}
assertThrows<InvalidEntryNameException> {
FSFolder(".", listOf())
}
assertThrows<InvalidEntryNameException> {
FSFolder("/", listOf())
}
}
@Test @Test
fun `non-cyclic folder`() { fun `non-cyclic folder`() {
val folder = val folder =
@@ -63,74 +39,4 @@ class FSEntryTest {
assertTrue(folder3.isCyclic()) assertTrue(folder3.isCyclic())
assertTrue(folder4.isCyclic()) assertTrue(folder4.isCyclic())
} }
@Test
fun `no duplicate names folder`() {
val folder =
FSFolder(
"folder",
listOf(
FSFile("README.md", "# Test File"),
FSFile("hello-world.txt", "Hello World!"),
FSFolder(
"src",
listOf(
FSFile("README.md", "# Source files"),
FSFile("solution-1.py", "print('1 + 1 = 1')"),
FSFile("solution-2.py", "print('1 + 1 = 1')"),
),
),
FSFolder("tmp", listOf()),
),
)
assertFalse(folder.hasDuplicateNames())
assertFalse(folder.deepHasDuplicateNames())
}
@Test
fun `shallow duplicate names folder`() {
val folder =
FSFolder(
"folder",
listOf(
FSFile("README.md", "# Test File"),
FSFile("hello-world.txt", "Hello World!"),
FSFolder(
"src",
listOf(
FSFile("README.md", "# Source files"),
FSFile("solution-1.py", "print('1 + 1 = 1')"),
FSFile("solution-2.py", "print('1 + 1 = 1')"),
),
),
FSFolder("tmp", listOf()),
FSFile("tmp", "A temporary file"),
),
)
assertTrue(folder.hasDuplicateNames())
assertTrue(folder.deepHasDuplicateNames())
}
@Test
fun `deep duplicate names folder`() {
val folder =
FSFolder(
"folder",
listOf(
FSFile("README.md", "# Test File"),
FSFile("hello-world.txt", "Hello World!"),
FSFolder(
"src",
listOf(
FSFile("README.md", "# Source files"),
FSFile("solution-1.py", "print('1 + 1 = 1')"),
FSFile("solution-1.py", "print('1 + 1 = 1')"),
),
),
FSFolder("tmp", listOf()),
),
)
assertFalse(folder.hasDuplicateNames())
assertTrue(folder.deepHasDuplicateNames())
}
} }