Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP - Delete inner directories first in deleteRecursive #588

Merged
merged 1 commit into from
May 7, 2023
Merged
Show file tree
Hide file tree
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
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