From 93ce43340730111df977921e62cae93c2bcc4a5b Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 28 Dec 2017 20:27:28 +0300 Subject: [backport] Add uri.relativeTo Original: cca63f7 --- core/src/main/kotlin/Utilities/Uri.kt | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 core/src/main/kotlin/Utilities/Uri.kt (limited to 'core/src/main/kotlin/Utilities/Uri.kt') diff --git a/core/src/main/kotlin/Utilities/Uri.kt b/core/src/main/kotlin/Utilities/Uri.kt new file mode 100644 index 00000000..5b520188 --- /dev/null +++ b/core/src/main/kotlin/Utilities/Uri.kt @@ -0,0 +1,40 @@ +package org.jetbrains.dokka + +import java.net.URI + + +fun URI.relativeTo(uri: URI): URI { + // Normalize paths to remove . and .. segments + val base = uri.normalize() + val child = this.normalize() + + fun StringBuilder.appendRelativePath() { + // Split paths into segments + var bParts = base.path.split('/').dropLastWhile { it.isEmpty() } + val cParts = child.path.split('/').dropLastWhile { it.isEmpty() } + + // Discard trailing segment of base path + if (bParts.isNotEmpty() && !base.path.endsWith("/")) { + bParts = bParts.dropLast(1) + } + + // Compute common prefix + val commonPartsSize = bParts.zip(cParts).count { (basePart, childPart) -> basePart == childPart } + bParts.drop(commonPartsSize).joinTo(this, separator = "") { "../" } + cParts.drop(commonPartsSize).joinTo(this, separator = "/") + } + + return URI.create(buildString { + if (base.path != child.path) { + appendRelativePath() + } + child.rawQuery?.let { + append("?") + append(it) + } + child.rawFragment?.let { + append("#") + append(it) + } + }) +} \ No newline at end of file -- cgit From 6361dd32aaf567c8e03e4aa63006193dc67cca7b Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 5 May 2018 01:54:31 +0300 Subject: Fix relative uri's generation when there is matching trailing segments --- core/src/main/kotlin/Utilities/Uri.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'core/src/main/kotlin/Utilities/Uri.kt') diff --git a/core/src/main/kotlin/Utilities/Uri.kt b/core/src/main/kotlin/Utilities/Uri.kt index 5b520188..9827c624 100644 --- a/core/src/main/kotlin/Utilities/Uri.kt +++ b/core/src/main/kotlin/Utilities/Uri.kt @@ -19,7 +19,7 @@ fun URI.relativeTo(uri: URI): URI { } // Compute common prefix - val commonPartsSize = bParts.zip(cParts).count { (basePart, childPart) -> basePart == childPart } + val commonPartsSize = bParts.zip(cParts).takeWhile { (basePart, childPart) -> basePart == childPart }.count() bParts.drop(commonPartsSize).joinTo(this, separator = "") { "../" } cParts.drop(commonPartsSize).joinTo(this, separator = "/") } -- cgit