1//===- HeaderFile.cpp ------------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "clang/InstallAPI/HeaderFile.h"
10#include "llvm/Support/VirtualFileSystem.h"
11#include "llvm/TextAPI/Utils.h"
12
13using namespace llvm;
14namespace clang::installapi {
15
16llvm::Regex HeaderFile::getFrameworkIncludeRule() {
17 return llvm::Regex("/(.+)\\.framework/(.+)?Headers/(.+)");
18}
19
20std::optional<std::string> createIncludeHeaderName(const StringRef FullPath) {
21 // Headers in usr(/local)*/include.
22 std::string Pattern = "/include/";
23 auto PathPrefix = FullPath.find(Str: Pattern);
24 if (PathPrefix != StringRef::npos) {
25 PathPrefix += Pattern.size();
26 return FullPath.drop_front(N: PathPrefix).str();
27 }
28
29 // Framework Headers.
30 SmallVector<StringRef, 4> Matches;
31 HeaderFile::getFrameworkIncludeRule().match(String: FullPath, Matches: &Matches);
32 // Returned matches are always in stable order.
33 if (Matches.size() != 4)
34 return std::nullopt;
35
36 return Matches[1].drop_front(N: Matches[1].rfind(C: '/') + 1).str() + "/" +
37 Matches[3].str();
38}
39
40bool isHeaderFile(StringRef Path) {
41 return StringSwitch<bool>(sys::path::extension(path: Path))
42 .Cases(CaseStrings: {".h", ".H", ".hh", ".hpp", ".hxx"}, Value: true)
43 .Default(Value: false);
44}
45
46llvm::Expected<PathSeq> enumerateFiles(FileManager &FM, StringRef Directory) {
47 PathSeq Files;
48 std::error_code EC;
49 auto &FS = FM.getVirtualFileSystem();
50 for (llvm::vfs::recursive_directory_iterator i(FS, Directory, EC), ie;
51 i != ie; i.increment(EC)) {
52 if (EC)
53 return errorCodeToError(EC);
54
55 // Skip files that do not exist. This usually happens for broken symlinks.
56 if (FS.status(Path: i->path()) == std::errc::no_such_file_or_directory)
57 continue;
58
59 StringRef Path = i->path();
60 if (isHeaderFile(Path))
61 Files.emplace_back(args&: Path);
62 }
63
64 return Files;
65}
66
67HeaderGlob::HeaderGlob(StringRef GlobString, Regex &&Rule, HeaderType Type)
68 : GlobString(GlobString), Rule(std::move(Rule)), Type(Type) {}
69
70bool HeaderGlob::match(const HeaderFile &Header) {
71 if (Header.getType() != Type)
72 return false;
73
74 bool Match = Rule.match(String: Header.getPath());
75 if (Match)
76 FoundMatch = true;
77 return Match;
78}
79
80Expected<std::unique_ptr<HeaderGlob>> HeaderGlob::create(StringRef GlobString,
81 HeaderType Type) {
82 auto Rule = MachO::createRegexFromGlob(Glob: GlobString);
83 if (!Rule)
84 return Rule.takeError();
85
86 return std::make_unique<HeaderGlob>(args&: GlobString, args: std::move(*Rule), args&: Type);
87}
88
89} // namespace clang::installapi
90