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

Implement path normalization #286

Draft
wants to merge 3 commits into
base: develop
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions core/api/kotlinx-io-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ public final class kotlinx/io/files/Path {
public final fun getParent ()Lkotlinx/io/files/Path;
public fun hashCode ()I
public final fun isAbsolute ()Z
public final fun normalized ()Lkotlinx/io/files/Path;
public fun toString ()Ljava/lang/String;
}

Expand Down
54 changes: 54 additions & 0 deletions core/common/src/files/Paths.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ public expect class Path {
*/
public val isAbsolute: Boolean

/**
* Returns normalized version of this path where all `..` and `.` segments are resolved
* and all sequential path separators are collapsed.
*/
public fun normalized(): Path

/**
* Returns a string representation of this path.
*
Expand Down Expand Up @@ -174,3 +180,51 @@ private fun removeTrailingSeparatorsWindows(suffixLength: Int, path: String): St
}
return path.substring(0, idx)
}

internal fun Path.normalizedInternal(preserveDrive: Boolean, vararg separators: Char): String {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It works incorrectly for UNC paths

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will fix it

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok!

var isAbs = isAbsolute
var stringRepresentation = toString()
var drive = ""
if (preserveDrive && stringRepresentation.length >= 2 && stringRepresentation[1] == ':') {
drive = stringRepresentation.substring(0, 2)
stringRepresentation = stringRepresentation.substring(2)
isAbs = stringRepresentation.isNotEmpty() && separators.contains(stringRepresentation.first())
}
val parts = stringRepresentation.split(*separators)
val constructedPath = mutableListOf<String>()
for (idx in parts.indices) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not for (part in parts)?

when (val part = parts[idx]) {
"." -> continue
".." -> if (isAbs) {
constructedPath.removeLastOrNull()
} else {
if (constructedPath.isEmpty() || constructedPath.last() == "..") {
constructedPath.add("..")
} else {
constructedPath.removeLast()
}
}

else -> {
if (part.isNotEmpty()) {
constructedPath.add(part)
}
}
}
}
return buildString {
append(drive)
var skipFirstSeparator = true
if (isAbs) {
append(SystemPathSeparator)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or skipFirstSeparator = false :)

}
for (segment in constructedPath) {
if (skipFirstSeparator) {
skipFirstSeparator = false
} else {
append(SystemPathSeparator)
}
append(segment)
}
}
}
13 changes: 13 additions & 0 deletions core/common/test/files/SmokeFileTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,19 @@ class SmokeFileTest {
source.close() // there should be no error
}

@Test
fun pathNormalize() {
assertEquals(Path(""), Path("").normalized())
assertEquals(Path("${SystemPathSeparator}a"), Path("/////////////a/").normalized())
assertEquals(Path("..", "..", "e"), Path("a/b/../c/../d/../../../../e").normalized())
assertEquals(Path("a"), Path("a/././././").normalized())

if (!isWindows) {
// On Windows, this path is usually considered relative
assertEquals(Path("${SystemPathSeparator}e"), Path("/a/b/../c/../d/../../../e").normalized())
}
}

private fun constructAbsolutePath(vararg parts: String): String {
return SystemPathSeparator.toString() + parts.joinToString(SystemPathSeparator.toString())
}
Expand Down
8 changes: 8 additions & 0 deletions core/common/test/files/SmokeFileTestWindows.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,12 @@ class SmokeFileTestWindows {
// this path could be transformed to use canonical separator on JVM
assertEquals(Path("//").toString(), Path("//").toString())
}

@Test
fun pathNormalize() {
if (!isWindows) return
assertEquals(Path("C:a", "b", "c", "d", "e"), Path("C:a/b\\\\\\//////c/d\\e").normalized())
assertEquals(Path("C:$SystemPathSeparator"), Path("C:\\..\\..\\..\\").normalized())
assertEquals(Path("C:..", "..", ".."), Path("C:..\\..\\..\\").normalized())
}
}
8 changes: 8 additions & 0 deletions core/common/test/files/UtilsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,12 @@ class UtilsTest {
assertEquals("C:\\", removeTrailingSeparatorsW("C:\\"))
assertEquals("C:\\", removeTrailingSeparatorsW("C:\\/\\"))
}

@Test
fun normalizePathWithDrive() {
assertEquals("C:$SystemPathSeparator",
Path("C:\\..\\..\\..\\").normalizedInternal(true, WindowsPathSeparator, UnixPathSeparator))
assertEquals("C:..$SystemPathSeparator..$SystemPathSeparator..",
Path("C:..\\..\\..\\").normalizedInternal(true, WindowsPathSeparator, UnixPathSeparator))
}
}
8 changes: 8 additions & 0 deletions core/jvm/src/files/PathsJvm.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ public actual class Path internal constructor(internal val file: File) {

public actual override fun toString(): String = file.toString()

// Don't use File.normalize here as it may work incorrectly for absolute paths:
// https://youtrack.jetbrains.com/issue/KT-48354
public actual fun normalized(): Path = Path(path = if (isWindows) {
normalizedInternal(true, WindowsPathSeparator, UnixPathSeparator)
} else {
normalizedInternal(false, UnixPathSeparator)
})

actual override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Path) return false
Expand Down
6 changes: 6 additions & 0 deletions core/native/src/files/PathsNative.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ public actual class Path internal constructor(
if (path.isEmpty() || path == SystemPathSeparator.toString()) return ""
return basenameImpl(path)
}

public actual fun normalized(): Path = Path(path = if (isWindows) {
normalizedInternal(true, WindowsPathSeparator, UnixPathSeparator)
} else {
normalizedInternal(false, UnixPathSeparator)
})
}

public actual val SystemPathSeparator: Char = UnixPathSeparator
Expand Down
6 changes: 6 additions & 0 deletions core/nodeFilesystemShared/src/files/PathsNodeJs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ public actual class Path internal constructor(
actual override fun hashCode(): Int {
return path.hashCode()
}

public actual fun normalized(): Path = Path(path = if (isWindows) {
normalizedInternal(true, WindowsPathSeparator, UnixPathSeparator)
} else {
normalizedInternal(false, UnixPathSeparator)
})
}

public actual val SystemPathSeparator: Char by lazy {
Expand Down
16 changes: 0 additions & 16 deletions core/wasmWasi/src/files/FileSystemWasm.kt
Original file line number Diff line number Diff line change
Expand Up @@ -272,22 +272,6 @@ internal object WasiFileSystem : SystemFileSystemImpl() {
}
}

private fun Path.normalized(): Path {
require(isAbsolute)

val parts = path.split(UnixPathSeparator)
val constructedPath = mutableListOf<String>()
// parts[0] is always empty
for (idx in 1 until parts.size) {
when (val part = parts[idx]) {
"." -> continue
".." -> constructedPath.removeLastOrNull()
else -> constructedPath.add(part)
}
}
return Path(UnixPathSeparator.toString(), *constructedPath.toTypedArray())
}

public actual open class FileNotFoundException actual constructor(
message: String?,
) : IOException(message)
Expand Down
2 changes: 2 additions & 0 deletions core/wasmWasi/src/files/PathsWasm.kt
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ public actual class Path internal constructor(rawPath: String, @Suppress("UNUSED
}

public actual val isAbsolute: Boolean = path.startsWith(SystemPathSeparator)

public actual fun normalized(): Path = Path(path = normalizedInternal(false, SystemPathSeparator))
}

// The path separator is always '/'.
Expand Down