[include-cleaner] Add --only-headers flag, opposite of --ignore-headers (#78714)

This commit is contained in:
Sam McCall 2024-01-22 16:03:37 +01:00 committed by GitHub
parent ff1cde5ba2
commit 3de5d8e125
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 31 additions and 3 deletions

View File

@ -22,6 +22,10 @@ int x = foo();
// IGNORE2-NOT: - "foobar.h"
// IGNORE2: + "foo.h"
// RUN: clang-include-cleaner -print=changes %s --only-headers="foo\.h" -- -I%S/Inputs/ | FileCheck --match-full-lines --allow-empty --check-prefix=ONLY %s
// ONLY-NOT: - "foobar.h"
// ONLY: + "foo.h"
// RUN: clang-include-cleaner -print %s -- -I%S/Inputs/ | FileCheck --match-full-lines --check-prefix=PRINT %s
// PRINT: #include "foo.h"
// PRINT-NOT: {{^}}#include "foobar.h"{{$}}

View File

@ -57,6 +57,14 @@ cl::opt<std::string> HTMLReportPath{
cl::cat(IncludeCleaner),
};
cl::opt<std::string> OnlyHeaders{
"only-headers",
cl::desc("A comma-separated list of regexes to match against suffix of a "
"header. Only headers that match will be analyzed."),
cl::init(""),
cl::cat(IncludeCleaner),
};
cl::opt<std::string> IgnoreHeaders{
"ignore-headers",
cl::desc("A comma-separated list of regexes to match against suffix of a "
@ -221,11 +229,12 @@ private:
llvm::StringMap<std::string> EditedFiles;
};
std::function<bool(llvm::StringRef)> headerFilter() {
// Compiles a regex list into a function that return true if any match a header.
// Prints and returns nullptr if any regexes are invalid.
std::function<bool(llvm::StringRef)> matchesAny(llvm::StringRef RegexFlag) {
auto FilterRegs = std::make_shared<std::vector<llvm::Regex>>();
llvm::SmallVector<llvm::StringRef> Headers;
llvm::StringRef(IgnoreHeaders).split(Headers, ',', -1, /*KeepEmpty=*/false);
RegexFlag.split(Headers, ',', -1, /*KeepEmpty=*/false);
for (auto HeaderPattern : Headers) {
std::string AnchoredPattern = "(" + HeaderPattern.str() + ")$";
llvm::Regex CompiledRegex(AnchoredPattern);
@ -246,6 +255,21 @@ std::function<bool(llvm::StringRef)> headerFilter() {
};
}
std::function<bool(llvm::StringRef)> headerFilter() {
auto OnlyMatches = matchesAny(OnlyHeaders);
auto IgnoreMatches = matchesAny(IgnoreHeaders);
if (!OnlyMatches || !IgnoreMatches)
return nullptr;
return [OnlyMatches, IgnoreMatches](llvm::StringRef Header) {
if (OnlyHeaders.getNumOccurrences() && !OnlyMatches(Header))
return true;
if (IgnoreHeaders.getNumOccurrences() && IgnoreMatches(Header))
return true;
return false;
};
}
} // namespace
} // namespace include_cleaner
} // namespace clang