Skip to content
This repository has been archived by the owner on Apr 13, 2022. It is now read-only.

Improvements in FileUtils #366

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 11 additions & 28 deletions testkit/src/main/scala/scorex/testkit/utils/FileUtils.scala
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
package scorex.testkit.utils

import java.nio.file.Path
import java.nio.file.{Files, Path}

import scala.collection.JavaConverters._
import org.scalacheck.Gen

import scala.util.Try

trait FileUtils {

protected val randomPrefixLength = 10

val basePath: Path = java.nio.file.Files.createTempDirectory(s"scorex-${System.nanoTime()}")

sys.addShutdownHook {
remove(basePath)
}

def createTempFile: java.io.File = {
val dir = createTempDir
val prefix = scala.util.Random.alphanumeric.take(randomPrefixLength).mkString
val suffix = scala.util.Random.alphanumeric.take(randomPrefixLength).mkString
val file = java.nio.file.Files.createTempFile(dir.toPath, prefix, suffix).toFile
private def createTempDirForPrefix(prefix: String): java.io.File = {
val path = java.nio.file.Files.createTempDirectory(basePath, prefix)
sys.addShutdownHook {
remove(path)
}
val file = path.toFile
file.deleteOnExit()
file
}
Expand All @@ -37,24 +37,7 @@ trait FileUtils {
* Recursively remove all the files and directories in `root`
*/
def remove(root: Path): Unit = {

@SuppressWarnings(Array("org.wartremover.warts.Recursion"))
def deleteRecursive(dir: java.io.File): Unit = {
for (file <- dir.listFiles) {
if (file.isDirectory){
deleteRecursive(file)
}
file.delete()
}
}

deleteRecursive(root.toFile)
}

private def createTempDirForPrefix(prefix: String): java.io.File = {
val file = java.nio.file.Files.createTempDirectory(basePath, prefix).toFile
file.deleteOnExit()
file
Files.walk(root).iterator().asScala.toSeq.reverse.foreach(path => Try(Files.delete(path)))
}

}