aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/projectexplorer/jsonwizard/jsonwizardfilegenerator.cpp
blob: 6cb8acb2ca8bde28fb0bb5580260e8a7b8be9d8f (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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0

#include "jsonwizardfilegenerator.h"

#include "../projectexplorer.h"
#include "jsonwizard.h"
#include "jsonwizardfactory.h"

#include <coreplugin/editormanager/editormanager.h>

#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <utils/macroexpander.h>
#include <utils/templateengine.h>
#include <utils/algorithm.h>

#include <QCoreApplication>
#include <QDir>
#include <QDirIterator>
#include <QVariant>

namespace ProjectExplorer {
namespace Internal {

bool JsonWizardFileGenerator::setup(const QVariant &data, QString *errorMessage)
{
    QTC_ASSERT(errorMessage && errorMessage->isEmpty(), return false);

    const QVariantList list = JsonWizardFactory::objectOrList(data, errorMessage);
    if (list.isEmpty())
        return false;

    for (const QVariant &d : list) {
        if (d.type() != QVariant::Map) {
            *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                        "Files data list entry is not an object.");
            return false;
        }

        File f;

        const QVariantMap tmp = d.toMap();
        f.source = tmp.value(QLatin1String("source")).toString();
        f.target = tmp.value(QLatin1String("target")).toString();
        f.condition = tmp.value(QLatin1String("condition"), true);
        f.isBinary = tmp.value(QLatin1String("isBinary"), false);
        f.overwrite = tmp.value(QLatin1String("overwrite"), false);
        f.openInEditor = tmp.value(QLatin1String("openInEditor"), false);
        f.isTemporary = tmp.value(QLatin1String("temporary"), false);
        f.openAsProject = tmp.value(QLatin1String("openAsProject"), false);

        f.options = JsonWizard::parseOptions(tmp.value(QLatin1String("options")), errorMessage);
        if (!errorMessage->isEmpty())
            return false;

        if (f.source.isEmpty() && f.target.isEmpty()) {
            *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                        "Source and target are both empty.");
            return false;
        }

        if (f.target.isEmpty())
            f.target = f.source;

        m_fileList << f;
    }

    return true;
}

Core::GeneratedFile JsonWizardFileGenerator::generateFile(const File &file,
    Utils::MacroExpander *expander, QString *errorMessage)
{
    // Read contents of source file
    const QFile::OpenMode openMode = file.isBinary.toBool() ?
        QIODevice::ReadOnly : (QIODevice::ReadOnly|QIODevice::Text);

    Utils::FileReader reader;
    if (!reader.fetch(Utils::FilePath::fromString(file.source), openMode, errorMessage))
        return Core::GeneratedFile();

    // Generate file information:
    Core::GeneratedFile gf;
    gf.setPath(file.target);

    if (!file.keepExisting) {
        if (file.isBinary.toBool()) {
            gf.setBinary(true);
            gf.setBinaryContents(reader.data());
        } else {
            // TODO: Document that input files are UTF8 encoded!
            gf.setBinary(false);
            Utils::MacroExpander nested;

            // evaluate file options once:
            QHash<QString, QString> options;
            for (const JsonWizard::OptionDefinition &od : qAsConst(file.options)) {
                if (od.condition(*expander))
                    options.insert(od.key(), od.value(*expander));
            }

            nested.registerExtraResolver([&options](QString n, QString *ret) -> bool {
                if (!options.contains(n))
                    return false;
                *ret = options.value(n);
                return true;
            });
            nested.registerExtraResolver([expander](QString n, QString *ret) {
                return expander->resolveMacro(n, ret);
            });

            gf.setContents(Utils::TemplateEngine::processText(&nested, QString::fromUtf8(reader.data()),
                                                              errorMessage));
            if (!errorMessage->isEmpty()) {
                *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizard", "When processing \"%1\":<br>%2")
                        .arg(file.source, *errorMessage);
                return Core::GeneratedFile();
            }
        }
    }

    Core::GeneratedFile::Attributes attributes;
    if (JsonWizard::boolFromVariant(file.openInEditor, expander))
        attributes |= Core::GeneratedFile::OpenEditorAttribute;
    if (JsonWizard::boolFromVariant(file.openAsProject, expander))
        attributes |= Core::GeneratedFile::OpenProjectAttribute;
    if (JsonWizard::boolFromVariant(file.overwrite, expander))
        attributes |= Core::GeneratedFile::ForceOverwrite;
    if (JsonWizard::boolFromVariant(file.isTemporary, expander))
        attributes |= Core::GeneratedFile::TemporaryFile;

    if (file.keepExisting)
        attributes |= Core::GeneratedFile::KeepExistingFileAttribute;

    gf.setAttributes(attributes);
    return gf;
}

Core::GeneratedFiles JsonWizardFileGenerator::fileList(Utils::MacroExpander *expander,
                                                       const QString &wizardDir, const QString &projectDir,
                                                       QString *errorMessage)
{
    errorMessage->clear();

    QDir wizard(wizardDir);
    QDir project(projectDir);

    const QList<File> enabledFiles
            = Utils::filtered(m_fileList, [&expander](const File &f) {
                                  return JsonWizard::boolFromVariant(f.condition, expander);
                              });

    const QList<File> concreteFiles
            = Utils::transform(enabledFiles,
                               [&expander, &wizard, &project](const File &f) -> File {
                                  // Return a new file with concrete values based on input file:
                                  File file = f;

                                  file.keepExisting = file.source.isEmpty();
                                  file.target = project.absoluteFilePath(expander->expand(file.target));
                                  file.source = file.keepExisting ? file.target : wizard.absoluteFilePath(
                                      expander->expand(file.source));
                                  file.isBinary = JsonWizard::boolFromVariant(file.isBinary, expander);

                                  return file;
                               });

    QList<File> fileList;
    QList<File> dirList;
    std::tie(fileList, dirList)
            = Utils::partition(concreteFiles, [](const File &f) { return !QFileInfo(f.source).isDir(); });

    const QSet<QString> knownFiles = Utils::transform<QSet>(fileList, &File::target);

    for (const File &dir : qAsConst(dirList)) {
        QDir sourceDir(dir.source);
        QDirIterator it(dir.source, QDir::NoDotAndDotDot | QDir::Files| QDir::Hidden,
                        QDirIterator::Subdirectories);

        while (it.hasNext()) {
            const QString relativeFilePath = sourceDir.relativeFilePath(it.next());
            const QString targetPath = dir.target + QLatin1Char('/') + relativeFilePath;

            if (knownFiles.contains(targetPath))
                continue;

            // initialize each new file with properties (isBinary etc)
            // from the current directory json entry
            File newFile = dir;
            newFile.source = dir.source + QLatin1Char('/') + relativeFilePath;
            newFile.target = targetPath;
            fileList.append(newFile);
        }
    }

    const Core::GeneratedFiles result
            = Utils::transform(fileList,
                               [this, &expander, &errorMessage](const File &f) {
                                   return generateFile(f, expander, errorMessage);
                               });

    if (Utils::contains(result, [](const Core::GeneratedFile &gf) { return gf.path().isEmpty(); }))
        return Core::GeneratedFiles();

    return result;
}

bool JsonWizardFileGenerator::writeFile(const JsonWizard *wizard, Core::GeneratedFile *file, QString *errorMessage)
{
    Q_UNUSED(wizard)
    if (!(file->attributes() & Core::GeneratedFile::KeepExistingFileAttribute)) {
        if (!file->write(errorMessage))
            return false;
    }
    return true;
}

} // namespace Internal
} // namespace ProjectExplorer