tealeafreader.cpp 22.1 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 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
/****************************************************************************
**
** 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 "tealeafreader.h"

#include "cmakebuildconfiguration.h"
#include "cmakecbpparser.h"
#include "cmakekitinformation.h"
#include "cmakeparser.h"
#include "cmakeprojectconstants.h"
#include "cmakeprojectmanager.h"
#include "cmakeprojectnodes.h"

#include <coreplugin/documentmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/idocument.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/reaper.h>
#include <cpptools/projectpartbuilder.h>
#include <projectexplorer/headerpath.h>
#include <projectexplorer/ioutputparser.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>
#include <projectexplorer/task.h>
#include <projectexplorer/taskhub.h>
#include <projectexplorer/toolchain.h>
#include <projectexplorer/toolchainmanager.h>

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

#include <QDateTime>
#include <QFileInfo>

Tobias Hunger's avatar
Tobias Hunger committed
60
using namespace Core;
61
using namespace ProjectExplorer;
Tobias Hunger's avatar
Tobias Hunger committed
62
using namespace Utils;
63 64 65 66 67 68 69 70

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

namespace CMakeProjectManager {
namespace Internal {

Tobias Hunger's avatar
Tobias Hunger committed
71
class CMakeFile : public IDocument
72 73
{
public:
Tobias Hunger's avatar
Tobias Hunger committed
74
    CMakeFile(TeaLeafReader *r, const FileName &fileName);
75 76 77 78 79 80 81 82

    ReloadBehavior reloadBehavior(ChangeTrigger state, ChangeType type) const override;
    bool reload(QString *errorString, ReloadFlag flag, ChangeType type) override;

private:
    TeaLeafReader *m_reader;
};

Tobias Hunger's avatar
Tobias Hunger committed
83
CMakeFile::CMakeFile(TeaLeafReader *r, const FileName &fileName) : m_reader(r)
84 85 86 87 88 89
{
    setId("Cmake.ProjectFile");
    setMimeType(Constants::CMAKEPROJECTMIMETYPE);
    setFilePath(fileName);
}

Tobias Hunger's avatar
Tobias Hunger committed
90
IDocument::ReloadBehavior CMakeFile::reloadBehavior(ChangeTrigger state, ChangeType type) const
91 92 93 94 95 96
{
    Q_UNUSED(state)
    Q_UNUSED(type)
    return BehaviorSilent;
}

Tobias Hunger's avatar
Tobias Hunger committed
97
bool CMakeFile::reload(QString *errorString, IDocument::ReloadFlag flag, IDocument::ChangeType type)
98 99 100 101 102 103 104 105 106 107 108
{
    Q_UNUSED(errorString);
    Q_UNUSED(flag);

    if (type != TypePermissions)
        emit m_reader->dirty();
    return true;
}

static QString lineSplit(const QString &rest, const QByteArray &array, std::function<void(const QString &)> f)
{
Tobias Hunger's avatar
Tobias Hunger committed
109
    QString tmp = rest + SynchronousProcess::normalizeNewlines(QString::fromLocal8Bit(array));
110 111 112 113 114 115 116 117 118 119
    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);
}

Tobias Hunger's avatar
Tobias Hunger committed
120 121
static QStringList toArguments(const CMakeConfig &config, const MacroExpander *expander) {
    return transform(config, [expander](const CMakeConfigItem &i) -> QString {
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
        return i.toArgument(expander);
    });
}

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);
}

// --------------------------------------------------------------------
// TeaLeafReader:
// --------------------------------------------------------------------

TeaLeafReader::TeaLeafReader()
{
Tobias Hunger's avatar
Tobias Hunger committed
154 155
    connect(EditorManager::instance(), &EditorManager::aboutToSave,
            this, [this](const IDocument *document) {
156 157 158 159 160 161 162 163 164 165 166 167 168
        if (m_cmakeFiles.contains(document->filePath()))
            emit dirty();
    });
}

TeaLeafReader::~TeaLeafReader()
{
    stop();
    resetData();
}

bool TeaLeafReader::isCompatible(const BuildDirReader::Parameters &p)
{
169
    return !p.cmakeHasServerMode;
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
}

void TeaLeafReader::resetData()
{
    m_hasData = false;

    qDeleteAll(m_watchedFiles);
    m_watchedFiles.clear();

    m_cmakeCache.clear();
    m_projectName.clear();
    m_buildTargets.clear();
    qDeleteAll(m_files);
    m_files.clear();
}

void TeaLeafReader::parse(bool force)
{
    const QString cbpFile = CMakeManager::findCbpFile(QDir(m_parameters.buildDirectory.toString()));
    const QFileInfo cbpFileFi = cbpFile.isEmpty() ? QFileInfo() : QFileInfo(cbpFile);
    if (!cbpFileFi.exists()) {
        // Initial create:
        startCMake(toArguments(m_parameters.configuration, m_parameters.expander));
        return;
    }

    const bool mustUpdate = force
            || m_cmakeFiles.isEmpty()
Tobias Hunger's avatar
Tobias Hunger committed
198
            || anyOf(m_cmakeFiles, [&cbpFileFi](const FileName &f) {
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
                   return f.toFileInfo().lastModified() > cbpFileFi.lastModified();
               });
    if (mustUpdate) {
        startCMake(QStringList());
    } else {
        extractData();
        m_hasData = true;
        emit dataAvailable();
    }
}

void TeaLeafReader::stop()
{
    cleanUpProcess();

    if (m_future) {
        m_future->reportCanceled();
        m_future->reportFinished();
        delete m_future;
        m_future = nullptr;
    }
}

bool TeaLeafReader::isParsing() const
{
    return m_cmakeProcess && m_cmakeProcess->state() != QProcess::NotRunning;
}

bool TeaLeafReader::hasData() const
{
    return m_hasData;
}

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

CMakeConfig TeaLeafReader::parsedConfiguration() const
{
    CMakeConfig result;
Tobias Hunger's avatar
Tobias Hunger committed
240
    FileName cacheFile = m_parameters.buildDirectory;
241 242 243 244 245 246 247
    cacheFile.appendPath(QLatin1String("CMakeCache.txt"));
    if (!cacheFile.exists())
        return result;
    QString errorMessage;
    m_cmakeCache = parseConfiguration(cacheFile, &errorMessage);
    if (!errorMessage.isEmpty())
        emit errorOccured(errorMessage);
Tobias Hunger's avatar
Tobias Hunger committed
248 249 250 251
    const FileName sourceOfBuildDir
            = FileName::fromUtf8(CMakeConfigItem::valueOf("CMAKE_HOME_DIRECTORY", m_cmakeCache));
    const FileName canonicalSourceOfBuildDir = FileUtils::canonicalPath(sourceOfBuildDir);
    const FileName canonicalSourceDirectory = FileUtils::canonicalPath(m_parameters.sourceDirectory);
252 253 254 255 256 257 258 259
    if (canonicalSourceOfBuildDir != canonicalSourceDirectory) { // Uses case-insensitive compare where appropriate
        emit errorOccured(tr("The build directory is not for %1 but for %2")
                          .arg(canonicalSourceOfBuildDir.toUserOutput(),
                               canonicalSourceDirectory.toUserOutput()));
    }
    return result;
}

Tobias Hunger's avatar
Tobias Hunger committed
260
CMakeConfig TeaLeafReader::parseConfiguration(const FileName &cacheFile, QString *errorMessage) const
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
{
    CMakeConfig result;
    QFile cache(cacheFile.toString());
    if (!cache.open(QIODevice::ReadOnly | QIODevice::Text)) {
        if (errorMessage)
            *errorMessage = tr("Failed to open %1 for reading.").arg(cacheFile.toUserOutput());
        return CMakeConfig();
    }

    QSet<QByteArray> advancedSet;
    QMap<QByteArray, QByteArray> valuesMap;
    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" */));
295
        } else if (key.endsWith("-STRINGS") && CMakeConfigItem::typeStringToType(type) == CMakeConfigItem::INTERNAL) {
296 297
            valuesMap[key.left(key.count() - 8) /* "-STRINGS" */] = value;
        } else {
298
            CMakeConfigItem::Type t = CMakeConfigItem::typeStringToType(type);
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
            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);

        if (valuesMap.contains(item.key)) {
            item.values = CMakeConfigItem::cmakeSplitValue(QString::fromUtf8(valuesMap[item.key]));
        } else if (item.key  == "CMAKE_BUILD_TYPE") {
            // WA for known options
            item.values << "" << "Debug" << "Release" << "MinSizeRel" << "RelWithDebInfo";
        }
    }

Tobias Hunger's avatar
Tobias Hunger committed
316
    sort(result, CMakeConfigItem::sortOperator());
317 318 319 320

    return result;
}

321
void TeaLeafReader::generateProjectTree(CMakeProjectNode *root, const QList<FileNode *> &allFiles)
322
{
323
    Q_UNUSED(allFiles);
324 325 326
    root->setDisplayName(m_projectName);

    // Delete no longer necessary file watcher:
Tobias Hunger's avatar
Tobias Hunger committed
327 328 329 330
    const QSet<FileName> currentWatched
            = transform(m_watchedFiles, [](CMakeFile *cmf) { return cmf->filePath(); });
    const QSet<FileName> toWatch = m_cmakeFiles;
    QSet<FileName> toDelete = currentWatched;
331
    toDelete.subtract(toWatch);
Tobias Hunger's avatar
Tobias Hunger committed
332
    m_watchedFiles = filtered(m_watchedFiles, [&toDelete](Internal::CMakeFile *cmf) {
333 334 335 336 337 338 339 340
            if (toDelete.contains(cmf->filePath())) {
                delete cmf;
                return false;
            }
            return true;
        });

    // Add new file watchers:
Tobias Hunger's avatar
Tobias Hunger committed
341
    QSet<FileName> toAdd = toWatch;
342
    toAdd.subtract(currentWatched);
Tobias Hunger's avatar
Tobias Hunger committed
343
    foreach (const FileName &fn, toAdd) {
344
        CMakeFile *cm = new CMakeFile(this, fn);
Tobias Hunger's avatar
Tobias Hunger committed
345
        DocumentManager::addDocument(cm);
346 347 348 349 350 351 352 353
        m_watchedFiles.insert(cm);
    }

    QList<FileNode *> fileNodes = m_files;
    root->buildTree(fileNodes);
    m_files.clear(); // Some of the FileNodes in files() were deleted!
}

Tobias Hunger's avatar
Tobias Hunger committed
354
QSet<Id> TeaLeafReader::updateCodeModel(CppTools::ProjectPartBuilder &ppBuilder)
355
{
Tobias Hunger's avatar
Tobias Hunger committed
356
    QSet<Id> languages;
357
    const ToolChain *tc = ToolChainManager::findToolChain(m_parameters.toolChainId);
Tobias Hunger's avatar
Tobias Hunger committed
358
    const FileName sysroot = m_parameters.sysRoot;
359 360 361 362 363 364 365 366 367

    QHash<QString, QStringList> targetDataCache;
    foreach (const CMakeBuildTarget &cbt, m_buildTargets) {
        if (cbt.targetType == UtilityType)
            continue;

        // CMake shuffles the include paths that it reports via the CodeBlocks generator
        // So remove the toolchain include paths, so that at least those end up in the correct
        // place.
368
        const QStringList cxxflags = getCXXFlagsFor(cbt, targetDataCache);
Tobias Hunger's avatar
Tobias Hunger committed
369
        QSet<FileName> tcIncludes;
370 371 372
        QStringList includePaths;
        if (tc) {
            foreach (const HeaderPath &hp, tc->systemHeaderPaths(cxxflags, sysroot))
Tobias Hunger's avatar
Tobias Hunger committed
373 374
                tcIncludes.insert(FileName::fromString(hp.path()));
            foreach (const FileName &i, cbt.includeFiles) {
375 376 377 378
                if (!tcIncludes.contains(i))
                    includePaths.append(i.toString());
            }
        } else {
Tobias Hunger's avatar
Tobias Hunger committed
379
            includePaths = transform(cbt.includeFiles, &FileName::toString);
380 381 382 383 384 385 386 387
        }
        includePaths += m_parameters.buildDirectory.toString();
        ppBuilder.setIncludePaths(includePaths);
        ppBuilder.setCFlags(cxxflags);
        ppBuilder.setCxxFlags(cxxflags);
        ppBuilder.setDefines(cbt.defines);
        ppBuilder.setDisplayName(cbt.title);

Tobias Hunger's avatar
Tobias Hunger committed
388 389 390
        const QSet<Id> partLanguages
                = QSet<Id>::fromList(ppBuilder.createProjectPartsForFiles(
                                               transform(cbt.files, [](const FileName &fn) { return fn.toString(); })));
391 392 393 394 395 396 397 398 399 400 401

        languages.unite(partLanguages);
    }
    return languages;

}

void TeaLeafReader::cleanUpProcess()
{
    if (m_cmakeProcess) {
        m_cmakeProcess->disconnect();
Tobias Hunger's avatar
Tobias Hunger committed
402
        Reaper::reap(m_cmakeProcess);
403 404 405 406 407 408 409 410 411 412 413 414
        m_cmakeProcess = nullptr;
    }

    // Delete issue parser:
    if (m_parser)
        m_parser->flush();
    delete m_parser;
    m_parser = nullptr;
}

void TeaLeafReader::extractData()
{
Tobias Hunger's avatar
Tobias Hunger committed
415 416
    const FileName srcDir = m_parameters.sourceDirectory;
    const FileName bldDir = m_parameters.buildDirectory;
417
    const FileName topCMake = Utils::FileName(srcDir).appendPath("CMakeLists.txt");
418 419 420 421

    resetData();

    m_projectName = m_parameters.projectName;
422
    m_files.append(new FileNode(topCMake, FileType::Project, false));
423 424 425
    // Do not insert topCMake into m_cmakeFiles: The project already watches that!

    // Find cbp file
Tobias Hunger's avatar
Tobias Hunger committed
426
    FileName cbpFile = FileName::fromString(CMakeManager::findCbpFile(bldDir.toString()));
427 428 429 430 431
    if (cbpFile.isEmpty())
        return;
    m_cmakeFiles.insert(cbpFile);

    // Add CMakeCache.txt file:
Tobias Hunger's avatar
Tobias Hunger committed
432
    FileName cacheFile = m_parameters.buildDirectory;
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
    cacheFile.appendPath(QLatin1String("CMakeCache.txt"));
    if (cacheFile.toFileInfo().exists())
        m_cmakeFiles.insert(cacheFile);

    // setFolderName
    CMakeCbpParser cbpparser;
    // Parsing
    if (!cbpparser.parseCbpFile(m_parameters.pathMapper, cbpFile, srcDir))
        return;

    m_projectName = cbpparser.projectName();

    m_files = cbpparser.fileList();
    if (cbpparser.hasCMakeFiles()) {
        m_files.append(cbpparser.cmakeFileList());
        foreach (const FileNode *node, cbpparser.cmakeFileList())
            m_cmakeFiles.insert(node->filePath());
    }

    // Make sure the top cmakelists.txt file is always listed:
Tobias Hunger's avatar
Tobias Hunger committed
453
    if (!contains(m_files, [topCMake](FileNode *fn) { return fn->filePath() == topCMake; }))
454
        m_files.append(new FileNode(topCMake, FileType::Project, false));
Tobias Hunger's avatar
Tobias Hunger committed
455 456

    Utils::sort(m_files, &Node::sortByPath);
457 458 459 460 461 462

    m_buildTargets = cbpparser.buildTargets();
}

void TeaLeafReader::startCMake(const QStringList &configurationArguments)
{
Tobias Hunger's avatar
Tobias Hunger committed
463
    const FileName buildDirectory = m_parameters.buildDirectory;
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
    QTC_ASSERT(!m_cmakeProcess, return);
    QTC_ASSERT(!m_parser, return);
    QTC_ASSERT(!m_future, return);
    QTC_ASSERT(buildDirectory.exists(), return);

    const QString srcDir = m_parameters.sourceDirectory.toString();

    m_parser = new CMakeParser;
    QDir source = QDir(srcDir);
    connect(m_parser, &IOutputParser::addTask, m_parser,
            [source](const Task &task) {
                if (task.file.isEmpty() || task.file.toFileInfo().isAbsolute()) {
                    TaskHub::addTask(task);
                } else {
                    Task t = task;
Tobias Hunger's avatar
Tobias Hunger committed
479
                    t.file = FileName::fromString(source.absoluteFilePath(task.file.toString()));
480 481 482 483 484 485 486
                    TaskHub::addTask(t);
                }
            });

    // 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.

Tobias Hunger's avatar
Tobias Hunger committed
487
    m_cmakeProcess = new QtcProcess;
488 489 490 491 492 493 494 495 496 497 498
    m_cmakeProcess->setWorkingDirectory(buildDirectory.toString());
    m_cmakeProcess->setEnvironment(m_parameters.environment);

    connect(m_cmakeProcess, &QProcess::readyReadStandardOutput,
            this, &TeaLeafReader::processCMakeOutput);
    connect(m_cmakeProcess, &QProcess::readyReadStandardError,
            this, &TeaLeafReader::processCMakeError);
    connect(m_cmakeProcess, static_cast<void(QProcess::*)(int,  QProcess::ExitStatus)>(&QProcess::finished),
            this, &TeaLeafReader::cmakeFinished);

    QString args;
Tobias Hunger's avatar
Tobias Hunger committed
499 500 501
    QtcProcess::addArg(&args, srcDir);
    QtcProcess::addArgs(&args, m_parameters.generatorArguments);
    QtcProcess::addArgs(&args, configurationArguments);
502 503 504

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

Tobias Hunger's avatar
Tobias Hunger committed
505 506 507 508
    MessageManager::write(tr("Running \"%1 %2\" in %3.")
                          .arg(m_parameters.cmakeExecutable.toUserOutput())
                          .arg(args)
                          .arg(buildDirectory.toUserOutput()));
509 510 511

    m_future = new QFutureInterface<void>();
    m_future->setProgressRange(0, 1);
Tobias Hunger's avatar
Tobias Hunger committed
512 513 514
    ProgressManager::addTask(m_future->future(),
                             tr("Configuring \"%1\"").arg(m_parameters.projectName),
                             "CMake.Configure");
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540

    m_cmakeProcess->setCommand(m_parameters.cmakeExecutable.toString(), args);
    m_cmakeProcess->start();
    emit configurationStarted();
}

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

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

    m_cmakeProcess->disconnect();
    cleanUpProcess();

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

    QString msg;
    if (status != QProcess::NormalExit)
        msg = tr("*** cmake process crashed!");
    else if (code != 0)
        msg = tr("*** cmake process exited with exit code %1.").arg(code);

    if (!msg.isEmpty()) {
Tobias Hunger's avatar
Tobias Hunger committed
541
        MessageManager::write(msg);
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
        TaskHub::addTask(Task::Error, msg, ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);
        m_future->reportCanceled();
    } else {
        m_future->setProgressValue(1);
    }

    m_future->reportFinished();
    delete m_future;
    m_future = nullptr;

    m_hasData = true;
    emit dataAvailable();
}

void TeaLeafReader::processCMakeOutput()
{
    static QString rest;
    rest = lineSplit(rest, m_cmakeProcess->readAllStandardOutput(),
Tobias Hunger's avatar
Tobias Hunger committed
560
                     [this](const QString &s) { MessageManager::write(s); });
561 562 563 564 565 566 567
}

void TeaLeafReader::processCMakeError()
{
    static QString rest;
    rest = lineSplit(rest, m_cmakeProcess->readAllStandardError(), [this](const QString &s) {
        m_parser->stdError(s);
Tobias Hunger's avatar
Tobias Hunger committed
568
        MessageManager::write(s);
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    });
}

QStringList TeaLeafReader::getCXXFlagsFor(const CMakeBuildTarget &buildTarget, QHash<QString, QStringList> &cache)
{
    // check cache:
    auto it = cache.constFind(buildTarget.title);
    if (it != cache.constEnd())
        return *it;

    if (extractCXXFlagsFromMake(buildTarget, cache))
        return cache.value(buildTarget.title);

    if (extractCXXFlagsFromNinja(buildTarget, cache))
        return cache.value(buildTarget.title);

    cache.insert(buildTarget.title, QStringList());
    return QStringList();
}

bool TeaLeafReader::extractCXXFlagsFromMake(const CMakeBuildTarget &buildTarget, QHash<QString, QStringList> &cache)
{
    QString makeCommand = buildTarget.makeCommand.toString();
    int startIndex = makeCommand.indexOf('\"');
    int endIndex = makeCommand.indexOf('\"', startIndex + 1);
    if (startIndex != -1 && endIndex != -1) {
        startIndex += 1;
        QString makefile = makeCommand.mid(startIndex, endIndex - startIndex);
        int slashIndex = makefile.lastIndexOf('/');
        makefile.truncate(slashIndex);
        makefile.append("/CMakeFiles/" + buildTarget.title + ".dir/flags.make");
        QFile file(makefile);
        if (file.exists()) {
            file.open(QIODevice::ReadOnly | QIODevice::Text);
            QTextStream stream(&file);
            while (!stream.atEnd()) {
                QString line = stream.readLine().trimmed();
                if (line.startsWith("CXX_FLAGS =")) {
                    // Skip past =
                    cache.insert(buildTarget.title,
                                 line.mid(11).trimmed().split(' ', QString::SkipEmptyParts));
                    return true;
                }
            }
        }
    }
    return false;
}

bool TeaLeafReader::extractCXXFlagsFromNinja(const CMakeBuildTarget &buildTarget, QHash<QString, QStringList> &cache)
{
    Q_UNUSED(buildTarget)
    if (!cache.isEmpty()) // We fill the cache in one go!
        return false;

    // Attempt to find build.ninja file and obtain FLAGS (CXX_FLAGS) from there if no suitable flags.make were
    // found
    // Get "all" target's working directory
    QByteArray ninjaFile;
    QString buildNinjaFile = buildTargets().at(0).workingDirectory.toString();
    buildNinjaFile += "/build.ninja";
    QFile buildNinja(buildNinjaFile);
    if (buildNinja.exists()) {
        buildNinja.open(QIODevice::ReadOnly | QIODevice::Text);
        ninjaFile = buildNinja.readAll();
        buildNinja.close();
    }

    if (ninjaFile.isEmpty())
        return false;

    QTextStream stream(ninjaFile);
    bool cxxFound = false;
    const QString targetSignature = "# Object build statements for ";
    QString currentTarget;

    while (!stream.atEnd()) {
        // 1. Look for a block that refers to the current target
        // 2. Look for a build rule which invokes CXX_COMPILER
        // 3. Return the FLAGS definition
        QString line = stream.readLine().trimmed();
        if (line.startsWith('#')) {
            if (line.startsWith(targetSignature)) {
                int pos = line.lastIndexOf(' ');
                currentTarget = line.mid(pos + 1);
            }
        } else if (!currentTarget.isEmpty() && line.startsWith("build")) {
            cxxFound = line.indexOf("CXX_COMPILER") != -1;
        } else if (cxxFound && line.startsWith("FLAGS =")) {
            // Skip past =
            cache.insert(currentTarget, line.mid(7).trimmed().split(' ', QString::SkipEmptyParts));
        }
    }
    return !cache.isEmpty();
}

} // namespace Internal
} // namespace CMakeProjectManager