1/*
2 This file is part of the KDE Baloo project.
3 SPDX-FileCopyrightText: 2010 Sebastian Trueg <trueg@kde.org>
4 SPDX-FileCopyrightText: 2014 Vishesh Handa <me@vhanda.in>
5
6 SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
7*/
8
9#include "regexpcache.h"
10#include "baloodebug.h"
11
12#include <QStringList>
13
14RegExpCache::RegExpCache()
15{
16}
17
18RegExpCache::~RegExpCache()
19{
20}
21
22bool RegExpCache::exactMatch(const QString& s) const
23{
24 if (m_exactMatches.contains(value: s)) {
25 return true;
26 }
27 for (const QRegularExpression& filter : std::as_const(t: m_regexpCache)) {
28 if (filter.match(subject: s).hasMatch()) {
29 return true;
30 }
31 }
32 return false;
33}
34
35void RegExpCache::rebuildCacheFromFilterList(const QStringList& filters)
36{
37 m_regexpCache.clear();
38 m_exactMatches.clear();
39
40 // RE matching "*.foo" style patterns
41 QRegularExpression suffixOnlyRe(QStringLiteral("^\\*\\.([^.\\*\\?]+)$"));
42 QStringList suffixes;
43
44 for (const QString& filter : filters) {
45 QString f = filter;
46 if (!f.contains(c: QLatin1Char('*')) && !f.contains(c: QLatin1Char('?'))) {
47 m_exactMatches += f;
48 continue;
49 }
50 auto m = suffixOnlyRe.match(subject: f);
51 if (m.hasMatch()) {
52 // qCDebug(BALOO) << "filter is suffix match:" << m;
53 suffixes += m.captured(nth: 1);
54 continue;
55 }
56 f.replace(c: QLatin1Char('.'), QStringLiteral("\\."));
57 f.replace(before: QLatin1Char('?'), after: QLatin1Char('.'));
58 f.replace(QStringLiteral("*"), QStringLiteral(".*"));
59 f = QLatin1String("^") + f + QLatin1String("$");
60
61 m_regexpCache.append(t: QRegularExpression(f));
62 }
63
64 // Combine all suffixes into one large RE: "^.*(foo|bar|baz)$"
65 QString suffixMatch = QStringLiteral("^.*\\.(")
66 + suffixes.join(sep: QLatin1Char('|'))
67 + QStringLiteral(")$");
68 // qCDebug(BALOO) << suffixMatch;
69 m_regexpCache.prepend(t: QRegularExpression(suffixMatch));
70}
71

source code of baloo/src/file/regexpcache.cpp