File: utils.cpp

package info (click to toggle)
plasma-mobile 6.5.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,412 kB
  • sloc: xml: 38,474; cpp: 18,529; javascript: 139; sh: 82; makefile: 5
file content (79 lines) | stat: -rw-r--r-- 2,347 bytes parent folder | download | duplicates (2)
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();
}