Skip to content

Commit

Permalink
AK: Make FileSystemPath better at handling relative paths
Browse files Browse the repository at this point in the history
Relative paths now canonicalize into a string starting with "./"
Previously, "foo" would be canonicalized as "/foo" which was clearly
not right.
  • Loading branch information
awesomekling committed Aug 23, 2019
1 parent b1bc7a1 commit 56eaf9b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 6 deletions.
27 changes: 21 additions & 6 deletions AK/FileSystemPath.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,26 @@ FileSystemPath::FileSystemPath(const StringView& s)

void FileSystemPath::canonicalize()
{
if (m_string.is_empty()) {
m_parts.clear();
return;
}

bool is_absolute_path = m_string[0] == '/';
auto parts = m_string.split_view('/');

if (!is_absolute_path)
parts.prepend(".");

int approximate_canonical_length = 0;
Vector<String> canonical_parts;

for (auto& part : parts) {
if (part == ".")
continue;
for (int i = 0; i < parts.size(); ++i) {
auto& part = parts[i];
if (is_absolute_path || i != 0) {
if (part == ".")
continue;
}
if (part == "..") {
if (!canonical_parts.is_empty())
canonical_parts.take_last();
Expand All @@ -43,9 +56,11 @@ void FileSystemPath::canonicalize()
m_extension = name_parts[1];

StringBuilder builder(approximate_canonical_length);
for (auto& cpart : canonical_parts) {
builder.append('/');
builder.append(cpart);
for (int i = 0; i < canonical_parts.size(); ++i) {
auto& canonical_part = canonical_parts[i];
if (is_absolute_path || i != 0)
builder.append('/');
builder.append(canonical_part);
}
m_parts = move(canonical_parts);
m_string = builder.to_string();
Expand Down
33 changes: 33 additions & 0 deletions AK/Tests/TestFileSystemPath.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,37 @@ TEST_CASE(dotdot_coalescing)
EXPECT_EQ(FileSystemPath("/../../../../").string(), "/");
}

TEST_CASE(relative_paths)
{
{
FileSystemPath path("simple");
EXPECT_EQ(path.is_valid(), true);
EXPECT_EQ(path.string(), "./simple");
EXPECT_EQ(path.parts().size(), 2);
EXPECT_EQ(path.basename(), "simple");
}
{
FileSystemPath path("a/relative/path");
EXPECT_EQ(path.is_valid(), true);
EXPECT_EQ(path.string(), "./a/relative/path");
EXPECT_EQ(path.parts().size(), 4);
EXPECT_EQ(path.basename(), "path");
}
{
FileSystemPath path("./././foo");
EXPECT_EQ(path.is_valid(), true);
EXPECT_EQ(path.string(), "./foo");
EXPECT_EQ(path.parts().size(), 2);
EXPECT_EQ(path.basename(), "foo");
}

{
FileSystemPath path(".");
EXPECT_EQ(path.is_valid(), true);
EXPECT_EQ(path.string(), ".");
EXPECT_EQ(path.parts().size(), 1);
EXPECT_EQ(path.basename(), ".");
}
}

TEST_MAIN(FileSystemPath)

0 comments on commit 56eaf9b

Please sign in to comment.