1 | // Copyright (C) 2022 The Qt Company Ltd. |
---|---|
2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 |
3 | |
4 | #include "filesignificancecheck.h" |
5 | |
6 | #include <mutex> |
7 | |
8 | QT_BEGIN_NAMESPACE |
9 | |
10 | FileSignificanceCheck *FileSignificanceCheck::m_instance = nullptr; |
11 | |
12 | void FileSignificanceCheck::setRootDirectories(const QStringList &paths) |
13 | { |
14 | const size_t pathsSize = static_cast<size_t>(paths.size()); |
15 | m_rootDirs.resize(new_size: pathsSize); |
16 | for (size_t i = 0; i < pathsSize; ++i) |
17 | m_rootDirs[i].setPath(paths.at(i)); |
18 | } |
19 | |
20 | void FileSignificanceCheck::setExclusionPatterns(const QStringList &patterns) |
21 | { |
22 | const size_t patternsSize = static_cast<size_t>(patterns.size()); |
23 | m_exclusionRegExes.resize(new_size: patternsSize); |
24 | for (size_t i = 0; i < patternsSize; ++i) |
25 | m_exclusionRegExes[i] = QRegularExpression::fromWildcard(pattern: patterns.at(i)); |
26 | } |
27 | |
28 | /* |
29 | * Return true if the given source file is significant for lupdate. |
30 | * A file is considered insignificant if |
31 | * - it's not within any project root |
32 | * - it's excluded |
33 | * |
34 | * This method is called from multiple threads. |
35 | * Results are cached. |
36 | */ |
37 | bool FileSignificanceCheck::isFileSignificant(const std::string &filePath) const |
38 | { |
39 | // cache lookup |
40 | std::shared_lock<std::shared_mutex> readLock(m_cacheMutex); |
41 | auto it = m_cache.find(x: filePath); |
42 | if (it != m_cache.end()) |
43 | return it->second; |
44 | |
45 | // cache miss |
46 | readLock.unlock(); |
47 | std::unique_lock<std::shared_mutex> writeLock(m_cacheMutex); |
48 | QString file = QString::fromUtf8(utf8: filePath); |
49 | QString cleanFile = QDir::cleanPath(path: file); |
50 | for (const QRegularExpression &rx : m_exclusionRegExes) { |
51 | if (rx.match(subject: cleanFile).hasMatch()) { |
52 | m_cache.insert(x: {filePath, false}); |
53 | return false; |
54 | } |
55 | } |
56 | |
57 | for (const QDir &rootDir : m_rootDirs) { |
58 | QString relativeFilePath = rootDir.relativeFilePath(fileName: file); |
59 | if (!relativeFilePath.startsWith(s: QLatin1String("../")) |
60 | && QFileInfo(relativeFilePath).isRelative()) { |
61 | m_cache.insert(x: {filePath, true}); |
62 | return true; |
63 | } |
64 | } |
65 | |
66 | m_cache.insert(x: {filePath, false}); |
67 | return false; |
68 | } |
69 | |
70 | QT_END_NAMESPACE |
71 |