Skip to content

Commit 460f8e8

Browse files
authored
Make os.remove behave more like Files.deleteIfExists, add checkExists flag to fall back to old behavior #89
Follow up from the discussion in #86. As discussed, we hope that it would be more intuitive to avoid failing loudly if a file we want to delete already doesn't exist. If the user cares, they can always check the returned `Boolean`, or pass `checkExists = true` if they want the exception CC @iulian-db Review by @lefou @sake92
1 parent a603803 commit 460f8e8

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

os/src/FileOps.scala

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -280,8 +280,16 @@ object copy {
280280
* any files or folders in the target path, or
281281
* does nothing if there aren't any
282282
*/
283-
object remove extends Function1[Path, Unit]{
284-
def apply(target: Path): Unit = Files.delete(target.wrapped)
283+
object remove extends Function1[Path, Boolean]{
284+
def apply(target: Path): Boolean = apply(target, false)
285+
def apply(target: Path, checkExists: Boolean = false): Boolean = {
286+
if (checkExists) {
287+
Files.delete(target.wrapped)
288+
true
289+
}else{
290+
Files.deleteIfExists(target.wrapped)
291+
}
292+
}
285293

286294
object all extends Function1[Path, Unit]{
287295
def apply(target: Path) = {
@@ -290,7 +298,7 @@ object remove extends Function1[Path, Unit]{
290298
val nioTarget = target.wrapped
291299
if (Files.exists(nioTarget, LinkOption.NOFOLLOW_LINKS)) {
292300
if (Files.isDirectory(nioTarget, LinkOption.NOFOLLOW_LINKS)) {
293-
walk.stream(target, preOrder = false).foreach(remove)
301+
walk.stream(target, preOrder = false).foreach(remove(_))
294302
}
295303
Files.delete(nioTarget)
296304
}

os/test/src/OpTests.scala

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,12 @@ object OpTests extends TestSuite{
2727
test("rm"){
2828
// shouldn't crash
2929
os.remove.all(os.pwd/"out"/"scratch"/"nonexistent")
30+
// shouldn't crash
31+
os.remove(os.pwd/"out"/"scratch"/"nonexistent") ==> false
32+
3033
// should crash
3134
intercept[NoSuchFileException]{
32-
os.remove(os.pwd/"out"/"scratch"/"nonexistent")
35+
os.remove(os.pwd/"out"/"scratch"/"nonexistent", checkExists = true)
3336
}
3437
}
3538
}

0 commit comments

Comments
 (0)