aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/cmakeprojectmanager/presetsparser.cpp
blob: 0f9b0c8c8efc5f0374dc0c49663513372d34e65a (plain)
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "presetsparser.h"

#include "cmakeprojectmanagertr.h"

#include <utils/algorithm.h>

#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>

namespace CMakeProjectManager::Internal {

bool parseVersion(const QJsonValue &jsonValue, int &version)
{
    if (jsonValue.isUndefined())
        return false;

    const int invalidVersion = -1;
    version = jsonValue.toInt(invalidVersion);
    return version != invalidVersion;
}

bool parseCMakeMinimumRequired(const QJsonValue &jsonValue, QVersionNumber &versionNumber)
{
    if (jsonValue.isUndefined() || !jsonValue.isObject())
        return false;

    QJsonObject object = jsonValue.toObject();
    versionNumber = QVersionNumber(object.value("major").toInt(),
                                   object.value("minor").toInt(),
                                   object.value("patch").toInt());

    return true;
}

std::optional<QStringList> parseInclude(const QJsonValue &jsonValue)
{
    std::optional<QStringList> includes;

    if (!jsonValue.isUndefined()) {
        if (jsonValue.isArray()) {
            includes = QStringList();
            const QJsonArray includeArray = jsonValue.toArray();
            for (const QJsonValue &includeValue : includeArray)
                includes.value() << includeValue.toString();
        }
    }

    return includes;
}

std::optional<PresetsDetails::Condition> parseCondition(const QJsonValue &jsonValue)
{
    std::optional<PresetsDetails::Condition> condition;

    if (jsonValue.isUndefined())
        return condition;

    condition = PresetsDetails::Condition();

    if (jsonValue.isNull()) {
        condition->type = "null";
        return condition;
    }

    if (jsonValue.isBool()) {
        condition->type = "const";
        condition->constValue = jsonValue.toBool();
        return condition;
    }

    if (!jsonValue.isObject())
        return condition;

    QJsonObject object = jsonValue.toObject();
    QString type = object.value("type").toString();
    if (type.isEmpty())
        return condition;

    if (type == "const") {
        condition->type = type;
        condition->constValue = object.value("const").toBool();
        return condition;
    }

    for (const auto &equals : {QString("equals"), QString("notEquals")}) {
        if (type == equals) {
            condition->type = equals;
            condition->lhs = object.value("lhs").toString();
            condition->rhs = object.value("rhs").toString();
        }
    }
    if (!condition->type.isEmpty())
        return condition;

    for (const auto &inList : {QString("inList"), QString("notInList")}) {
        if (type == inList) {
            condition->type = inList;
            condition->string = object.value("string").toString();
            if (object.value("list").isArray()) {
                condition->list = QStringList();
                const QJsonArray listArray = object.value("list").toArray();
                for (const QJsonValue &listValue : listArray)
                    condition->list.value() << listValue.toString();
            }
        }
    }
    if (!condition->type.isEmpty())
        return condition;

    for (const auto &matches : {QString("matches"), QString("notMatches")}) {
        if (type == matches) {
            condition->type = matches;
            condition->string = object.value("string").toString();
            condition->regex = object.value("regex").toString();
        }
    }
    if (!condition->type.isEmpty())
        return condition;

    for (const auto &anyOf : {QString("anyOf"), QString("allOf")}) {
        if (type == anyOf) {
            condition->type = anyOf;
            if (object.value("conditions").isArray()) {
                condition->conditions = std::vector<PresetsDetails::Condition::ConditionPtr>();
                const QJsonArray conditionsArray = object.value("conditions").toArray();
                for (const QJsonValue &conditionsValue : conditionsArray) {
                    condition->conditions.value().emplace_back(
                        std::make_shared<PresetsDetails::Condition>(
                            parseCondition(conditionsValue).value()));
                }
            }
        }
    }
    if (!condition->type.isEmpty())
        return condition;

    if (type == "not") {
        condition->type = type;
        condition->condition = std::make_shared<PresetsDetails::Condition>(
            parseCondition(object.value("condition")).value());
        return condition;
    }

    return condition;
}

bool parseConfigurePresets(const QJsonValue &jsonValue,
                           QList<PresetsDetails::ConfigurePreset> &configurePresets,
                           const Utils::FilePath &fileDir)
{
    // The whole section is optional
    if (jsonValue.isUndefined())
        return true;

    if (!jsonValue.isArray())
        return false;

    const QJsonArray configurePresetsArray = jsonValue.toArray();
    for (const QJsonValue &presetJson : configurePresetsArray) {
        if (!presetJson.isObject())
            continue;

        QJsonObject object = presetJson.toObject();
        PresetsDetails::ConfigurePreset preset;

        preset.name = object.value("name").toString();
        preset.fileDir = fileDir;
        preset.hidden = object.value("hidden").toBool();

        QJsonValue inherits = object.value("inherits");
        if (!inherits.isUndefined()) {
            preset.inherits = QStringList();
            if (inherits.isArray()) {
                const QJsonArray inheritsArray = inherits.toArray();
                for (const QJsonValue &inheritsValue : inheritsArray)
                    preset.inherits.value() << inheritsValue.toString();
            } else {
                QString inheritsValue = inherits.toString();
                if (!inheritsValue.isEmpty())
                    preset.inherits.value() << inheritsValue;
            }
        }

        if (object.contains("condition"))
            preset.condition = parseCondition(object.value("condition"));

        if (object.contains("displayName"))
            preset.displayName = object.value("displayName").toString();
        if (object.contains("description"))
            preset.description = object.value("description").toString();
        if (object.contains("generator"))
            preset.generator = object.value("generator").toString();
        if (object.contains("binaryDir"))
            preset.binaryDir = object.value("binaryDir").toString();
        if (object.contains("installDir"))
            preset.installDir = object.value("installDir").toString();
        if (object.contains("toolchainFile"))
            preset.toolchainFile = object.value("toolchainFile").toString();
        if (object.contains("cmakeExecutable"))
            preset.cmakeExecutable = object.value("cmakeExecutable").toString();

        const QJsonObject cacheVariablesObj = object.value("cacheVariables").toObject();
        for (const QString &cacheKey : cacheVariablesObj.keys()) {
            if (!preset.cacheVariables)
                preset.cacheVariables = CMakeConfig();

            QJsonValue cacheValue = cacheVariablesObj.value(cacheKey);
            if (cacheValue.isObject()) {
                QJsonObject cacheVariableObj = cacheValue.toObject();
                CMakeConfigItem item;
                item.key = cacheKey.toUtf8();
                item.type = CMakeConfigItem::typeStringToType(
                    cacheVariableObj.value("type").toString().toUtf8());
                item.value = cacheVariableObj.value("value").toString().toUtf8();
                preset.cacheVariables.value() << item;

            } else {
                if (cacheValue.isBool()) {
                    preset.cacheVariables.value()
                        << CMakeConfigItem(cacheKey.toUtf8(),
                                           CMakeConfigItem::BOOL,
                                           cacheValue.toBool() ? "ON" : "OFF");
                } else if (CMakeConfigItem::toBool(cacheValue.toString()).has_value()) {
                    preset.cacheVariables.value()
                        << CMakeConfigItem(cacheKey.toUtf8(),
                                           CMakeConfigItem::BOOL,
                                           cacheValue.toString().toUtf8());
                } else {
                    preset.cacheVariables.value()
                        << CMakeConfigItem(cacheKey.toUtf8(), cacheValue.toString().toUtf8());
                }
            }
        }

        const QJsonObject environmentObj = object.value("environment").toObject();
        for (const QString &envKey : environmentObj.keys()) {
            if (!preset.environment)
                preset.environment = Utils::Environment();

            QJsonValue envValue = environmentObj.value(envKey);
            preset.environment.value().set(envKey, envValue.toString());
        }

        const QJsonObject warningsObj = object.value("warnings").toObject();
        if (!warningsObj.isEmpty()) {
            preset.warnings = PresetsDetails::Warnings();

            if (warningsObj.contains("dev"))
                preset.warnings->dev = warningsObj.value("dev").toBool();
            if (warningsObj.contains("deprecated"))
                preset.warnings->deprecated = warningsObj.value("deprecated").toBool();
            if (warningsObj.contains("uninitialized"))
                preset.warnings->uninitialized = warningsObj.value("uninitialized").toBool();
            if (warningsObj.contains("unusedCli"))
                preset.warnings->unusedCli = warningsObj.value("unusedCli").toBool();
            if (warningsObj.contains("systemVars"))
                preset.warnings->systemVars = warningsObj.value("systemVars").toBool();
        }

        const QJsonObject errorsObj = object.value("errors").toObject();
        if (!errorsObj.isEmpty()) {
            preset.errors = PresetsDetails::Errors();

            if (errorsObj.contains("dev"))
                preset.errors->dev = errorsObj.value("dev").toBool();
            if (errorsObj.contains("deprecated"))
                preset.errors->deprecated = errorsObj.value("deprecated").toBool();
        }

        const QJsonObject debugObj = object.value("debug").toObject();
        if (!debugObj.isEmpty()) {
            preset.debug = PresetsDetails::Debug();

            if (debugObj.contains("output"))
                preset.debug->output = debugObj.value("output").toBool();
            if (debugObj.contains("tryCompile"))
                preset.debug->tryCompile = debugObj.value("tryCompile").toBool();
            if (debugObj.contains("find"))
                preset.debug->find = debugObj.value("find").toBool();
        }

        const QJsonObject architectureObj = object.value("architecture").toObject();
        if (!architectureObj.isEmpty()) {
            preset.architecture = PresetsDetails::ValueStrategyPair();

            if (architectureObj.contains("value"))
                preset.architecture->value = architectureObj.value("value").toString();
            if (architectureObj.contains("strategy")) {
                const QString strategy = architectureObj.value("strategy").toString();
                if (strategy == "set")
                    preset.architecture->strategy = PresetsDetails::ValueStrategyPair::Strategy::set;
                if (strategy == "external")
                    preset.architecture->strategy
                        = PresetsDetails::ValueStrategyPair::Strategy::external;
            }
        }

        const QJsonObject toolsetObj = object.value("toolset").toObject();
        if (!toolsetObj.isEmpty()) {
            preset.toolset = PresetsDetails::ValueStrategyPair();

            if (toolsetObj.contains("value"))
                preset.toolset->value = toolsetObj.value("value").toString();
            if (toolsetObj.contains("strategy")) {
                const QString strategy = toolsetObj.value("strategy").toString();
                if (strategy == "set")
                    preset.toolset->strategy = PresetsDetails::ValueStrategyPair::Strategy::set;
                if (strategy == "external")
                    preset.toolset->strategy = PresetsDetails::ValueStrategyPair::Strategy::external;
            }
        }

        configurePresets.emplace_back(preset);
    }

    return true;
}

bool parseBuildPresets(const QJsonValue &jsonValue,
                       QList<PresetsDetails::BuildPreset> &buildPresets,
                       const Utils::FilePath &fileDir)
{
    // The whole section is optional
    if (jsonValue.isUndefined())
        return true;

    if (!jsonValue.isArray())
        return false;

    const QJsonArray buildPresetsArray = jsonValue.toArray();
    for (const QJsonValue &presetJson : buildPresetsArray) {
        if (!presetJson.isObject())
            continue;

        QJsonObject object = presetJson.toObject();
        PresetsDetails::BuildPreset preset;

        preset.name = object.value("name").toString();
        preset.fileDir = fileDir;
        preset.hidden = object.value("hidden").toBool();

        QJsonValue inherits = object.value("inherits");
        if (!inherits.isUndefined()) {
            preset.inherits = QStringList();
            if (inherits.isArray()) {
                const QJsonArray inheritsArray = inherits.toArray();
                for (const QJsonValue &inheritsValue : inheritsArray)
                    preset.inherits.value() << inheritsValue.toString();
            } else {
                QString inheritsValue = inherits.toString();
                if (!inheritsValue.isEmpty())
                    preset.inherits.value() << inheritsValue;
            }
        }

        if (object.contains("condition"))
            preset.condition = parseCondition(object.value("condition"));

        if (object.contains("displayName"))
            preset.displayName = object.value("displayName").toString();
        if (object.contains("description"))
            preset.description = object.value("description").toString();

        const QJsonObject environmentObj = object.value("environment").toObject();
        for (const QString &envKey : environmentObj.keys()) {
            if (!preset.environment)
                preset.environment = Utils::Environment();

            QJsonValue envValue = environmentObj.value(envKey);
            preset.environment.value().set(envKey, envValue.toString());
        }

        if (object.contains("configurePreset"))
            preset.configurePreset = object.value("configurePreset").toString();
        if (object.contains("inheritConfigureEnvironment"))
            preset.inheritConfigureEnvironment = object.value("inheritConfigureEnvironment").toBool();
        if (object.contains("jobs"))
            preset.jobs = object.value("jobs").toInt();

        QJsonValue targets = object.value("targets");
        if (!targets.isUndefined()) {
            preset.targets = QStringList();
            if (targets.isArray()) {
                const QJsonArray targetsArray = targets.toArray();
                for (const QJsonValue &targetsValue : targetsArray)
                    preset.targets.value() << targetsValue.toString();
            } else {
                QString targetsValue = targets.toString();
                if (!targetsValue.isEmpty())
                    preset.targets.value() << targetsValue;
            }
        }
        if (object.contains("configuration"))
            preset.configuration = object.value("configuration").toString();
        if (object.contains("verbose"))
            preset.verbose = object.value("verbose").toBool();
        if (object.contains("cleanFirst"))
            preset.cleanFirst = object.value("cleanFirst").toBool();

        QJsonValue nativeToolOptions = object.value("nativeToolOptions");
        if (!nativeToolOptions.isUndefined()) {
            if (nativeToolOptions.isArray()) {
                preset.nativeToolOptions = QStringList();
                const QJsonArray toolOptionsArray = nativeToolOptions.toArray();
                for (const QJsonValue &toolOptionsValue : toolOptionsArray)
                    preset.nativeToolOptions.value() << toolOptionsValue.toString();
            }
        }

        buildPresets.emplace_back(preset);
    }

    return true;
}

const PresetsData &PresetsParser::presetsData() const
{
    return m_presetsData;
}

bool PresetsParser::parse(const Utils::FilePath &jsonFile, QString &errorMessage, int &errorLine)
{
    const Utils::expected_str<QByteArray> jsonContents = jsonFile.fileContents();
    if (!jsonContents) {
        errorMessage = Tr::tr("Failed to read file \"%1\".").arg(jsonFile.fileName());
        return false;
    }

    QJsonParseError error;
    const QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonContents.value(), &error);
    if (jsonDoc.isNull()) {
        errorLine = 1;
        for (int i = 0; i < error.offset; ++i)
            if (jsonContents.value().at(i) == '\n')
                ++errorLine;
        errorMessage = error.errorString();
        return false;
    }

    if (!jsonDoc.isObject()) {
        errorMessage = Tr::tr("Invalid file \"%1\".").arg(jsonFile.fileName());
        return false;
    }

    QJsonObject root = jsonDoc.object();

    m_presetsData.fileDir = jsonFile.parentDir();

    if (!parseVersion(root.value("version"), m_presetsData.version)) {
        errorMessage = Tr::tr("Invalid \"version\" in file \"%1\".").arg(jsonFile.fileName());
        return false;
    }

    // optional
    parseCMakeMinimumRequired(root.value("cmakeMinimumRequired"),
                              m_presetsData.cmakeMinimimRequired);

    // optional
    m_presetsData.include = parseInclude(root.value("include"));

    // optional
    if (!parseConfigurePresets(root.value("configurePresets"),
                               m_presetsData.configurePresets,
                               jsonFile.parentDir())) {
        errorMessage
            = Tr::tr("Invalid \"configurePresets\" section in %1 file").arg(jsonFile.fileName());
        return false;
    }

    // optional
    if (!parseBuildPresets(root.value("buildPresets"),
                           m_presetsData.buildPresets,
                           jsonFile.parentDir())) {
        errorMessage
            = Tr::tr("Invalid \"buildPresets\" section in %1 file").arg(jsonFile.fileName());
        return false;
    }

    return true;
}

static QHash<QString, QString> merge(const QHash<QString, QString> &first,
                                     const QHash<QString, QString> &second)
{
    QHash<QString, QString> result = first;
    for (auto it = second.constKeyValueBegin(); it != second.constKeyValueEnd(); ++it) {
        result[it->first] = it->second;
    }

    return result;
}

static CMakeConfig merge(const CMakeConfig &first, const CMakeConfig &second)
{
    return Utils::setUnionMerge<CMakeConfig>(
        first,
        second,
        [](const auto & /*left*/, const auto &right) { return right; },
        &CMakeConfigItem::less);
}

static QStringList merge(const QStringList &first, const QStringList &second)
{
    return Utils::setUnionMerge<QStringList>(
        first,
        second,
        [](const auto & /*left*/, const auto &right) { return right; });
}

void PresetsDetails::ConfigurePreset::inheritFrom(const ConfigurePreset &other)
{
    if (!condition && other.condition && !other.condition.value().isNull())
        condition = other.condition;

    if (!vendor && other.vendor)
        vendor = other.vendor;

    if (vendor && other.vendor)
        vendor = merge(other.vendor.value(), vendor.value());

    if (!generator && other.generator)
        generator = other.generator;

    if (!architecture && other.architecture)
        architecture = other.architecture;

    if (!toolset && other.toolset)
        toolset = other.toolset;

    if (!toolchainFile && other.toolchainFile)
        toolchainFile = other.toolchainFile;

    if (!binaryDir && other.binaryDir)
        binaryDir = other.binaryDir;

    if (!installDir && other.installDir)
        installDir = other.installDir;

    if (!cmakeExecutable && other.cmakeExecutable)
        cmakeExecutable = other.cmakeExecutable;

    if (!cacheVariables && other.cacheVariables)
        cacheVariables = other.cacheVariables;
    else if (cacheVariables && other.cacheVariables)
        cacheVariables = merge(other.cacheVariables.value(), cacheVariables.value());

    if (!environment && other.environment)
        environment = other.environment;
    else if (environment && other.environment)
        environment = environment.value().appliedToEnvironment(other.environment.value());

    if (!warnings && other.warnings)
        warnings = other.warnings;

    if (!errors && other.errors)
        errors = other.errors;

    if (!debug && other.debug)
        debug = other.debug;
}

void PresetsDetails::BuildPreset::inheritFrom(const BuildPreset &other)
{
    if (!condition && other.condition && !other.condition.value().isNull())
        condition = other.condition;

    if (!vendor && other.vendor)
        vendor = other.vendor;

    if (vendor && other.vendor)
        vendor = merge(other.vendor.value(), vendor.value());

    if (!environment && other.environment)
        environment = other.environment;
    else if (environment && other.environment)
        environment = environment.value().appliedToEnvironment(other.environment.value());

    if (!configurePreset && other.configurePreset)
        configurePreset = other.configurePreset;

    if (!inheritConfigureEnvironment && other.inheritConfigureEnvironment)
        inheritConfigureEnvironment = other.inheritConfigureEnvironment;

    if (!jobs && other.jobs)
        jobs = other.jobs;

    if (!targets && other.targets)
        targets = other.targets;
    else if (targets && other.targets)
        targets = merge(other.targets.value(), targets.value());

    if (!configuration && other.configuration)
        configuration = other.configuration;

    if (!verbose && other.verbose)
        verbose = other.verbose;

    if (!cleanFirst && other.cleanFirst)
        cleanFirst = other.cleanFirst;

    if (!nativeToolOptions && other.nativeToolOptions)
        nativeToolOptions = other.nativeToolOptions;
    else if (nativeToolOptions && other.nativeToolOptions)
        nativeToolOptions = merge(other.nativeToolOptions.value(), nativeToolOptions.value());
}

bool PresetsDetails::Condition::evaluate() const
{
    if (isNull())
        return true;

    if (isConst() && constValue)
        return constValue.value();

    if (isEquals() && lhs && rhs)
        return lhs.value() == rhs.value();

    if (isNotEquals() && lhs && rhs)
        return lhs.value() != rhs.value();

    if (isInList() && string && list)
        return list.value().contains(string.value());

    if (isNotInList() && string && list)
        return !list.value().contains(string.value());

    if (isMatches() && string && regex) {
        QRegularExpression qRegex(regex.value());
        return qRegex.match(string.value()).hasMatch();
    }

    if (isNotMatches() && string && regex) {
        QRegularExpression qRegex(regex.value());
        return !qRegex.match(string.value()).hasMatch();
    }

    if (isAnyOf() && conditions)
        return Utils::anyOf(conditions.value(), [](const ConditionPtr &c) { return c->evaluate(); });

    if (isAllOf() && conditions)
        return Utils::allOf(conditions.value(), [](const ConditionPtr &c) { return c->evaluate(); });

    if (isNot() && condition)
        return !condition.value()->evaluate();

    return false;
}

} // CMakeProjectManager::Internal