AK: Update LexicalPath::relative_path to work for '/' prefix

If the prefix path is just a slash the LexicalPath was removing too many
characters. Now only remove an extra character if the prefix is not just
the root path.
This commit is contained in:
Tim Waterhouse 2021-04-03 15:48:26 -07:00 committed by Andreas Kling
parent 83d2c3f2f5
commit 4d81d868c7
Notes: sideshowbarker 2024-07-18 20:30:35 +09:00
2 changed files with 14 additions and 1 deletions

View file

@ -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 {};

View file

@ -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)