Skip to content

Commit a086319

Browse files
committed
Improve move docs and add tests
1 parent 5dd47e1 commit a086319

File tree

3 files changed

+37
-5
lines changed

3 files changed

+37
-5
lines changed

core/common/src/files/FileSystem.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ public sealed interface FileSystem {
6262
* Atomically renames [source] to [destination] overriding [destination] if it already exists.
6363
*
6464
* When the filesystem does not support atomic move of [source] and [destination] corresponds to different
65-
* filesystems and the operation could not be performed atomically,
65+
* filesystems (or different volumes, on Windows) and the operation could not be performed atomically,
6666
* [UnsupportedOperationException] is thrown.
6767
*
6868
* @param source the path to rename.

core/common/test/files/SmokeFileTest.kt

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,33 @@ class SmokeFileTest {
107107
}
108108
}
109109

110+
@OptIn(ExperimentalStdlibApi::class)
111+
@Test
112+
fun atomicMoveDir() {
113+
val src = createTempPath()
114+
val dst = createTempPath()
115+
FileSystem.System.createDirectories(src)
116+
117+
FileSystem.System.atomicMove(src, dst)
118+
assertFalse(FileSystem.System.exists(src))
119+
assertTrue(FileSystem.System.exists(dst))
120+
121+
val src2 = createTempPath()
122+
FileSystem.System.createDirectories(src2)
123+
FileSystem.System.atomicMove(src2, dst)
124+
assertFalse(FileSystem.System.exists(src2))
125+
126+
val src3 = createTempPath()
127+
FileSystem.System.sink(src3).buffered().use { it.writeString("hehe") }
128+
assertFailsWith<IOException> { FileSystem.System.atomicMove(src3, dst) }
129+
130+
val dstFile = createTempPath()
131+
FileSystem.System.sink(dstFile).buffered().use { it.writeString("hehe") }
132+
val srcDir = createTempPath()
133+
FileSystem.System.createDirectories(srcDir)
134+
assertFailsWith<IOException> { FileSystem.System.atomicMove(srcDir, dstFile) }
135+
}
136+
110137
@Test
111138
fun deleteFile() {
112139
val p = createTempPath()

core/jvm/src/files/FileSystemJvm.kt

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,15 @@ private class NioMover : Mover {
2323
if (!source.file.exists()) {
2424
throw FileNotFoundException("Source file does not exist: ${source.file}")
2525
}
26-
Files.move(
27-
source.file.toPath(), destination.file.toPath(),
28-
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING
29-
)
26+
try {
27+
Files.move(
28+
source.file.toPath(), destination.file.toPath(),
29+
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING
30+
)
31+
} catch (e: Throwable) {
32+
if (e is IOException) throw e
33+
throw IOException("Move failed", e)
34+
}
3035
}
3136
}
3237

0 commit comments

Comments
 (0)