diff --git a/AK/LexicalPath.cpp b/AK/LexicalPath.cpp index cbe28d31de..7fbe01482f 100644 --- a/AK/LexicalPath.cpp +++ b/AK/LexicalPath.cpp @@ -127,7 +127,9 @@ String LexicalPath::relative_path(const String absolute_path, const String& pref if (!absolute_path.starts_with(prefix)) return absolute_path; - size_t prefix_length = LexicalPath { prefix }.string().length() + 1; + size_t prefix_length = LexicalPath { prefix }.string().length(); + if (prefix != "/") + prefix_length++; if (prefix_length >= absolute_path.length()) return {}; diff --git a/AK/Tests/TestLexicalPath.cpp b/AK/Tests/TestLexicalPath.cpp index 4d4a431af9..77f102b7c7 100644 --- a/AK/Tests/TestLexicalPath.cpp +++ b/AK/Tests/TestLexicalPath.cpp @@ -84,4 +84,15 @@ TEST_CASE(has_extension) } } +TEST_CASE(relative_path) +{ + EXPECT_EQ(LexicalPath::relative_path("/tmp/abc.txt", "/tmp"), "abc.txt"); + EXPECT_EQ(LexicalPath::relative_path("/tmp/abc.txt", "/tmp/"), "abc.txt"); + EXPECT_EQ(LexicalPath::relative_path("/tmp/abc.txt", "/"), "tmp/abc.txt"); + EXPECT_EQ(LexicalPath::relative_path("/tmp/abc.txt", "/usr"), "/tmp/abc.txt"); + + EXPECT_EQ(LexicalPath::relative_path("/tmp/foo.txt", "tmp"), String {}); + EXPECT_EQ(LexicalPath::relative_path("tmp/foo.txt", "/tmp"), String {}); +} + TEST_MAIN(LexicalPath)