AK: Implement a way to resolve relative paths lexically

This commit is contained in:
Ben Wiederhake 2021-09-11 12:55:07 +02:00 committed by Brian Gianforcaro
parent 24e7196158
commit 50ad294527
3 changed files with 22 additions and 0 deletions

View file

@ -121,6 +121,14 @@ String LexicalPath::canonicalized_path(String path)
return builder.to_string();
}
String LexicalPath::absolute_path(String dir_path, String target)
{
if (LexicalPath(target).is_absolute()) {
return LexicalPath::canonicalized_path(target);
}
return LexicalPath::canonicalized_path(join(dir_path, target).string());
}
String LexicalPath::relative_path(StringView const& a_path, StringView const& a_prefix)
{
if (!a_path.starts_with('/') || !a_prefix.starts_with('/')) {

View file

@ -33,6 +33,7 @@ public:
[[nodiscard]] LexicalPath parent() const;
[[nodiscard]] static String canonicalized_path(String);
[[nodiscard]] static String absolute_path(String dir_path, String target);
[[nodiscard]] static String relative_path(StringView const& absolute_path, StringView const& prefix);
template<typename... S>

View file

@ -128,6 +128,19 @@ TEST_CASE(trailing_slash)
EXPECT_EQ(path.parts_view().size(), 2u);
}
TEST_CASE(resolve_absolute_path)
{
EXPECT_EQ(LexicalPath::absolute_path("/home/anon", "foo.txt"), "/home/anon/foo.txt");
EXPECT_EQ(LexicalPath::absolute_path("/home/anon/", "foo.txt"), "/home/anon/foo.txt");
EXPECT_EQ(LexicalPath::absolute_path("/home/anon", "././foo.txt"), "/home/anon/foo.txt");
EXPECT_EQ(LexicalPath::absolute_path("/home/anon/quux", "../foo.txt"), "/home/anon/foo.txt");
EXPECT_EQ(LexicalPath::absolute_path("/home/anon/quux", "../test/foo.txt"), "/home/anon/test/foo.txt");
EXPECT_EQ(LexicalPath::absolute_path("quux", "../test/foo.txt"), "test/foo.txt");
EXPECT_EQ(LexicalPath::absolute_path("quux", "../../test/foo.txt"), "../test/foo.txt");
EXPECT_EQ(LexicalPath::absolute_path("quux/bar", "../../test/foo.txt"), "test/foo.txt");
EXPECT_EQ(LexicalPath::absolute_path("quux/bar/", "../../test/foo.txt"), "test/foo.txt");
}
TEST_CASE(has_extension)
{
{