KT-57298 createParentDirectories: handle already existing directory symlink

This commit is contained in:
Ilya Gorbunov
2023-03-27 05:29:14 +02:00
committed by Space Team
parent 912b65060e
commit f8d001c21f
2 changed files with 20 additions and 2 deletions
@@ -562,8 +562,16 @@ public inline fun Path.createDirectories(vararg attributes: FileAttribute<*>): P
*/ */
@SinceKotlin("1.9") @SinceKotlin("1.9")
@Throws(IOException::class) @Throws(IOException::class)
public fun Path.createParentDirectories(vararg attributes: FileAttribute<*>): Path = public fun Path.createParentDirectories(vararg attributes: FileAttribute<*>): Path = also {
this.apply { parent?.createDirectories(*attributes) } val parent = it.parent
if (parent != null && !parent.isDirectory()) {
try {
parent.createDirectories(*attributes)
} catch (e: FileAlreadyExistsException) {
if (!parent.isDirectory()) throw e
}
}
}
/** /**
* Moves or renames the file located by this path to the [target] path. * Moves or renames the file located by this path to the [target] path.
@@ -98,6 +98,16 @@ class PathExtensionsTest : AbstractPathTest() {
} }
} }
@Test
fun createParentDirectoriesOverExistingSymlink() {
val root = createTempDirectory("createParent-root").cleanupRecursively()
val dir = (root / "dir").createDirectory()
val link = (root / "link").tryCreateSymbolicLinkTo(dir) ?: return
val file = (link / "file")
file.createParentDirectories().writeText("txt")
assertTrue((dir / "file").isRegularFile())
}
@Test @Test
fun createTempFileDefaultDir() { fun createTempFileDefaultDir() {
val file1 = createTempFile().cleanup() val file1 = createTempFile().cleanup()