A potential point of failure would be the usage of mkdir
instead of mkdirs
, also some null-safety issues spotted for first and second file property accessors.
Therefore, I would refactor the following to:
import java.io.File
fun createCommitDirectory(
parentFile: File,
directoryIdHashName: String,
indexFile: File,
rootFile: File
) {
val directory = File("${parentFile}/${directoryIdHashName}")
.apply(File::mkdirs)
rootFile.canonicalFile.parentFile.listFiles()
?.first { it.name == indexFile.readLines().elementAt(0) }
?.copyTo(directory)
rootFile.canonicalFile.parentFile.listFiles()
?.first { it.name == indexFile.readLines().elementAt(2) }
?.copyTo(directory)
}
javadocs for mkdirs()
:
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
For the difference between mkdir()
and mkdirs()
, see: stackoverflow.com/a/9820115/5037430
Then, we could take this one more step, and add some error handling to the nullables:
import java.io.File
fun createCommitDirectory(
parentFile: File,
directoryIdHashName: String,
indexFile: File,
rootFile: File
) {
val directory = File("${parentFile}/${directoryIdHashName}")
.apply(File::mkdirs)
rootFile.canonicalFile.parentFile.listFiles()
?.first { it.name == indexFile.readLines().elementAt(0) }
?.copyTo(directory)
?: error("Could not find file at index: 0")
rootFile.canonicalFile.parentFile.listFiles()
?.first { it.name == indexFile.readLines().elementAt(2) }
?.copyTo(directory)
?: error("Could not find file at index: 2")
}
Error is a Kotlin built-in:
Error throws an IllegalStateException with the given message.
However, the error reporting above might not be good enough to figure out what is the problem, so we can introduce better error reporting by including the directory and indexed element when an exception is thrown:
import java.io.File
fun createCommitDirectory(
parentFile: File,
directoryIdHashName: String,
indexFile: File,
rootFile: File
) {
File("${parentFile}/${directoryIdHashName}")
.apply(File::mkdirs)
.let { directory ->
rootFile.canonicalFile.parentFile.listFiles()?.let { children ->
val indexFileLines = indexFile.readLines()
val indexedElement0 = indexFileLines.elementAt(0)
val indexedElement2 = indexFileLines.elementAt(2)
children
.first { it.name == indexedElement0 }
?.copyTo(directory)
?: errorReporter(indexedElement0, children)
children
.first { it.name == indexedElement2 }
?.copyTo(directory)
?: errorReporter(indexedElement2, children)
}
}
}
fun errorReporter(indexedElement0: String, children: Array<out File>) {
error("Indexed file name: $indexedElement0 did not match any file in the directory: ${children.toList()}")
}
Do note, without the actual error message, it would be hard to understand what is going on. However, try running the above and see if you can spot the error now.
Goodluck.