File indexing completed on 2024-05-05 05:29:12

0001 /*
0002  *   SPDX-FileCopyrightText: 2018 Aleix Pol Gonzalez <aleixpol@blue-systems.com>
0003  *
0004  *   SPDX-License-Identifier: LGPL-2.0-or-later
0005  */
0006 
0007 #include "ReadFile.h"
0008 #include "discover_debug.h"
0009 
0010 ReadFile::ReadFile()
0011 {
0012     connect(&m_watcher, &QFileSystemWatcher::fileChanged, this, &ReadFile::openNow);
0013     connect(&m_file, &QFile::readyRead, this, &ReadFile::process);
0014 }
0015 
0016 void ReadFile::componentComplete()
0017 {
0018     completed = true;
0019     openNow();
0020 }
0021 
0022 void ReadFile::setPath(QString path)
0023 {
0024     processPath(path);
0025     if (path == m_file.fileName())
0026         return;
0027 
0028     if (path.isEmpty())
0029         return;
0030 
0031     if (m_file.isOpen())
0032         m_watcher.removePath(m_file.fileName());
0033 
0034     m_file.setFileName(path);
0035     m_sizeOnSet = m_file.size() + 1;
0036     openNow();
0037 
0038     m_watcher.addPath(m_file.fileName());
0039 }
0040 
0041 void ReadFile::openNow()
0042 {
0043     if (!completed)
0044         return;
0045 
0046     if (!m_contents.isEmpty()) {
0047         m_contents.clear();
0048         Q_EMIT contentsChanged(m_contents);
0049     }
0050     m_file.close();
0051     const auto open = m_file.open(QIODevice::ReadOnly | QIODevice::Text);
0052     Q_EMIT pathChanged(path());
0053     if (!open)
0054         return;
0055 
0056     m_stream.reset(new QTextStream(&m_file));
0057     m_stream->seek(m_sizeOnSet);
0058     process();
0059 }
0060 
0061 void ReadFile::processPath(QString &path)
0062 {
0063     const QRegularExpression envRx(QStringLiteral("\\$([A-Z_]+)"));
0064     auto matchIt = envRx.globalMatch(path);
0065     while (matchIt.hasNext()) {
0066         auto match = matchIt.next();
0067         path.replace(match.capturedStart(), match.capturedLength(), QString::fromUtf8(qgetenv(match.capturedView(1).toUtf8().constData())));
0068     }
0069 }
0070 
0071 void ReadFile::process()
0072 {
0073     const QString read = m_stream->readAll();
0074 
0075     if (m_filter.isValid() && !m_filter.pattern().isEmpty()) {
0076         auto it = m_filter.globalMatch(read);
0077         while (it.hasNext()) {
0078             const auto match = it.next();
0079             m_contents.append(match.capturedView(match.lastCapturedIndex()));
0080             m_contents.append(QLatin1Char('\n'));
0081         }
0082     } else
0083         m_contents += read;
0084     Q_EMIT contentsChanged(m_contents);
0085 }
0086 
0087 void ReadFile::setFilter(const QString &filter)
0088 {
0089     m_filter = QRegularExpression(filter);
0090     if (!m_filter.isValid())
0091         qCDebug(DISCOVER_LOG) << "error" << m_filter.errorString();
0092     Q_ASSERT(filter.isEmpty() || m_filter.isValid());
0093 }
0094 
0095 QString ReadFile::filter() const
0096 {
0097     return m_filter.pattern();
0098 }