builddirmanager.cpp 15.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 27
/****************************************************************************
**
** 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"
#include "cmakekitinformation.h"
28
#include "cmakeparser.h"
29 30 31 32
#include "cmakeprojectmanager.h"
#include "cmaketool.h"

#include <coreplugin/messagemanager.h>
33
#include <coreplugin/progressmanager/progressmanager.h>
34 35 36 37 38 39 40
#include <projectexplorer/kit.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectnodes.h>
#include <projectexplorer/taskhub.h>

#include <utils/algorithm.h>
#include <utils/qtcassert.h>
41
#include <utils/qtcprocess.h>
42 43 44
#include <utils/synchronousprocess.h>

#include <QDateTime>
Tobias Hunger's avatar
Tobias Hunger committed
45
#include <QFile>
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
#include <QFileInfo>
#include <QFileSystemWatcher>
#include <QRegularExpression>
#include <QSet>
#include <QTemporaryDir>
#include <QTimer>

// --------------------------------------------------------------------
// Helper:
// --------------------------------------------------------------------

namespace CMakeProjectManager {
namespace Internal {

static QStringList toArguments(const CMakeConfig &config) {
    return Utils::transform(config, [](const CMakeConfigItem &i) -> QString {
                                 QString a = QString::fromLatin1("-D");
                                 a.append(QString::fromUtf8(i.key));
                                 switch (i.type) {
                                 case CMakeConfigItem::FILEPATH:
                                     a.append(QLatin1String(":FILEPATH="));
                                     break;
                                 case CMakeConfigItem::PATH:
                                     a.append(QLatin1String(":PATH="));
                                     break;
                                 case CMakeConfigItem::BOOL:
                                     a.append(QLatin1String(":BOOL="));
                                     break;
                                 case CMakeConfigItem::STRING:
                                     a.append(QLatin1String(":STRING="));
                                     break;
                                 case CMakeConfigItem::INTERNAL:
                                     a.append(QLatin1String(":INTERNAL="));
                                     break;
                                 }
                                 a.append(QString::fromUtf8(i.value));

                                 return a;
                             });
}

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

BuildDirManager::BuildDirManager(const Utils::FileName &sourceDir, const ProjectExplorer::Kit *k,
                                 const CMakeConfig &inputConfig, const Utils::Environment &env,
                                 const Utils::FileName &buildDir) :
    m_sourceDir(sourceDir),
    m_buildDir(buildDir),
    m_kit(k),
    m_environment(env),
    m_inputConfig(inputConfig),
    m_watcher(new QFileSystemWatcher(this))
{
    QTC_CHECK(!sourceDir.isEmpty());
    m_projectName = m_sourceDir.fileName();
    if (m_buildDir.isEmpty()) {
        m_tempDir = new QTemporaryDir(QLatin1String("cmake-tmp-XXXXXX"));
        m_buildDir = Utils::FileName::fromString(m_tempDir->path());
    }
    QTC_CHECK(!m_buildDir.isEmpty());
    QTC_CHECK(k);

    connect(m_watcher, &QFileSystemWatcher::fileChanged, this, [this]() {
        if (!isBusy())
            forceReparse();
    });

    QTimer::singleShot(0, this, &BuildDirManager::parse);
}

BuildDirManager::~BuildDirManager()
{
    delete m_tempDir;
}

bool BuildDirManager::isBusy() const
{
    if (m_cmakeProcess)
        return m_cmakeProcess->state() != QProcess::NotRunning;
    return false;
}

void BuildDirManager::forceReparse()
{
    CMakeTool *tool = CMakeKitInformation::cmakeTool(m_kit);
    const QString generator = CMakeGeneratorKitInformation::generator(m_kit);

    QTC_ASSERT(tool, return);
    QTC_ASSERT(!generator.isEmpty(), return);

    startCMake(tool, generator, m_inputConfig);
}

141 142 143 144 145 146
void BuildDirManager::setInputConfiguration(const CMakeConfig &config)
{
    m_inputConfig = config;
    forceReparse();
}

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
void BuildDirManager::parse()
{
    CMakeTool *tool = CMakeKitInformation::cmakeTool(m_kit);
    const QString generator = CMakeGeneratorKitInformation::generator(m_kit);

    QTC_ASSERT(tool, return);
    QTC_ASSERT(!generator.isEmpty(), return);

    // Pop up a dialog asking the user to rerun cmake
    QString cbpFile = CMakeManager::findCbpFile(QDir(m_buildDir.toString()));
    QFileInfo cbpFileFi(cbpFile);

    if (!cbpFileFi.exists()) {
        // Initial create:
        startCMake(tool, generator, m_inputConfig);
        return;
    }

    const bool mustUpdate
            = Utils::anyOf(m_watchedFiles, [&cbpFileFi](const Utils::FileName &f) {
                  return f.toFileInfo().lastModified() > cbpFileFi.lastModified();
              });
    if (mustUpdate) {
        startCMake(tool, generator, CMakeConfig());
    } else {
        extractData();
        emit dataAvailable();
    }
}

bool BuildDirManager::isProjectFile(const Utils::FileName &fileName) const
{
    return m_watchedFiles.contains(fileName);
}

QString BuildDirManager::projectName() const
{
    return m_projectName;
}

QList<CMakeBuildTarget> BuildDirManager::buildTargets() const
{
    return m_buildTargets;
}

QList<ProjectExplorer::FileNode *> BuildDirManager::files() const
{
    return m_files;
}

Tobias Hunger's avatar
Tobias Hunger committed
197 198 199 200 201
CMakeConfig BuildDirManager::configuration() const
{
    return parseConfiguration();
}

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
void BuildDirManager::extractData()
{
    const Utils::FileName topCMake
            = Utils::FileName::fromString(m_sourceDir.toString() + QLatin1String("/CMakeLists.txt"));

    m_projectName = m_sourceDir.fileName();
    m_buildTargets.clear();
    m_watchedFiles.clear();
    m_files.clear();
    m_files.append(new ProjectExplorer::FileNode(topCMake, ProjectExplorer::ProjectFileType, false));
    m_watchedFiles.insert(topCMake);

    foreach (const QString &file, m_watcher->files())
        m_watcher->removePath(file);

    // Find cbp file
    QString cbpFile = CMakeManager::findCbpFile(m_buildDir.toString());
    if (cbpFile.isEmpty())
        return;

    m_watcher->addPath(cbpFile);

    // setFolderName
    CMakeCbpParser cbpparser;
    // Parsing
    if (!cbpparser.parseCbpFile(m_kit, cbpFile, m_sourceDir.toString()))
        return;

    m_projectName = cbpparser.projectName();

    m_files = cbpparser.fileList();
    QSet<Utils::FileName> projectFiles;
    if (cbpparser.hasCMakeFiles()) {
        m_files.append(cbpparser.cmakeFileList());
        foreach (const ProjectExplorer::FileNode *node, cbpparser.cmakeFileList())
            projectFiles.insert(node->filePath());
    } else {
        m_files.append(new ProjectExplorer::FileNode(topCMake, ProjectExplorer::ProjectFileType, false));
        projectFiles.insert(topCMake);
    }

    m_watchedFiles = projectFiles;
    foreach (const Utils::FileName &f, m_watchedFiles)
        m_watcher->addPath(f.toString());

    m_buildTargets = cbpparser.buildTargets();
}

void BuildDirManager::startCMake(CMakeTool *tool, const QString &generator,
                                 const CMakeConfig &config)
{
    QTC_ASSERT(tool && tool->isValid(), return);
    QTC_ASSERT(!m_cmakeProcess, return);
255
    QTC_ASSERT(!m_parser, return);
256
    QTC_ASSERT(!m_future, return);
257 258 259 260 261 262

    // Make sure m_buildDir exists:
    const QString buildDirStr = m_buildDir.toString();
    QDir bDir = QDir(buildDirStr);
    bDir.mkpath(buildDirStr);

263 264 265 266 267 268 269 270 271 272 273 274 275
    m_parser = new CMakeParser;
    QDir source = QDir(m_sourceDir.toString());
    connect(m_parser, &ProjectExplorer::IOutputParser::addTask, m_parser,
            [source](const ProjectExplorer::Task &task) {
                if (task.file.isEmpty() || task.file.toFileInfo().isAbsolute()) {
                    ProjectExplorer::TaskHub::addTask(task);
                } else {
                    ProjectExplorer::Task t = task;
                    t.file = Utils::FileName::fromString(source.absoluteFilePath(task.file.toString()));
                    ProjectExplorer::TaskHub::addTask(t);
                }
            });

276 277 278 279 280 281 282 283 284 285
    // Always use the sourceDir: If we are triggered because the build directory is getting deleted
    // then we are racing against CMakeCache.txt also getting deleted.
    const QString srcDir = m_sourceDir.toString();

    m_cmakeProcess = new Utils::QtcProcess(this);
    m_cmakeProcess->setWorkingDirectory(buildDirStr);
    m_cmakeProcess->setEnvironment(m_environment);

    connect(m_cmakeProcess, &QProcess::readyReadStandardOutput,
            this, &BuildDirManager::processCMakeOutput);
286 287
    connect(m_cmakeProcess, &QProcess::readyReadStandardError,
            this, &BuildDirManager::processCMakeError);
288 289 290 291 292 293 294 295 296 297 298
    connect(m_cmakeProcess, static_cast<void(QProcess::*)(int,  QProcess::ExitStatus)>(&QProcess::finished),
            this, &BuildDirManager::cmakeFinished);

    QString args;
    Utils::QtcProcess::addArg(&args, srcDir);
    if (!generator.isEmpty())
        Utils::QtcProcess::addArg(&args, QString::fromLatin1("-G%1").arg(generator));
    Utils::QtcProcess::addArgs(&args, toArguments(config));

    ProjectExplorer::TaskHub::clearTasks(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);

299 300 301 302 303 304 305 306 307 308 309
    Core::MessageManager::write(tr("Running '%1 %2' in %3.")
                                .arg(tool->cmakeExecutable().toUserOutput())
                                .arg(args)
                                .arg(m_buildDir.toUserOutput()));

    m_future = new QFutureInterface<void>();
    m_future->setProgressRange(0, 1);
    Core::ProgressManager::addTask(m_future->future(),
                                   tr("Configuring \"%1\"").arg(projectName()),
                                   "CMake.Configure");

310 311 312 313 314 315 316 317 318 319
    m_cmakeProcess->setCommand(tool->cmakeExecutable().toString(), args);
    m_cmakeProcess->start();
    emit parsingStarted();
}

void BuildDirManager::cmakeFinished(int code, QProcess::ExitStatus status)
{
    QTC_ASSERT(m_cmakeProcess, return);

    // process rest of the output:
320 321
    processCMakeOutput();
    processCMakeError();
322

323 324 325
    m_parser->flush();
    delete m_parser;
    m_parser = nullptr;
326 327 328 329 330 331

    m_cmakeProcess->deleteLater();
    m_cmakeProcess = nullptr;

    extractData(); // try even if cmake failed...

332
    QString msg;
333
    if (status != QProcess::NormalExit)
334
        msg = tr("*** cmake process crashed!");
335
    else if (code != 0)
336 337 338 339 340 341
        msg = tr("*** cmake process exited with exit code %1.").arg(code);

    if (!msg.isEmpty()) {
        Core::MessageManager::write(msg);
        ProjectExplorer::TaskHub::addTask(ProjectExplorer::Task::Error, msg,
                                          ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);
342 343 344
        m_future->reportCanceled();
    } else {
        m_future->setProgressValue(1);
345 346
    }

347 348 349 350
    m_future->reportFinished();
    delete m_future;
    m_future = 0;

351 352 353
    emit dataAvailable();
}

354 355 356 357 358 359 360 361 362 363 364 365 366
static QString lineSplit(const QString &rest, const QByteArray &array, std::function<void(const QString &)> f)
{
    QString tmp = rest + Utils::SynchronousProcess::normalizeNewlines(QString::fromLocal8Bit(array));
    int start = 0;
    int end = tmp.indexOf(QLatin1Char('\n'), start);
    while (end >= 0) {
        f(tmp.mid(start, end - start));
        start = end + 1;
        end = tmp.indexOf(QLatin1Char('\n'), start);
    }
    return tmp.mid(start);
}

367 368
void BuildDirManager::processCMakeOutput()
{
369 370
    static QString rest;
    rest = lineSplit(rest, m_cmakeProcess->readAllStandardOutput(), [this](const QString &s) { Core::MessageManager::write(s); });
371 372
}

373
void BuildDirManager::processCMakeError()
374
{
375 376 377 378 379
    static QString rest;
    rest = lineSplit(rest, m_cmakeProcess->readAllStandardError(), [this](const QString &s) {
        m_parser->stdError(s);
        Core::MessageManager::write(s);
    });
380 381
}

Tobias Hunger's avatar
Tobias Hunger committed
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
static QByteArray trimCMakeCacheLine(const QByteArray &in) {
    int start = 0;
    while (start < in.count() && (in.at(start) == ' ' || in.at(start) == '\t'))
        ++start;

    return in.mid(start, in.count() - start - 1);
}

static QByteArrayList splitCMakeCacheLine(const QByteArray &line) {
    const int colonPos = line.indexOf(':');
    if (colonPos < 0)
        return QByteArrayList();

    const int equalPos = line.indexOf('=', colonPos + 1);
    if (equalPos < colonPos)
        return QByteArrayList();

    return QByteArrayList() << line.mid(0, colonPos)
                            << line.mid(colonPos + 1, equalPos - colonPos - 1)
                            << line.mid(equalPos + 1);
}

static CMakeConfigItem::Type fromByteArray(const QByteArray &type) {
    if (type == "BOOL")
        return CMakeConfigItem::BOOL;
    if (type == "STRING")
        return CMakeConfigItem::STRING;
    if (type == "FILEPATH")
        return CMakeConfigItem::FILEPATH;
    if (type == "PATH")
        return CMakeConfigItem::PATH;
    QTC_CHECK(type == "INTERNAL" || type == "STATIC");

    return CMakeConfigItem::INTERNAL;
}

CMakeConfig BuildDirManager::parseConfiguration() const
{
    CMakeConfig result;
    const QString cacheFile = QDir(m_buildDir.toString()).absoluteFilePath(QLatin1String("CMakeCache.txt"));
    QFile cache(cacheFile);
    if (!cache.open(QIODevice::ReadOnly | QIODevice::Text))
        return CMakeConfig();

    QSet<QByteArray> advancedSet;
    QByteArray documentation;
    while (!cache.atEnd()) {
        const QByteArray line = trimCMakeCacheLine(cache.readLine());

        if (line.isEmpty() || line.startsWith('#'))
            continue;

        if (line.startsWith("//")) {
            documentation = line.mid(2);
            continue;
        }

        const QByteArrayList pieces = splitCMakeCacheLine(line);
        if (pieces.isEmpty())
            continue;

        QTC_ASSERT(pieces.count() == 3, continue);
        const QByteArray key = pieces.at(0);
        const QByteArray type = pieces.at(1);
        const QByteArray value = pieces.at(2);

        if (key.endsWith("-ADVANCED") && value == "1") {
            advancedSet.insert(key.left(key.count() - 9 /* "-ADVANCED" */));
        } else {
            CMakeConfigItem::Type t = fromByteArray(type);
            if (t != CMakeConfigItem::INTERNAL)
                result << CMakeConfigItem(key, t, documentation, value);
        }
    }

    // Set advanced flags:
    for (int i = 0; i < result.count(); ++i) {
        CMakeConfigItem &item = result[i];
        item.isAdvanced = advancedSet.contains(item.key);
    }

    Utils::sort(result, CMakeConfigItem::sortOperator());

    return result;
}

468 469
} // namespace Internal
} // namespace CMakeProjectManager