builddirmanager.cpp 12.4 KB
Newer Older
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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/

#include "builddirmanager.h"
27
#include "cmakebuildconfiguration.h"
28
#include "cmakekitinformation.h"
29
#include "cmakeparser.h"
30
#include "cmakeprojectmanager.h"
31
#include "cmakeprojectnodes.h"
32 33
#include "cmaketool.h"

34
#include <coreplugin/icore.h>
35
#include <coreplugin/documentmanager.h>
36
#include <coreplugin/messagemanager.h>
37
#include <coreplugin/editormanager/editormanager.h>
38
#include <coreplugin/progressmanager/progressmanager.h>
39 40
#include <cpptools/projectpartbuilder.h>
#include <projectexplorer/headerpath.h>
41
#include <projectexplorer/kit.h>
42
#include <projectexplorer/kitinformation.h>
43
#include <projectexplorer/project.h>
44 45
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectnodes.h>
46
#include <projectexplorer/target.h>
47
#include <projectexplorer/taskhub.h>
48
#include <projectexplorer/toolchain.h>
49 50

#include <utils/algorithm.h>
51
#include <utils/fileutils.h>
52
#include <utils/qtcassert.h>
53
#include <utils/qtcprocess.h>
54 55 56
#include <utils/synchronousprocess.h>

#include <QDateTime>
Tobias Hunger's avatar
Tobias Hunger committed
57
#include <QFile>
58
#include <QFileInfo>
59
#include <QMessageBox>
60 61 62 63
#include <QRegularExpression>
#include <QSet>
#include <QTemporaryDir>

64 65
using namespace ProjectExplorer;

66 67 68 69 70 71 72
namespace CMakeProjectManager {
namespace Internal {

// --------------------------------------------------------------------
// BuildDirManager:
// --------------------------------------------------------------------

73
BuildDirManager::BuildDirManager(CMakeBuildConfiguration *bc) :
74
    m_buildConfiguration(bc)
75
{
76
    QTC_ASSERT(bc, return);
77

78
    m_reparseTimer.setSingleShot(true);
79

80
    connect(&m_reparseTimer, &QTimer::timeout, this, &BuildDirManager::parse);
81 82
}

83 84
BuildDirManager::~BuildDirManager() = default;

85 86
const Utils::FileName BuildDirManager::workDirectory() const
{
87
    const Utils::FileName bdir = m_buildConfiguration->buildDirectory();
88 89
    if (bdir.exists())
        return bdir;
90 91 92 93 94 95
    if (!m_tempDir) {
        const QString path = QDir::tempPath() + QLatin1String("/qtc-cmake-XXXXXX");
        m_tempDir.reset(new QTemporaryDir(path));
        if (!m_tempDir->isValid())
            emit errorOccured(tr("Failed to create temporary directory using template \"%1\".").arg(path));
    }
96
    return Utils::FileName::fromString(m_tempDir->path());
97 98
}

99
void BuildDirManager::updateReaderType(std::function<void()> todo)
100
{
101 102
    BuildDirReader::Parameters p(m_buildConfiguration);
    p.buildDirectory = workDirectory();
103

104 105 106 107 108 109 110 111 112 113 114
    if (!m_reader || !m_reader->isCompatible(p)) {
        m_reader.reset(BuildDirReader::createReader(p));
        connect(m_reader.get(), &BuildDirReader::configurationStarted,
                this, &BuildDirManager::configurationStarted);
        connect(m_reader.get(), &BuildDirReader::dataAvailable,
                this, &BuildDirManager::dataAvailable);
        connect(m_reader.get(), &BuildDirReader::errorOccured,
                this, &BuildDirManager::errorOccured);
        connect(m_reader.get(), &BuildDirReader::dirty, this, &BuildDirManager::becameDirty);
    }
    m_reader->setParameters(p);
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

    if (m_reader->isReady())
        todo();
    else
        connect(m_reader.get(), &BuildDirReader::isReadyNow, this, todo);
}

void BuildDirManager::updateReaderData()
{
    BuildDirReader::Parameters p(m_buildConfiguration);
    p.buildDirectory = workDirectory();

    m_reader->setParameters(p);
}

void BuildDirManager::parseOnceReaderReady(bool force)
{
    checkConfiguration();
    m_reader->stop();
    m_reader->parse(force);
}

void BuildDirManager::maybeForceReparseOnceReaderReady()
{
    checkConfiguration();

    const QByteArray GENERATOR_KEY = "CMAKE_GENERATOR";
    const QByteArray EXTRA_GENERATOR_KEY = "CMAKE_EXTRA_GENERATOR";
    const QByteArray CMAKE_COMMAND_KEY = "CMAKE_COMMAND";

    const QByteArrayList criticalKeys
            = QByteArrayList() << GENERATOR_KEY << CMAKE_COMMAND_KEY;

    if (!m_reader->hasData()) {
        forceReparse();
        return;
    }

    const CMakeConfig currentConfig = parsedConfiguration();

    Kit *k = m_buildConfiguration->target()->kit();
    const CMakeTool *tool = CMakeKitInformation::cmakeTool(k);
    QTC_ASSERT(tool, return); // No cmake... we should not have ended up here in the first place
    const QString extraKitGenerator = CMakeGeneratorKitInformation::extraGenerator(k);
    const QString mainKitGenerator = CMakeGeneratorKitInformation::generator(k);
    CMakeConfig targetConfig = m_buildConfiguration->cmakeConfiguration();
    targetConfig.append(CMakeConfigItem(GENERATOR_KEY, CMakeConfigItem::INTERNAL,
                                        QByteArray(), mainKitGenerator.toUtf8()));
    if (!extraKitGenerator.isEmpty())
        targetConfig.append(CMakeConfigItem(EXTRA_GENERATOR_KEY, CMakeConfigItem::INTERNAL,
                                            QByteArray(), extraKitGenerator.toUtf8()));
    targetConfig.append(CMakeConfigItem(CMAKE_COMMAND_KEY, CMakeConfigItem::INTERNAL,
                                        QByteArray(), tool->cmakeExecutable().toUserOutput().toUtf8()));
    Utils::sort(targetConfig, CMakeConfigItem::sortOperator());

    bool mustReparse = false;
    auto ccit = currentConfig.constBegin();
    auto kcit = targetConfig.constBegin();

    while (ccit != currentConfig.constEnd() && kcit != targetConfig.constEnd()) {
        if (ccit->key == kcit->key) {
            if (ccit->value != kcit->value) {
                if (criticalKeys.contains(kcit->key)) {
                        clearCache();
                        return;
                }
                mustReparse = true;
            }
            ++ccit;
            ++kcit;
        } else {
            if (ccit->key < kcit->key) {
                ++ccit;
            } else {
                ++kcit;
                mustReparse = true;
            }
        }
    }

    // If we have keys that do not exist yet, then reparse.
    //
    // The critical keys *must* be set in cmake configuration, so those were already
    // handled above.
    if (mustReparse || kcit != targetConfig.constEnd())
        parseOnceReaderReady(true);
201 202 203
}

bool BuildDirManager::isParsing() const
204
{
205
    return m_reader && m_reader->isParsing();
206 207
}

208
void BuildDirManager::becameDirty()
209 210 211 212
{
    if (isParsing())
        return;

213 214 215 216 217 218
    Target *t = m_buildConfiguration->target()->project()->activeTarget();
    BuildConfiguration *bc = t ? t->activeBuildConfiguration() : nullptr;

    if (bc != m_buildConfiguration)
        return;

219 220 221 222
    const CMakeTool *tool = CMakeKitInformation::cmakeTool(m_buildConfiguration->target()->kit());
    if (!tool->isAutoRun())
        return;

223
    m_reparseTimer.start(1000);
224 225
}

226 227
void BuildDirManager::forceReparse()
{
228 229 230
    if (m_buildConfiguration->target()->activeBuildConfiguration() != m_buildConfiguration)
        return;

231
    CMakeTool *tool = CMakeKitInformation::cmakeTool(m_buildConfiguration->target()->kit());
232 233
    QTC_ASSERT(tool, return);

234
    m_reader.reset(); // Force reparse by forcing in a new reader
235
    updateReaderType([this]() { parseOnceReaderReady(true); });
236 237
}

238
void BuildDirManager::resetData()
239
{
240 241
    if (m_reader)
        m_reader->resetData();
242

Tobias Hunger's avatar
Tobias Hunger committed
243
    m_cmakeCache.clear();
244 245

    m_reader.reset(nullptr);
246 247
}

248 249 250 251 252
bool BuildDirManager::updateCMakeStateBeforeBuild()
{
    return m_reparseTimer.isActive();
}

253 254 255 256 257
bool BuildDirManager::persistCMakeState()
{
    if (!m_tempDir)
        return false;

258 259 260
    const QString buildDir = m_buildConfiguration->buildDirectory().toString();
    QDir dir(buildDir);
    dir.mkpath(buildDir);
261

262
    m_tempDir.reset(nullptr);
263

264
    QTimer::singleShot(0, this, &BuildDirManager::parse); // make sure signals only happen afterwards!
265 266 267
    return true;
}

268 269
void BuildDirManager::generateProjectTree(CMakeProjectNode *root)
{
270 271
    QTC_ASSERT(m_reader, return);
    m_reader->generateProjectTree(root);
272 273
}

274 275
QSet<Core::Id> BuildDirManager::updateCodeModel(CppTools::ProjectPartBuilder &ppBuilder)
{
276 277
    QTC_ASSERT(m_reader, return QSet<Core::Id>());
    return m_reader->updateCodeModel(ppBuilder);
278 279
}

280 281
void BuildDirManager::parse()
{
282
    updateReaderType([this]() { parseOnceReaderReady(false); });
283 284
}

285 286
void BuildDirManager::clearCache()
{
287 288
    auto cmakeCache = Utils::FileName(workDirectory()).appendPath(QLatin1String("CMakeCache.txt"));
    auto cmakeFiles = Utils::FileName(workDirectory()).appendPath(QLatin1String("CMakeFiles"));
289 290 291 292 293 294 295 296 297 298 299

    const bool mustCleanUp = cmakeCache.exists() || cmakeFiles.exists();
    if (!mustCleanUp)
        return;

    Utils::FileUtils::removeRecursively(cmakeCache);
    Utils::FileUtils::removeRecursively(cmakeFiles);

    forceReparse();
}

300 301
QList<CMakeBuildTarget> BuildDirManager::buildTargets() const
{
302 303
    QTC_ASSERT(m_reader, return QList<CMakeBuildTarget>());
    return m_reader->buildTargets();
304 305
}

Tobias Hunger's avatar
Tobias Hunger committed
306
CMakeConfig BuildDirManager::parsedConfiguration() const
Tobias Hunger's avatar
Tobias Hunger committed
307
{
308 309 310
    QTC_ASSERT(m_reader, return m_cmakeCache);
    if (m_cmakeCache.isEmpty())
        m_cmakeCache = m_reader->parsedConfiguration();
Tobias Hunger's avatar
Tobias Hunger committed
311
    return m_cmakeCache;
Tobias Hunger's avatar
Tobias Hunger committed
312 313
}

314 315 316 317 318
void BuildDirManager::checkConfiguration()
{
    if (m_tempDir) // always throw away changes in the tmpdir!
        return;

319
    Kit *k = m_buildConfiguration->target()->kit();
320
    const CMakeConfig cache = m_reader->parsedConfiguration();
321 322 323 324 325 326
    if (cache.isEmpty())
        return; // No cache file yet.

    CMakeConfig newConfig;
    QSet<QString> changedKeys;
    QSet<QString> removedKeys;
327
    foreach (const CMakeConfigItem &iBc, m_buildConfiguration->cmakeConfiguration()) {
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
        const CMakeConfigItem &iCache
                = Utils::findOrDefault(cache, [&iBc](const CMakeConfigItem &i) { return i.key == iBc.key; });
        if (iCache.isNull()) {
            removedKeys << QString::fromUtf8(iBc.key);
        } else if (QString::fromUtf8(iCache.value) != iBc.expandedValue(k)) {
            changedKeys << QString::fromUtf8(iBc.key);
            newConfig.append(iCache);
        } else {
            newConfig.append(iBc);
        }
    }

    if (!changedKeys.isEmpty() || !removedKeys.isEmpty()) {
        QSet<QString> total = removedKeys + changedKeys;
        QStringList keyList = total.toList();
        Utils::sort(keyList);
        QString table = QLatin1String("<table>");
        foreach (const QString &k, keyList) {
            QString change;
            if (removedKeys.contains(k))
                change = tr("<removed>");
            else
                change = QString::fromUtf8(CMakeConfigItem::valueOf(k.toUtf8(), cache)).trimmed();
            if (change.isEmpty())
                change = tr("<empty>");
            table += QString::fromLatin1("\n<tr><td>%1</td><td>%2</td></tr>").arg(k).arg(change.toHtmlEscaped());
        }
        table += QLatin1String("\n</table>");

        QPointer<QMessageBox> box = new QMessageBox(Core::ICore::mainWindow());
        box->setText(tr("CMake configuration has changed on disk."));
        box->setInformativeText(tr("The CMakeCache.txt file has changed: %1").arg(table));
360 361 362
        auto *defaultButton = box->addButton(tr("Overwrite Changes in CMake"), QMessageBox::RejectRole);
        box->addButton(tr("Apply Changes to Project"), QMessageBox::AcceptRole);
        box->setDefaultButton(defaultButton);
363 364

        int ret = box->exec();
365
        if (ret == QMessageBox::Apply) {
366
            m_buildConfiguration->setCMakeConfiguration(newConfig);
367
            updateReaderData(); // Apply changes to reader
368
        }
Tobias Hunger's avatar
Tobias Hunger committed
369
    }
370 371
}

372 373
void BuildDirManager::maybeForceReparse()
{
374
    updateReaderType([this]() { maybeForceReparseOnceReaderReady(); });
375 376
}

377 378
} // namespace Internal
} // namespace CMakeProjectManager