File: templaterenderer.cpp

package info (click to toggle)
kdevelop 4%3A5.6.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 57,892 kB
  • sloc: cpp: 278,773; javascript: 3,558; python: 3,385; sh: 1,317; ansic: 689; xml: 273; php: 95; makefile: 40; lisp: 13; sed: 12
file content (310 lines) | stat: -rw-r--r-- 8,961 bytes parent folder | download
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
/*
 * This file is part of KDevelop
 * Copyright 2012 Miha Čančula <miha@noughmad.eu>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "templaterenderer.h"

#include "documentchangeset.h"
#include "sourcefiletemplate.h"
#include "templateengine.h"
#include "templateengine_p.h"
#include "archivetemplateloader.h"
#include <debug.h>

#include <serialization/indexedstring.h>

#include <grantlee/context.h>

#include <QDir>
#include <QFile>
#include <QUrl>

#include <KArchive>

using namespace Grantlee;

class NoEscapeStream
    : public OutputStream
{
public:
    NoEscapeStream();
    explicit NoEscapeStream (QTextStream* stream);

    QString escape (const QString& input) const override;
    QSharedPointer<OutputStream> clone (QTextStream* stream) const override;
};

NoEscapeStream::NoEscapeStream() : OutputStream()
{
}

NoEscapeStream::NoEscapeStream(QTextStream* stream) : OutputStream(stream)
{
}

QString NoEscapeStream::escape(const QString& input) const
{
    return input;
}

QSharedPointer<OutputStream> NoEscapeStream::clone(QTextStream* stream) const
{
    QSharedPointer<OutputStream> clonedStream = QSharedPointer<OutputStream>(new NoEscapeStream(stream));
    return clonedStream;
}

using namespace KDevelop;

namespace KDevelop {
class TemplateRendererPrivate
{
public:
    Engine* engine;
    Grantlee::Context context;
    TemplateRenderer::EmptyLinesPolicy emptyLinesPolicy;
    QString errorString;
};
}

TemplateRenderer::TemplateRenderer()
    : d_ptr(new TemplateRendererPrivate)
{
    Q_D(TemplateRenderer);

    d->engine = &TemplateEngine::self()->d_ptr->engine;
    d->emptyLinesPolicy = KeepEmptyLines;
}

TemplateRenderer::~TemplateRenderer() = default;

void TemplateRenderer::addVariables(const QVariantHash& variables)
{
    Q_D(TemplateRenderer);

    QVariantHash::const_iterator it = variables.constBegin();
    QVariantHash::const_iterator end = variables.constEnd();
    for (; it != end; ++it) {
        d->context.insert(it.key(), it.value());
    }
}

void TemplateRenderer::addVariable(const QString& name, const QVariant& value)
{
    Q_D(TemplateRenderer);

    d->context.insert(name, value);
}

QVariantHash TemplateRenderer::variables() const
{
    Q_D(const TemplateRenderer);

    return d->context.stackHash(0);
}

QString TemplateRenderer::render(const QString& content, const QString& name)
{
    Q_D(TemplateRenderer);

    Template t = d->engine->newTemplate(content, name);

    QString output;
    QTextStream textStream(&output);
    NoEscapeStream stream(&textStream);
    t->render(&stream, &d->context);

    if (t->error() != Grantlee::NoError) {
        d->errorString = t->errorString();
    } else
    {
        d->errorString.clear();
    }

    if (d->emptyLinesPolicy == TrimEmptyLines && output.contains(QLatin1Char('\n'))) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
        QStringList lines = output.split(QLatin1Char('\n'), Qt::KeepEmptyParts);
#else
        QStringList lines = output.split(QLatin1Char('\n'), QString::KeepEmptyParts);
#endif
        QMutableStringListIterator it(lines);

        // Remove empty lines from the start of the document
        while (it.hasNext()) {
            if (it.next().trimmed().isEmpty()) {
                it.remove();
            } else
            {
                break;
            }
        }

        // Remove single empty lines
        it.toFront();
        bool prePreviousEmpty = false;
        bool previousEmpty = false;
        while (it.hasNext()) {
            bool currentEmpty = it.peekNext().trimmed().isEmpty();
            if (!prePreviousEmpty && previousEmpty && !currentEmpty) {
                it.remove();
            }
            prePreviousEmpty = previousEmpty;
            previousEmpty = currentEmpty;
            it.next();
        }

        // Compress multiple empty lines
        it.toFront();
        previousEmpty = false;
        while (it.hasNext()) {
            bool currentEmpty = it.next().trimmed().isEmpty();
            if (currentEmpty && previousEmpty) {
                it.remove();
            }
            previousEmpty = currentEmpty;
        }

        // Remove empty lines from the end
        it.toBack();
        while (it.hasPrevious()) {
            if (it.previous().trimmed().isEmpty()) {
                it.remove();
            } else
            {
                break;
            }
        }

        // Add a newline to the end of file
        it.toBack();
        it.insert(QString());

        output = lines.join(QLatin1Char('\n'));
    } else if (d->emptyLinesPolicy == RemoveEmptyLines) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
        QStringList lines = output.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
#else
        QStringList lines = output.split(QLatin1Char('\n'), QString::SkipEmptyParts);
#endif
        QMutableStringListIterator it(lines);
        while (it.hasNext()) {
            if (it.next().trimmed().isEmpty()) {
                it.remove();
            }
        }
        it.toBack();
        if (lines.size() > 1) {
            it.insert(QString());
        }
        output = lines.join(QLatin1Char('\n'));
    }

    return output;
}

QString TemplateRenderer::renderFile(const QUrl& url, const QString& name)
{
    QFile file(url.toLocalFile());
    file.open(QIODevice::ReadOnly);

    const QString content = QString::fromUtf8(file.readAll());
    qCDebug(LANGUAGE) << content;

    return render(content, name);
}

QStringList TemplateRenderer::render(const QStringList& contents)
{
    Q_D(TemplateRenderer);

    qCDebug(LANGUAGE) << d->context.stackHash(0);
    QStringList ret;
    ret.reserve(contents.size());
    for (const QString& content : contents) {
        ret << render(content);
    }

    return ret;
}

void TemplateRenderer::setEmptyLinesPolicy(TemplateRenderer::EmptyLinesPolicy policy)
{
    Q_D(TemplateRenderer);

    d->emptyLinesPolicy = policy;
}

TemplateRenderer::EmptyLinesPolicy TemplateRenderer::emptyLinesPolicy() const
{
    Q_D(const TemplateRenderer);

    return d->emptyLinesPolicy;
}

DocumentChangeSet TemplateRenderer::renderFileTemplate(const SourceFileTemplate& fileTemplate,
                                                       const QUrl& baseUrl,
                                                       const QHash<QString, QUrl>& fileUrls)
{
    DocumentChangeSet changes;
    const QDir baseDir(baseUrl.path());

    QRegExp nonAlphaNumeric(QStringLiteral("\\W"));
    for (QHash<QString, QUrl>::const_iterator it = fileUrls.constBegin(); it != fileUrls.constEnd(); ++it) {
        QString cleanName = it.key().toLower();
        cleanName.replace(nonAlphaNumeric, QStringLiteral("_"));
        const QString path = it.value().toLocalFile();
        addVariable(QLatin1String("output_file_") + cleanName, baseDir.relativeFilePath(path));
        addVariable(QLatin1String("output_file_") + cleanName + QLatin1String("_absolute"), path);
    }

    const KArchiveDirectory* directory = fileTemplate.directory();
    ArchiveTemplateLocation location(directory);
    const auto outputFiles = fileTemplate.outputFiles();
    for (const SourceFileTemplate::OutputFile& outputFile : outputFiles) {
        const KArchiveEntry* entry = directory->entry(outputFile.fileName);
        if (!entry) {
            qCWarning(LANGUAGE) << "Entry" << outputFile.fileName << "is mentioned in group" << outputFile.identifier <<
                "but is not present in the archive";
            continue;
        }

        const auto* file = dynamic_cast<const KArchiveFile*>(entry);
        if (!file) {
            qCWarning(LANGUAGE) << "Entry" << entry->name() << "is not a file";
            continue;
        }

        QUrl url = fileUrls[outputFile.identifier];
        IndexedString document(url);
        KTextEditor::Range range(KTextEditor::Cursor(0, 0), 0);

        DocumentChange change(document, range, QString(),
            render(QString::fromUtf8(file->data()), outputFile.identifier));
        changes.addChange(change);
        qCDebug(LANGUAGE) << "Added change for file" << document.str();
    }

    return changes;
}

QString TemplateRenderer::errorString() const
{
    Q_D(const TemplateRenderer);

    return d->errorString;
}