File indexing completed on 2024-05-05 04:38:44
0001 /* 0002 SPDX-FileCopyrightText: 2020 Igor Kushnir <igorkuo@gmail.com> 0003 0004 SPDX-License-Identifier: LGPL-2.0-or-later 0005 */ 0006 0007 #include "filesystemhelpers.h" 0008 0009 #include <QByteArray> 0010 #include <QByteArrayList> 0011 #include <QDebug> 0012 #include <QDir> 0013 #include <QFile> 0014 #include <QFileInfo> 0015 #include <QString> 0016 #include <QStringList> 0017 0018 bool FilesystemHelpers::createNewFileAndWrite(const QString& filePath, 0019 const QByteArray& fileContents) 0020 { 0021 QFile file(filePath); 0022 0023 if (!file.open(QIODevice::NewOnly)) { 0024 qCritical() << Q_FUNC_INFO << file.error() << file.errorString(); 0025 return false; 0026 } 0027 0028 if (!fileContents.isEmpty() && file.write(fileContents) == -1) { 0029 qCritical() << Q_FUNC_INFO << file.error() << file.errorString(); 0030 return false; 0031 } 0032 return true; 0033 } 0034 0035 QString FilesystemHelpers::makeAbsoluteCreateAndWrite(const QString& dirPath, QString& filePath, 0036 const QByteArray& fileContents) 0037 { 0038 const QFileInfo info{QDir{dirPath}, filePath}; 0039 QString pathToFile = info.absolutePath(); 0040 if (!QDir{}.mkpath(pathToFile)) { 0041 return pathToFile; 0042 } 0043 filePath = info.absoluteFilePath(); 0044 if (!createNewFileAndWrite(filePath, fileContents)) { 0045 return filePath; 0046 } 0047 return QString{}; 0048 } 0049 0050 QString FilesystemHelpers::makeAbsoluteCreateAndWrite(const QString& dirPath, QStringList& filePaths, 0051 const QByteArrayList& fileContents) 0052 { 0053 Q_ASSERT(fileContents.size() == filePaths.size()); 0054 for (int i = 0; i < filePaths.size(); ++i) { 0055 QString errorPath = makeAbsoluteCreateAndWrite(dirPath, filePaths[i], fileContents[i]); 0056 if (!errorPath.isEmpty()) { 0057 return errorPath; 0058 } 0059 } 0060 return QString{}; 0061 } 0062 0063 QString FilesystemHelpers::makeAbsoluteCreateAndWrite(const QString& dirPath, QStringList& filePaths, 0064 const QByteArray& commonFileContents) 0065 { 0066 for (auto& fPath : filePaths) { 0067 QString errorPath = makeAbsoluteCreateAndWrite(dirPath, fPath, commonFileContents); 0068 if (!errorPath.isEmpty()) { 0069 return errorPath; 0070 } 0071 } 0072 return QString{}; 0073 }