[include-cleaner][NFC] expose and test normalizePath helper (#189364)

Also fix a bug where the root `/` path would become an empty string.
This commit is contained in:
Daniil Dudkin
2026-04-03 22:34:07 +03:00
committed by GitHub
parent 88f6b181b6
commit 418ae6c600
3 changed files with 20 additions and 4 deletions

View File

@@ -100,14 +100,12 @@ std::string Include::quote() const {
.str();
}
static llvm::SmallString<128> normalizePath(llvm::StringRef Path) {
llvm::SmallString<128> normalizePath(llvm::StringRef Path) {
namespace path = llvm::sys::path;
llvm::SmallString<128> P = Path;
path::remove_dots(P, /*remove_dot_dot=*/true);
path::native(P, path::Style::posix);
while (!P.empty() && P.back() == '/')
P.pop_back();
return P;
}

View File

@@ -96,6 +96,8 @@ template <typename T> struct Hinted : public T {
}
};
llvm::SmallString<128> normalizePath(llvm::StringRef Path);
} // namespace clang::include_cleaner
#endif

View File

@@ -1,4 +1,4 @@
//===-- RecordTest.cpp ----------------------------------------------------===//
//===-- TypesTest.cpp -----------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -7,6 +7,7 @@
//===----------------------------------------------------------------------===//
#include "clang-include-cleaner/Types.h"
#include "TypesInternal.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Tooling/Inclusions/StandardLibrary.h"
@@ -98,5 +99,20 @@ TEST(RecordedIncludesTest, MatchVerbatimMixedAbsoluteRelative) {
EXPECT_THAT(Inc.match(Header("<bar.h>")), IsEmpty());
}
TEST(NormalizePathTest, RemovesDotSegments) {
EXPECT_EQ(normalizePath("foo/./bar/../baz").str(), "foo/baz");
EXPECT_EQ(normalizePath("/foo/./bar").str(), "/foo/bar");
EXPECT_EQ(normalizePath("/foo/../bar").str(), "/bar");
EXPECT_EQ(normalizePath("foo/bar/").str(), "foo/bar");
}
TEST(NormalizePathTest, CanonicalizesSeparators) {
EXPECT_EQ(normalizePath("foo\\bar").str(), "foo/bar");
}
TEST(NormalizePathTest, PreservesRootPath) {
EXPECT_EQ(normalizePath("/").str(), "/");
}
} // namespace
} // namespace clang::include_cleaner