1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
// SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
// SPDX-License-Identifier: GPL-2.0-or-later
#include "utils.h"
#include <QStandardPaths>
void setOptionsImmutable(bool immutable, const QString &configFilePath, const QMap<QString, QMap<QString, QVariant>> &options)
{
// Find ~/.config/{configFilePath}
QDir basePath{QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)};
QString fullPath = basePath.filePath(configFilePath);
QFile file{fullPath};
if (!file.exists()) {
return;
}
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qCCritical(LOGGING_CATEGORY) << "Unable to read from" << configFilePath << "to change immutability!";
return;
}
QTextStream in(&file);
QStringList lines;
QString configGroup;
// Read file line by line, and add/remove [$i] suffixes from each option
while (!in.atEnd()) {
QString line = in.readLine();
if (line.trimmed().startsWith("//")) {
lines << line;
continue;
}
// Split by first '=' sign
int equalsIndex = line.indexOf('=');
if (equalsIndex == -1) {
lines << line;
// Is it a group?
if (line.startsWith("[") && line.endsWith("]")) {
configGroup = line.mid(1, line.length() - 2);
}
continue;
}
QString key = line.mid(0, equalsIndex);
QString value = line.mid(equalsIndex + 1);
const QString immutableSuffix = "[$i]";
// Remove [$i] key suffix
if (key.endsWith(immutableSuffix)) {
key.chop(immutableSuffix.length());
}
// Add [$i] key suffix, only edit line if it's found in provided options
if (immutable && (options.contains(configGroup) && options[configGroup].contains(key))) {
key += immutableSuffix;
}
lines << (key + "=" + value);
}
file.close();
// Overwrite file with edited lines
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
qCCritical(LOGGING_CATEGORY) << "Unable to write to" << configFilePath << "to change immutability!";
return;
}
QTextStream out(&file);
for (const QString &line : std::as_const(lines)) {
out << line << "\n";
}
file.close();
}
|