summaryrefslogtreecommitdiff
path: root/src/jsMain/kotlin/io/Path.kt
diff options
context:
space:
mode:
authorromangraef <romangraef@users.noreply.github.com>2021-08-12 23:37:33 +0000
committerromangraef <romangraef@users.noreply.github.com>2021-08-12 23:37:33 +0000
commitbb618136911c338a926496dfb6971aa86f7d87c2 (patch)
treea57c587eca5bde9ea02996a002d9eaf3c269a3cb /src/jsMain/kotlin/io/Path.kt
parent09dbaa8df9aec51cf41694266574ad330963dfbe (diff)
downloadwebos-bb618136911c338a926496dfb6971aa86f7d87c2.tar.gz
webos-bb618136911c338a926496dfb6971aa86f7d87c2.tar.bz2
webos-bb618136911c338a926496dfb6971aa86f7d87c2.zip
Automated deployment: Thu Aug 12 23:37:33 UTC 2021 b6187f47b9e969ce311de73de1c6b32d970fd69f
Diffstat (limited to 'src/jsMain/kotlin/io/Path.kt')
-rw-r--r--src/jsMain/kotlin/io/Path.kt75
1 files changed, 75 insertions, 0 deletions
diff --git a/src/jsMain/kotlin/io/Path.kt b/src/jsMain/kotlin/io/Path.kt
new file mode 100644
index 0000000..8f77203
--- /dev/null
+++ b/src/jsMain/kotlin/io/Path.kt
@@ -0,0 +1,75 @@
+package io
+
+sealed interface Path {
+ val parts: List<String>
+ fun toAbsolutePath(relativeTo: Absolute): Absolute {
+ return relativeTo.resolve(this)
+ }
+
+ fun resolve(path: Path): Path
+
+ companion object {
+ val root = Absolute(listOf())
+
+ fun ofShell(string: String, userHome: Absolute): Path =
+ ofShell(string.split("/"), userHome)
+
+ fun ofShell(vararg parts: String, userHome: Absolute): Path =
+ ofShell(parts.toList(), userHome)
+
+ fun of(vararg parts: String): Path =
+ of(parts.toList())
+
+ fun of(string: String): Path =
+ of(string.split("/"))
+
+ fun ofShell(parts: List<String>, userHome: Absolute): Path {
+ if (parts.firstOrNull() == "~")
+ return userHome.resolve(Relative(parts.subList(1, parts.size).filter { it.isNotEmpty() }))
+ return of(parts)
+ }
+
+ fun of(parts: List<String>): Path {
+ if (parts.isEmpty())
+ return root
+ if (parts[0] == "") // Starts with a /
+ return Absolute(parts.subList(1, parts.size).filter { it.isNotEmpty() })
+ return Relative(parts.filter { it.isNotEmpty() })
+ }
+ }
+
+ data class Relative internal constructor(override val parts: List<String>) : Path {
+ override fun resolve(path: Path): Path {
+ if (path is Absolute) return path
+ return Relative(this.parts + path.parts)
+ }
+ }
+
+ data class Absolute internal constructor(override val parts: List<String>) : Path {
+ override fun resolve(path: Path): Absolute {
+ if (path is Absolute) return path
+ return Absolute(this.parts + path.parts)
+ }
+
+ fun relativize(path: Path): Relative = when (path) {
+ is Relative -> path
+ is Absolute -> {
+ var commonPrefix = true
+ val partList = mutableListOf<String>()
+ var returns = 0
+ for ((idx, part) in path.parts.withIndex()) {
+ if (idx < this.parts.size) {
+ if (this.parts[idx] == part && commonPrefix) {
+ continue
+ } else {
+ commonPrefix = false
+ returns++
+ }
+ }
+ partList.add(part)
+ }
+ Relative(List(returns) { "" } + partList)
+ }
+ }
+ }
+}