From 351ed857f4484abd3b10cf4f7c2422bb182c574f Mon Sep 17 00:00:00 2001 From: Asher Date: Fri, 12 Jul 2024 13:38:48 -0800 Subject: [PATCH] Expand ~/ on Windows --- src/main/kotlin/com/coder/gateway/util/PathExtensions.kt | 9 ++++++--- .../kotlin/com/coder/gateway/util/PathExtensionsTest.kt | 7 +++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/kotlin/com/coder/gateway/util/PathExtensions.kt b/src/main/kotlin/com/coder/gateway/util/PathExtensions.kt index 72298aab..bd3f186e 100644 --- a/src/main/kotlin/com/coder/gateway/util/PathExtensions.kt +++ b/src/main/kotlin/com/coder/gateway/util/PathExtensions.kt @@ -31,13 +31,16 @@ fun expand(path: String): String { if (path == "~" || path == "\$HOME" || path == "\${user.home}") { return System.getProperty("user.home") } - if (path.startsWith("~" + File.separator)) { + // On Windows also allow /. Windows seems to work fine with mixed slashes + // like c:\users\coder/my/path/here. + val os = getOS() + if (path.startsWith("~" + File.separator) || (os == OS.WINDOWS && path.startsWith("~/"))) { return Path.of(System.getProperty("user.home"), path.substring(1)).toString() } - if (path.startsWith("\$HOME" + File.separator)) { + if (path.startsWith("\$HOME" + File.separator) || (os == OS.WINDOWS && path.startsWith("\$HOME/"))) { return Path.of(System.getProperty("user.home"), path.substring(5)).toString() } - if (path.startsWith("\${user.home}" + File.separator)) { + if (path.startsWith("\${user.home}" + File.separator) || (os == OS.WINDOWS && path.startsWith("\${user.home}/"))) { return Path.of(System.getProperty("user.home"), path.substring(12)).toString() } return path diff --git a/src/test/kotlin/com/coder/gateway/util/PathExtensionsTest.kt b/src/test/kotlin/com/coder/gateway/util/PathExtensionsTest.kt index 3252f238..85c74406 100644 --- a/src/test/kotlin/com/coder/gateway/util/PathExtensionsTest.kt +++ b/src/test/kotlin/com/coder/gateway/util/PathExtensionsTest.kt @@ -108,7 +108,14 @@ internal class PathExtensionsTest { // Do not replace if part of a larger string. assertEquals(home, expand(it)) assertEquals(home, expand(it + File.separator)) + if (isWindows) { + assertEquals(home, expand(it + "/")) + } else { + assertEquals(it + "\\", expand(it + "\\")) + } assertEquals(it + "hello", expand(it + "hello")) + assertEquals(it + "hello/foo", expand(it + "hello/foo")) + assertEquals(it + "hello\\foo", expand(it + "hello\\foo")) } } }