File indexing completed on 2024-05-12 05:52:48

0001 /*
0002  * SPDX-License-Identifier: GPL-3.0-or-later
0003  * SPDX-FileCopyrightText: 2020 Johan Ouwerkerk <jm.ouwerkerk@gmail.com>
0004  */
0005 #include "output.h"
0006 
0007 #include <QCoreApplication>
0008 #include <QDir>
0009 #include <QFile>
0010 #include <QTextStream>
0011 #include <QtDebug>
0012 
0013 static QString outputDirBaseName(QLatin1String("output"));
0014 static QString resourceDirBaseName(QLatin1String("resources"));
0015 
0016 namespace test
0017 {
0018     bool ensureOutputDirectory(void)
0019     {
0020         QDir base(QCoreApplication::applicationDirPath());
0021         return base.mkpath(outputDirBaseName) && base.cd(outputDirBaseName) && base.mkpath(QCoreApplication::applicationName());
0022     }
0023 
0024     bool copyResource(const QString &resource, const QString &outputRelPath)
0025     {
0026         QFile source(resource);
0027         if (ensureOutputDirectory() && source.exists()) {
0028             QDir base(QCoreApplication::applicationDirPath());
0029 
0030             if (base.cd(outputDirBaseName) && base.cd(QCoreApplication::applicationName())) {
0031                 QString dest = base.absoluteFilePath(outputRelPath);
0032                 return (!base.exists(dest) || base.remove(dest)) && source.copy(dest);
0033             }
0034         }
0035 
0036         return false;
0037     }
0038 
0039     bool ensureWritable(const QString &outputRelPath)
0040     {
0041         QFile result(test::path(outputRelPath));
0042         return result.exists() && result.setPermissions(result.permissions() | QFileDevice::WriteOwner | QFileDevice::WriteUser);
0043     }
0044 
0045     bool copyResourceAsWritable(const QString &resource, const QString &outputRelPath)
0046     {
0047         return copyResource(resource, outputRelPath) && ensureWritable(outputRelPath);
0048     }
0049 
0050     QString path(const QString &relPath)
0051     {
0052         QDir base(QCoreApplication::applicationDirPath());
0053         base.cd(outputDirBaseName);
0054         base.cd(QCoreApplication::applicationName());
0055         return base.absoluteFilePath(relPath);
0056     }
0057 
0058     QString slurp(const QString &path)
0059     {
0060         QFile source(path);
0061         bool opened = source.open(QIODevice::ReadOnly | QIODevice::Text);
0062         if (opened) {
0063             QTextStream input(&source);
0064             QString result = input.readAll();
0065             source.close();
0066             return result;
0067         } else {
0068             qDebug() << "Failed to open:" << path;
0069             return QString();
0070         }
0071     }
0072 }