diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2024-09-25 22:16:26 +0200 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2024-09-25 22:16:26 +0200 |
| commit | f03c738a9e39053ad185084bf83bf6e526011b71 (patch) | |
| tree | 86baa67bb76e7e7f2f12a41afd8ddc8ea3506164 /libs/utils/src/main | |
| parent | 2d8949a0d9333bfda2385e3eab124581704286bf (diff) | |
samba & sftp: Share path utils methods
Add tests for them, and add basename, currently unused, for completeness
Diffstat (limited to 'libs/utils/src/main')
| -rw-r--r-- | libs/utils/src/main/java/org/the_jk/cleversync/PathUtils.kt | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/libs/utils/src/main/java/org/the_jk/cleversync/PathUtils.kt b/libs/utils/src/main/java/org/the_jk/cleversync/PathUtils.kt new file mode 100644 index 0000000..4202b24 --- /dev/null +++ b/libs/utils/src/main/java/org/the_jk/cleversync/PathUtils.kt @@ -0,0 +1,49 @@ +package org.the_jk.cleversync + +object PathUtils { + fun dirname(path: String): String { + if (path.isEmpty()) return "." + var start = path.lastIndex + while (start > -1 && path[start] == '/') start-- + if (start == -1) return "/" + val index = path.lastIndexOf('/', startIndex = start) + if (index == 0) return "/" + if (index > -1) return path.substring(0, index) + return "." + } + + fun basename(path: String): String { + if (path.isEmpty()) return "" + var start = path.lastIndex + while (start > -1 && path[start] == '/') start-- + if (start == -1) return "/" + val index = path.lastIndexOf('/', startIndex = start) + return path.substring(index + 1, start + 1) + } + + fun join(path1: String, path2: String): String { + if (path1.isEmpty() || path2.startsWith("/")) return path2 + if (path2.isEmpty()) return path1 + return if (path1.endsWith("/")) path1 + path2 else "${path1}/${path2}" + } + + fun resolve(path: String): String { + if (path.isEmpty()) return "" + val prefixed = path.startsWith("/") + val parts = path.split('/').filter { part -> + part.isNotEmpty() && part != "." + }.toMutableList() + var i = 0 + while (i < parts.size) { + if (parts[i] == "..") { + parts.removeAt(i) + if (i > 0) { + parts.removeAt(i - 1) + } + } else { + i++ + } + } + return parts.joinToString("/", prefix = if (prefixed) "/" else "") + } +} |
