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

Commit

Permalink
#586 - Delete inner directories first in deleteRecursive (#588)
Browse files Browse the repository at this point in the history
  • Loading branch information
hbibel authored May 7, 2023
1 parent 2e00ffa commit 4e59536
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
9 changes: 8 additions & 1 deletion nio/src/main/scala/zio/nio/file/Files.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import java.nio.file.{
import java.util.function.BiPredicate
import scala.jdk.CollectionConverters._
import scala.reflect._
import zio.ZIOAspect

object Files {

Expand Down Expand Up @@ -134,7 +135,13 @@ object Files {
attemptBlocking(JFiles.deleteIfExists(path.javaPath)).refineToOrDie[IOException]

def deleteRecursive(path: Path)(implicit trace: Trace): ZIO[Any, IOException, Long] =
newDirectoryStream(path).mapZIO(delete).run(ZSink.count) <* delete(path)
newDirectoryStream(path).mapZIO { p =>
for {
deletedInSubDirectory <- deleteRecursive(p).whenZIO(isDirectory(p)).map(_.getOrElse(0L))
deletedFile <- deleteIfExists(p).map(if (_) 1 else 0)
} yield deletedInSubDirectory + deletedFile
}
.run(ZSink.sum) <* delete(path)

def copy(source: Path, target: Path, copyOptions: CopyOption*)(implicit
trace: Trace
Expand Down
11 changes: 11 additions & 0 deletions nio/src/test/scala/zio/nio/file/FilesSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,17 @@ object FilesSpec extends BaseSpec {
tmpFileExistsAfterUsage <- Files.exists(tmpFilePath)
} yield assert(readBytes)(equalTo(sampleFileContent)) &&
assert(tmpFileExistsAfterUsage)(isFalse)
},
test("deleteRecursive deletes subdirectories") {
for {
outerDir <- Files.createTempDirectory(prefix = None, fileAttributes = Nil)
innerDir = outerDir / "inner"
_ <- Files.createDirectory(innerDir)
innerDir <- Files.writeLines(innerDir / "file.txt", "test" :: Nil)
_ <- Files.deleteRecursive(outerDir)
isDeleted <- Files.notExists(outerDir)
} yield assertTrue(isDeleted)

}
)

Expand Down

0 comments on commit 4e59536

Please sign in to comment.