aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/corelib/buildgraph/transformerchangetracking.cpp
blob: 505f0cbbad9671c93a494a6c20dd89edda4a23d6 (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
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "transformerchangetracking.h"

#include "projectbuilddata.h"
#include "requesteddependencies.h"
#include "rulecommands.h"
#include "transformer.h"
#include <language/language.h>
#include <language/property.h>
#include <language/propertymapinternal.h>
#include <language/qualifiedid.h>
#include <logging/categories.h>
#include <tools/fileinfo.h>
#include <tools/qbsassert.h>
#include <tools/qttools.h>

#include <QtCore/qvariant.h>

namespace qbs {
namespace Internal {

class TrafoChangeTracker
{
public:
    TrafoChangeTracker(const Transformer *transformer,
                       const ResolvedProduct *product,
                       const std::unordered_map<QString, const ResolvedProduct *> &productsByName,
                       const std::unordered_map<QString, const ResolvedProject *> &projectsByName)
        : m_transformer(transformer),
          m_product(product),
          m_productsByName(productsByName),
          m_projectsByName(projectsByName)
    {
    }

    bool prepareScriptNeedsRerun() const;
    bool commandsNeedRerun() const;

private:
    QVariantMap propertyMapByKind(const Property &property) const;
    bool checkForPropertyChange(const Property &restoredProperty,
                                const QVariantMap &newProperties) const;
    bool checkForImportFileChange(const std::vector<QString> &importedFiles,
                                  const FileTime &referenceTime,
                                  const char *context) const;
    bool isExportedModuleUpToDate(const QString &productName, const ExportedModule &module) const;
    bool areExportedModulesUpToDate(
            const std::unordered_map<QString, ExportedModule> exportedModules) const;
    const Artifact *getArtifact(const QString &filePath, const QString &productName) const;
    const ResolvedProduct *getProduct(const QString &name) const;

    const Transformer * const m_transformer;
    const ResolvedProduct * const m_product;
    const std::unordered_map<QString, const ResolvedProduct *> &m_productsByName;
    const std::unordered_map<QString, const ResolvedProject *> &m_projectsByName;
    mutable const ResolvedProduct * m_lastProduct = nullptr;
    mutable const Artifact *m_lastArtifact = nullptr;
};

template<typename T> static QVariantMap getParameterValue(
        const QHash<T, QVariantMap> &parameters,
        const QString &depName)
{
    for (auto it = parameters.cbegin(); it != parameters.cend(); ++it) {
        if (it.key()->name == depName)
            return it.value();
    }
    return {};
}

QVariantMap TrafoChangeTracker::propertyMapByKind(const Property &property) const
{
    switch (property.kind) {
    case Property::PropertyInModule: {
        const ResolvedProduct * const p = getProduct(property.productName);
        return p ? p->moduleProperties->value() : QVariantMap();
    }
    case Property::PropertyInProduct: {
        const ResolvedProduct * const p = getProduct(property.productName);
        return p ? p->productProperties : QVariantMap();
    }
    case Property::PropertyInProject: {
        if (property.productName == m_product->project->name)
            return m_product->project->projectProperties();
        const auto it = m_projectsByName.find(property.productName);
        if (it != m_projectsByName.cend())
            return it->second->projectProperties();
        return {};
    }
    case Property::PropertyInParameters: {
        const int sepIndex = property.moduleName.indexOf(QLatin1Char(':'));
        const QString depName = property.moduleName.left(sepIndex);
        const ResolvedProduct * const p = getProduct(property.productName);
        if (!p)
            return {};
        QVariantMap v = getParameterValue(p->dependencyParameters, depName);
        if (!v.empty())
            return v;
        return getParameterValue(p->moduleParameters, depName);
    }
    case Property::PropertyInArtifact:
    default:
        QBS_CHECK(false);
    }
    return {};
}

bool TrafoChangeTracker::checkForPropertyChange(const Property &restoredProperty,
                                                const QVariantMap &newProperties) const
{
    QVariant v;
    switch (restoredProperty.kind) {
    case Property::PropertyInProduct:
    case Property::PropertyInProject:
        v = newProperties.value(restoredProperty.propertyName);
        break;
    case Property::PropertyInModule:
        v = moduleProperty(newProperties, restoredProperty.moduleName,
                           restoredProperty.propertyName);
        break;
    case Property::PropertyInParameters: {
        const int sepIndex = restoredProperty.moduleName.indexOf(QLatin1Char(':'));
        QualifiedId moduleName
                = QualifiedId::fromString(restoredProperty.moduleName.mid(sepIndex + 1));
        QVariantMap map = newProperties;
        while (!moduleName.empty())
            map = map.value(moduleName.takeFirst()).toMap();
        v = map.value(restoredProperty.propertyName);
        break;
    }
    case Property::PropertyInArtifact:
        QBS_CHECK(false);
    }
    if (restoredProperty.value != v) {
        qCDebug(lcBuildGraph).noquote().nospace()
                << "Value for property '" << restoredProperty.moduleName << "."
                << restoredProperty.propertyName << "' has changed.\n"
                << "Old value was '" << restoredProperty.value << "'.\n"
                << "New value is '" << v << "'.";
        return true;
    }
    return false;
}

bool TrafoChangeTracker::checkForImportFileChange(const std::vector<QString> &importedFiles,
                                                  const FileTime &referenceTime,
                                                  const char *context) const
{
    for (const QString &importedFile : importedFiles) {
        const FileInfo fi(importedFile);
        if (!fi.exists()) {
            qCDebug(lcBuildGraph) << context << "imported file" << importedFile
                                  << "is gone, need to re-run";
            return true;
        }
        if (fi.lastModified() > referenceTime) {
            qCDebug(lcBuildGraph) << context << "imported file" << importedFile
                                  << "has been updated, need to re-run"
                                  << fi.lastModified() << referenceTime;
            return true;
        }
    }
    return false;
}

bool TrafoChangeTracker::isExportedModuleUpToDate(const QString &productName,
                                                  const ExportedModule &module) const
{
    const ResolvedProduct * const product = getProduct(productName);
    if (!product) {
        qCDebug(lcBuildGraph) << "product" << productName
                              << "does not exist anymore, need to re-run";
        return false;
    }
    if (product->exportedModule != module) {
        qCDebug(lcBuildGraph) << "exported module has changed for product" << productName
                              << ", need to re-run";
        return false;
    }
    return true;
}

bool TrafoChangeTracker::areExportedModulesUpToDate(
        const std::unordered_map<QString, ExportedModule> exportedModules) const
{
    for (const auto &kv : exportedModules) {
        if (!isExportedModuleUpToDate(kv.first, kv.second))
            return false;
    }
    return true;
}

const Artifact *TrafoChangeTracker::getArtifact(const QString &filePath,
                                                const QString &productName) const
{
    if (m_lastArtifact && m_lastArtifact->filePath() == filePath
            && m_lastArtifact->product.get()->uniqueName() == productName) {
        return m_lastArtifact;
    }
    const ResolvedProduct * const product = getProduct(productName);
    if (!product)
        return nullptr;
    const auto &candidates = product->topLevelProject()->buildData->lookupFiles(filePath);
    const Artifact *artifact = nullptr;
    for (const FileResourceBase * const candidate : candidates) {
        if (candidate->fileType() == FileResourceBase::FileTypeArtifact) {
            auto const a = static_cast<const Artifact *>(candidate);
            if (a->product.get() == product) {
                m_lastArtifact = artifact = a;
                break;
            }
        }
    }
    return artifact;
}

const ResolvedProduct *TrafoChangeTracker::getProduct(const QString &name) const
{
    if (m_lastProduct && name == m_lastProduct->uniqueName())
        return m_lastProduct;
    if (name == m_product->uniqueName()) {
        m_lastProduct = m_product;
        return m_product;
    }
    const auto it = m_productsByName.find(name);
    if (it != m_productsByName.cend()) {
        m_lastProduct = it->second;
        return it->second;
    }
    return nullptr;
}

bool TrafoChangeTracker::prepareScriptNeedsRerun() const
{
    for (const Property &property : qAsConst(m_transformer->propertiesRequestedInPrepareScript)) {
        if (checkForPropertyChange(property, propertyMapByKind(property)))
            return true;
    }

    if (checkForImportFileChange(m_transformer->importedFilesUsedInPrepareScript,
                                 m_transformer->lastPrepareScriptExecutionTime, "prepare script")) {
        return true;
    }

    for (auto it = m_transformer->propertiesRequestedFromArtifactInPrepareScript.constBegin();
         it != m_transformer->propertiesRequestedFromArtifactInPrepareScript.constEnd(); ++it) {
        for (const Property &property : qAsConst(it.value())) {
            const Artifact * const artifact = getArtifact(it.key(), property.productName);
            if (!artifact)
                return true;
            if (property.kind == Property::PropertyInArtifact) {
                if (sorted(artifact->fileTags().toStringList()) != property.value.toStringList())
                    return true;
                continue;
            }
            if (checkForPropertyChange(property, artifact->properties->value()))
                return true;
        }
    }

    if (!m_transformer->depsRequestedInPrepareScript.isUpToDate(m_product->topLevelProject()))
        return true;
    if (!m_transformer->artifactsMapRequestedInPrepareScript.isUpToDate(
                m_product->topLevelProject())) {
        return true;
    }
    if (!areExportedModulesUpToDate(m_transformer->exportedModulesAccessedInPrepareScript))
        return true;

    return false;
}

bool TrafoChangeTracker::commandsNeedRerun() const
{
    for (const Property &property : qAsConst(m_transformer->propertiesRequestedInCommands)) {
        if (checkForPropertyChange(property, propertyMapByKind(property)))
            return true;
    }

    QMap<QString, SourceArtifactConstPtr> artifactMap;
    for (auto it = m_transformer->propertiesRequestedFromArtifactInCommands.cbegin();
         it != m_transformer->propertiesRequestedFromArtifactInCommands.cend(); ++it) {
        for (const Property &property : qAsConst(it.value())) {
            const Artifact * const artifact = getArtifact(it.key(), property.productName);
            if (!artifact)
                return true;
            if (property.kind == Property::PropertyInArtifact) {
                if (sorted(artifact->fileTags().toStringList()) != property.value.toStringList())
                    return true;
                continue;
            }
            if (checkForPropertyChange(property, artifact->properties->value()))
                return true;
        }
    }

    if (checkForImportFileChange(m_transformer->importedFilesUsedInCommands,
                                 m_transformer->lastCommandExecutionTime, "command")) {
        return true;
    }

    if (!m_transformer->depsRequestedInCommands.isUpToDate(m_product->topLevelProject()))
        return true;
    if (!m_transformer->artifactsMapRequestedInCommands.isUpToDate(m_product->topLevelProject()))
        return true;
    if (!areExportedModulesUpToDate(m_transformer->exportedModulesAccessedInCommands))
        return true;

    // TODO: Also track env access in JS commands and prepare scripts
    for (const AbstractCommandPtr &c : qAsConst(m_transformer->commands.commands())) {
        if (c->type() != AbstractCommand::ProcessCommandType)
            continue;
        const ProcessCommandPtr &processCmd = std::static_pointer_cast<ProcessCommand>(c);
        const auto envVars = processCmd->relevantEnvVars();
        for (const QString &var : envVars) {
            const QString &oldValue = processCmd->relevantEnvValue(var);
            const QString &newValue = m_product->buildEnvironment.value(var);
            if (oldValue != newValue) {
                qCDebug(lcBuildGraph) << "need to re-run command: value of environment variable"
                                      << var << "changed from" << oldValue << "to" << newValue
                                      << "for command" << processCmd->program() << "in rule"
                                      << m_transformer->rule->toString();
                return true;
            }
        }
    }

    return false;
}

bool prepareScriptNeedsRerun(
        Transformer *transformer, const ResolvedProduct *product,
        const std::unordered_map<QString, const ResolvedProduct *> &productsByName,
        const std::unordered_map<QString, const ResolvedProject *> &projectsByName)
{
    if (!transformer->prepareScriptNeedsChangeTracking)
        return false;
    transformer->prepareScriptNeedsChangeTracking = false;
    return TrafoChangeTracker(transformer, product, productsByName, projectsByName)
            .prepareScriptNeedsRerun();
}

bool commandsNeedRerun(Transformer *transformer, const ResolvedProduct *product,
                       const std::unordered_map<QString, const ResolvedProduct *> &productsByName,
                       const std::unordered_map<QString, const ResolvedProject *> &projectsByName)
{
    if (!transformer->commandsNeedChangeTracking)
        return false;
    transformer->commandsNeedChangeTracking = false;
    return TrafoChangeTracker(transformer, product, productsByName, projectsByName)
            .commandsNeedRerun();
}

} // namespace Internal
} // namespace qbs