aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/squish/suiteconf.cpp
blob: 17e7c383f52ae7116c3ca249434e5161a6ceea50 (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
// Copyright (C) 2022 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 "suiteconf.h"

#include "squishplugin.h"
#include "squishsettings.h"

#include <coreplugin/documentmanager.h>

#include <utils/algorithm.h>
#include <utils/qtcassert.h>

#include <QRegularExpression>

namespace Squish {
namespace Internal {

const char squishLanguageKey[] = "LANGUAGE";
const char squishTestCasesKey[] = "TEST_CASES";
const char squishAutKey[] = "AUT";
const char objectsMapKey[] = "OBJECTMAP";
const char objectMapStyleKey[] = "OBJECTMAPSTYLE";

// splits an input string into chunks separated by ws, but keeps quoted items without splitting
// them (quotes get removed inside the resulting list)
static QStringList parseHelper(const QStringView input)
{
    if (input.isEmpty())
        return {};

    QStringList result;
    QString chunk;

    auto appendChunk = [&]() {
        if (!chunk.isEmpty())
            result.append(chunk);
        chunk.clear();
    };

    bool inQuote = false;
    for (const QChar &inChar : input) {
        switch (inChar.toLatin1()) {
        case '"':
            appendChunk();
            inQuote = !inQuote;
            break;
        case ' ':
            if (!inQuote) {
                appendChunk();
                break;
            }
            Q_FALLTHROUGH();
        default:
            chunk.append(inChar);
        }
    }
    appendChunk();
    return result;
}

static QString quoteIfNeeded(const QString &input)
{
    if (input.contains(' '))
        return QString('"' + input + '"');
    return input;
}

// joins items, separating them by single ws and quoting items if needed
static QString joinItems(const QStringList &items)
{
    QStringList result;
    for (const QString &current : items)
        result.append(quoteIfNeeded(current));
    return result.join(' ');
}

static QMap<QString, QString> readSuiteConfContent(const Utils::FilePath &file)
{
    if (!file.isReadableFile())
        return {};

    std::optional<QByteArray> suiteConfContent = file.fileContents();
    if (!suiteConfContent)
        return {};

    QMap<QString, QString> suiteConf;
    int invalidCounter = 0;
    static const QRegularExpression validLine("^(?<key>[A-Z_]+)=(?<value>.*)$");
    for (const QByteArray &line : suiteConfContent->split('\n')) {
        const QString utf8Line = QString::fromUtf8(line.trimmed());
        if (utf8Line.isEmpty()) // skip empty lines
            continue;
        const QRegularExpressionMatch match = validLine.match(utf8Line);
        if (match.hasMatch())
            suiteConf.insert(match.captured("key"), match.captured("value"));
        else // save invalid lines
            suiteConf.insert(QString::number(++invalidCounter), utf8Line);
    }
    return suiteConf;
}

static bool writeSuiteConfContent(const Utils::FilePath &file, const QMap<QString, QString> &data)
{
    auto isNumber = [](const QString &str) {
        return !str.isEmpty() && Utils::allOf(str, &QChar::isDigit);
    };
    QByteArray outData;
    for (auto it = data.begin(), end = data.end(); it != end; ++it) {
        if (isNumber(it.key())) // an invalid line we just write out as we got it
            outData.append(it.value().toUtf8()).append('\n');
        else
            outData.append(it.key().toUtf8()).append('=').append(it.value().toUtf8()).append('\n');
    }
    return file.writeFileContents(outData);
}

bool SuiteConf::read()
{
    const QMap<QString, QString> suiteConf = readSuiteConfContent(m_filePath);

    // TODO get all information - actually only the information needed now is fetched
    const QStringList parsedAUT = parseHelper(suiteConf.value(squishAutKey));
    if (parsedAUT.isEmpty()) {
        m_aut.clear();
        m_arguments.clear();
    } else {
        m_aut = parsedAUT.first();
        if (parsedAUT.size() > 1)
            m_arguments = joinItems(parsedAUT.mid(1));
        else
            m_arguments.clear();
    }

    setLanguage(suiteConf.value(squishLanguageKey));
    m_testcases = suiteConf.value(squishTestCasesKey);
    m_objectMap = suiteConf.value(objectsMapKey);
    m_objectMapStyle = suiteConf.value(objectMapStyleKey);
    return true;
}

static QString languageEntry(Language language)
{
    switch (language) {
    case Language::Python: return "Python";
    case Language::Perl: return "Perl";
    case Language::JavaScript: return "JavaScript";
    case Language::Ruby: return "Ruby";
    case Language::Tcl: return "Tcl";
    }
    return {};
}

bool SuiteConf::write()
{
    Core::DocumentManager::expectFileChange(m_filePath);

    // we need the original suite.conf content to handle invalid content "correctly"
    QMap<QString, QString> suiteConf = readSuiteConfContent(m_filePath);
    if (m_arguments.isEmpty())
        suiteConf.insert(squishAutKey, quoteIfNeeded(m_aut));
    else if (QTC_GUARD(!m_aut.isEmpty()))
        suiteConf.insert(squishAutKey, QString(quoteIfNeeded(m_aut) + ' ' + m_arguments));

    suiteConf.insert(squishLanguageKey, languageEntry(m_language));
    suiteConf.insert(objectsMapKey, m_objectMap);
    if (!m_objectMap.isEmpty())
        suiteConf.insert(objectMapStyleKey, m_objectMapStyle);
    suiteConf.insert(squishTestCasesKey, m_testcases);

    return writeSuiteConfContent(m_filePath, suiteConf);
}

QString SuiteConf::langParameter() const
{
    switch (m_language) {
    case Language::Python: return "py";
    case Language::Perl: return "pl";
    case Language::JavaScript: return "js";
    case Language::Ruby: return "rb";
    case Language::Tcl: return "tcl";
    }
    return {};
}

Utils::FilePath SuiteConf::objectMapPath() const
{
    const Utils::FilePath suiteDir = m_filePath.parentDir();
    if (m_objectMapStyle == "script")
        return suiteDir.resolvePath("shared/scripts/names" + scriptExtension());

    return suiteDir.resolvePath(m_objectMap.isEmpty() ? QString{"objects.map"} : m_objectMap);
}

QString SuiteConf::scriptExtension() const
{
    return '.' + langParameter(); // for now okay
}

QStringList SuiteConf::testCases() const
{
    return parseHelper(m_testcases);
}

QStringList SuiteConf::usedTestCases() const
{
    QStringList result = testCases();

    auto suiteDir = m_filePath.parentDir();
    const Utils::FilePaths entries = Utils::filtered(
                suiteDir.dirEntries(QDir::Dirs | QDir::NoDotAndDotDot),
                [](const Utils::FilePath &fp) {
        return fp.fileName().startsWith("tst_");
    });
    const QStringList testCaseNames = Utils::transform(entries, &Utils::FilePath::fileName);
    for (const QString &testCaseName : testCaseNames) {
        if (result.contains(testCaseName))
            continue;
        result.append(testCaseName); // should this check for test.*?
    }
    return result;
}

void SuiteConf::addTestCase(const QString &name)
{
    QStringList current = testCases();
    int insertAt = 0;
    for (int count = current.count(); insertAt < count; ++insertAt) {
        if (current.at(insertAt) > name)
            break;
    }
    current.insert(insertAt, name);
    m_testcases = joinItems(current);
}

void SuiteConf::setLanguage(const QString &language)
{
    if (language == "Python")
        m_language = Language::Python;
    else if (language == "Perl")
        m_language = Language::Perl;
    else if (language == "JavaScript")
        m_language = Language::JavaScript;
    else if (language == "Ruby")
        m_language = Language::Ruby;
    else if (language == "Tcl")
        m_language = Language::Tcl;
    else
        QTC_ASSERT(false, m_language = Language::JavaScript);
}

QStringList SuiteConf::validTestCases(const QString &baseDirectory)
{
    QStringList validCases;
    const Utils::FilePath subDir = Utils::FilePath::fromString(baseDirectory);
    const Utils::FilePath suiteConf = subDir / "suite.conf";
    if (suiteConf.exists()) {
        const SuiteConf conf = readSuiteConf(suiteConf);
        const QString extension = conf.scriptExtension();
        const QStringList cases = conf.testCases();

        for (const QString &testCase : cases) {
            const Utils::FilePath testCaseDir = subDir / testCase;
            if (testCaseDir.isDir()) {
                Utils::FilePath testCaseTest = testCaseDir.pathAppended("test" + extension);
                validCases.append(testCaseTest.toString());
            }
        }

        // now unlisted matching tests (suite.conf's TEST_CASES is used for some ordering)
        const Utils::FilePaths entries = subDir.dirEntries(QDir::Dirs | QDir::NoDotAndDotDot);
        for (const Utils::FilePath &entry : entries) {
            if (!entry.fileName().startsWith("tst_"))
                continue;
            const QString testFileStr = entry.pathAppended("test" + extension).toString();
            if (!validCases.contains(testFileStr))
                validCases.append(testFileStr);
        }
    }
    return validCases;
}

SuiteConf SuiteConf::readSuiteConf(const Utils::FilePath &suiteConfPath)
{
    SuiteConf suiteConf(suiteConfPath);
    suiteConf.read();
    return suiteConf;
}

bool SuiteConf::ensureObjectMapExists() const
{
    if (m_objectMapStyle != "script") {
        const Utils::FilePath objectMap = objectMapPath();
        return objectMap.parentDir().ensureWritableDir() && objectMap.ensureExistingFile();
    }

    const Utils::FilePath scripts = SquishPlugin::squishSettings()->scriptsPath(language());
    QTC_ASSERT(scripts.exists(), return false);

    const QString extension = scriptExtension();
    const Utils::FilePath destinationObjectMap = m_filePath.parentDir()
            .pathAppended("shared/scripts/names" + extension);
    if (destinationObjectMap.exists()) // do not overwrite existing
        return true;

    const Utils::FilePath objectMap = scripts.pathAppended("objectmap_template" + extension);
    bool ok = destinationObjectMap.parentDir().ensureWritableDir();
    QTC_ASSERT(ok, return false);
    ok = objectMap.copyFile(destinationObjectMap);
    QTC_ASSERT(ok, return false);
    return ok;
}

} // namespace Internal
} // namespace Squish