vcsmanager.cpp 22.8 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
Eike Ziller's avatar
Eike Ziller committed
3
4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8
9
10
11
** 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
Eike Ziller's avatar
Eike Ziller committed
12
13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18
19
20
21
22
23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24
**
Eike Ziller's avatar
Eike Ziller committed
25
26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
con's avatar
con committed
27
28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
hjk's avatar
hjk committed
30

con's avatar
con committed
31
32
#include "vcsmanager.h"
#include "iversioncontrol.h"
33
#include "icore.h"
34
#include "documentmanager.h"
35
36
37
#include "idocument.h"
#include "infobar.h"

38
39
40
#include <coreplugin/dialogs/addtovcsdialog.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
con's avatar
con committed
41

42
#include <vcsbase/vcsbaseconstants.h>
con's avatar
con committed
43
#include <extensionsystem/pluginmanager.h>
44
#include <utils/algorithm.h>
45
#include <utils/qtcassert.h>
con's avatar
con committed
46

47
48
49
50
#include <QDir>
#include <QString>
#include <QList>
#include <QMap>
con's avatar
con committed
51

52
53
#include <QFileInfo>
#include <QMessageBox>
con's avatar
con committed
54
55
56

namespace Core {

57
58
59
60
typedef QList<IVersionControl *> VersionControlList;

static inline VersionControlList allVersionControls()
{
61
    return ExtensionSystem::PluginManager::getObjects<IVersionControl>();
62
63
}

Tobias Hunger's avatar
Tobias Hunger committed
64
65
66
67
#if defined(WITH_TESTS)
const char TEST_PREFIX[] = "/8E3A9BA0-0B97-40DF-AEC1-2BDF9FC9EDBE/";
#endif

68
69
70
// ---- VCSManagerPrivate:
// Maintains a cache of top-level directory->version control.

hjk's avatar
hjk committed
71
72
73
class VcsManagerPrivate
{
public:
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
    class VcsInfo {
    public:
        VcsInfo(IVersionControl *vc, const QString &tl) :
            versionControl(vc), topLevel(tl)
        { }

        bool operator == (const VcsInfo &other) const
        {
            return versionControl == other.versionControl &&
                    topLevel == other.topLevel;
        }

        IVersionControl *versionControl;
        QString topLevel;
    };

90
    VcsManagerPrivate() : m_unconfiguredVcs(0), m_cachedAdditionalToolsPathsDirty(true)
91
92
    { }

93
94
95
96
97
    ~VcsManagerPrivate()
    {
        qDeleteAll(m_vcsInfoList);
    }

98
    VcsInfo *findInCache(const QString &dir)
99
    {
100
101
102
        QTC_ASSERT(QDir(dir).isAbsolute(), return 0);
        QTC_ASSERT(!dir.endsWith(QLatin1Char('/')), return 0);
        QTC_ASSERT(QDir::fromNativeSeparators(dir) == dir, return 0);
103
104

        const QMap<QString, VcsInfo *>::const_iterator it = m_cachedMatches.constFind(dir);
105
106
107
108
109
110
111
112
        if (it != m_cachedMatches.constEnd())
            return it.value();
        return 0;
    }

    VcsInfo *findUpInCache(const QString &directory)
    {
        VcsInfo *result = 0;
113
        const QChar slash = QLatin1Char('/');
114
115
        // Split the path, trying to find the matching repository. We start from the reverse
        // in order to detected nested repositories correctly (say, a git checkout under SVN).
116
        for (int pos = directory.size() - 1; pos >= 0; pos = directory.lastIndexOf(slash, pos) - 1) {
117
118
119
120
121
122
123
124
            const QString directoryPart = directory.left(pos);
            result = findInCache(directoryPart);
            if (result != 0)
                break;
        }
        return result;
    }

125
126
127
128
129
    void clearCache()
    {
        m_cachedMatches.clear();
    }

Tobias Hunger's avatar
Tobias Hunger committed
130
    void resetCache(const QString &dir)
131
    {
Tobias Hunger's avatar
Tobias Hunger committed
132
133
134
135
        QTC_ASSERT(QDir(dir).isAbsolute(), return);
        QTC_ASSERT(!dir.endsWith(QLatin1Char('/')), return);
        QTC_ASSERT(QDir::fromNativeSeparators(dir) == dir, return);

136
137
138
139
140
141
142
        const QString dirSlash = dir + QLatin1Char('/');
        foreach (const QString &key, m_cachedMatches.keys()) {
            if (key == dir || key.startsWith(dirSlash))
                m_cachedMatches.remove(key);
        }
    }

Tobias Hunger's avatar
Tobias Hunger committed
143
    void cache(IVersionControl *vc, const QString &topLevel, const QString &dir)
144
    {
Tobias Hunger's avatar
Tobias Hunger committed
145
146
147
        QTC_ASSERT(QDir(dir).isAbsolute(), return);
        QTC_ASSERT(!dir.endsWith(QLatin1Char('/')), return);
        QTC_ASSERT(QDir::fromNativeSeparators(dir) == dir, return);
Tobias Hunger's avatar
Tobias Hunger committed
148
149
150
        QTC_ASSERT(dir.startsWith(topLevel + QLatin1Char('/'))
                   || topLevel == dir || topLevel.isEmpty(), return);
        QTC_ASSERT((topLevel.isEmpty() && !vc) || (!topLevel.isEmpty() && vc), return);
Tobias Hunger's avatar
Tobias Hunger committed
151

152
153
154
        VcsInfo *newInfo = new VcsInfo(vc, topLevel);
        bool createdNewInfo(true);
        // Do we have a matching VcsInfo already?
155
        foreach (VcsInfo *i, m_vcsInfoList) {
156
157
158
159
160
161
162
163
164
165
            if (*i == *newInfo) {
                delete newInfo;
                newInfo = i;
                createdNewInfo = false;
                break;
            }
        }
        if (createdNewInfo)
            m_vcsInfoList.append(newInfo);

166
        QString tmpDir = dir;
167
        const QChar slash = QLatin1Char('/');
168
        while (tmpDir.count() >= topLevel.count() && !tmpDir.isEmpty()) {
169
            m_cachedMatches.insert(tmpDir, newInfo);
170
171
172
173
            // if no vc was found, this might mean we're inside a repo internal directory (.git)
            // Cache only input directory, not parents
            if (!vc)
                break;
174
            const int slashPos = tmpDir.lastIndexOf(slash);
175
            if (slashPos >= 0)
176
                tmpDir.truncate(slashPos);
177
            else
178
                tmpDir.clear();
179
180
181
182
183
        }
    }

    QMap<QString, VcsInfo *> m_cachedMatches;
    QList<VcsInfo *> m_vcsInfoList;
184
    IVersionControl *m_unconfiguredVcs;
185
186
187

    QStringList m_cachedAdditionalToolsPaths;
    bool m_cachedAdditionalToolsPathsDirty;
con's avatar
con committed
188
189
};

hjk's avatar
hjk committed
190
191
static VcsManagerPrivate *d = 0;
static VcsManager *m_instance = 0;
192

hjk's avatar
hjk committed
193
VcsManager::VcsManager(QObject *parent) :
194
   QObject(parent)
con's avatar
con committed
195
{
hjk's avatar
hjk committed
196
    m_instance = this;
197
    d = new VcsManagerPrivate;
con's avatar
con committed
198
199
}

200
201
// ---- VCSManager:

hjk's avatar
hjk committed
202
VcsManager::~VcsManager()
con's avatar
con committed
203
{
hjk's avatar
hjk committed
204
    m_instance = 0;
hjk's avatar
hjk committed
205
    delete d;
con's avatar
con committed
206
207
}

208
VcsManager *VcsManager::instance()
hjk's avatar
hjk committed
209
210
211
212
{
    return m_instance;
}

hjk's avatar
hjk committed
213
void VcsManager::extensionsInitialized()
214
215
216
217
{
    // Change signal connections
    foreach (IVersionControl *versionControl, allVersionControls()) {
        connect(versionControl, SIGNAL(filesChanged(QStringList)),
218
                DocumentManager::instance(), SIGNAL(filesChangedInternally(QStringList)));
219
        connect(versionControl, SIGNAL(repositoryChanged(QString)),
hjk's avatar
hjk committed
220
                m_instance, SIGNAL(repositoryChanged(QString)));
221
222
        connect(versionControl, SIGNAL(configurationChanged()),
                m_instance, SLOT(handleConfigurationChanges()));
223
224
225
    }
}

226
227
228
229
230
231
232
233
234
235
236
237
QList<IVersionControl *> VcsManager::versionControls()
{
    return ExtensionSystem::PluginManager::getObjects<IVersionControl>();
}

IVersionControl *VcsManager::versionControl(Id id)
{
    return Utils::findOrDefault(versionControls(), [id](const Core::IVersionControl *vc) {
        return vc->id() == id;
    });
}

238
239
240
241
242
243
244
245
void VcsManager::resetVersionControlForDirectory(const QString &inputDirectory)
{
    if (inputDirectory.isEmpty())
        return;

    const QString directory = QDir(inputDirectory).absolutePath();

    d->resetCache(directory);
hjk's avatar
hjk committed
246
    emit m_instance->repositoryChanged(directory);
247
248
}

249
IVersionControl* VcsManager::findVersionControlForDirectory(const QString &inputDirectory,
250
                                                            QString *topLevelDirectory)
con's avatar
con committed
251
{
252
253
    typedef QPair<QString, IVersionControl *> StringVersionControlPair;
    typedef QList<StringVersionControlPair> StringVersionControlPairs;
254
255
256
    if (inputDirectory.isEmpty()) {
        if (topLevelDirectory)
            topLevelDirectory->clear();
257
        return 0;
258
    }
259

260
    // Make sure we an absolute path:
261
262
    QString directory = QDir(inputDirectory).absolutePath();
#ifdef WITH_TESTS
263
    if (directory[0].isLetter() && directory.indexOf(QLatin1Char(':') + QLatin1String(TEST_PREFIX)) == 1)
264
265
        directory = directory.mid(2);
#endif
hjk's avatar
hjk committed
266
    VcsManagerPrivate::VcsInfo *cachedData = d->findInCache(directory);
267
    if (cachedData) {
268
        if (topLevelDirectory)
269
270
            *topLevelDirectory = cachedData->topLevel;
        return cachedData->versionControl;
con's avatar
con committed
271
272
    }

273
    // Nothing: ask the IVersionControls directly.
274
    const VersionControlList versionControls = allVersionControls();
275
    StringVersionControlPairs allThatCanManage;
Sami Tikka's avatar
Sami Tikka committed
276

hjk's avatar
hjk committed
277
    foreach (IVersionControl * versionControl, versionControls) {
Tobias Hunger's avatar
Tobias Hunger committed
278
        QString topLevel;
279
        if (versionControl->managesDirectory(directory, &topLevel))
280
            allThatCanManage.push_back(StringVersionControlPair(topLevel, versionControl));
con's avatar
con committed
281
    }
Sami Tikka's avatar
Sami Tikka committed
282
283
284

    // To properly find a nested repository (say, git checkout inside SVN),
    // we need to select the version control with the longest toplevel pathname.
285
286
287
288
    Utils::sort(allThatCanManage, [](const StringVersionControlPair &l,
                                     const StringVersionControlPair &r) {
        return l.first.size() > r.first.size();
    });
Sami Tikka's avatar
Sami Tikka committed
289

290
    if (allThatCanManage.isEmpty()) {
hjk's avatar
hjk committed
291
        d->cache(0, QString(), directory); // register that nothing was found!
292
293

        // report result;
Sami Tikka's avatar
Sami Tikka committed
294
        if (topLevelDirectory)
295
296
            topLevelDirectory->clear();
        return 0;
Sami Tikka's avatar
Sami Tikka committed
297
    }
298
299

    // Register Vcs(s) with the cache
300
    QString tmpDir = QFileInfo(directory).canonicalFilePath();
Tobias Hunger's avatar
Tobias Hunger committed
301
302
303
304
305
#if defined WITH_TESTS
    // Force caching of test directories (even though they do not exist):
    if (directory.startsWith(QLatin1String(TEST_PREFIX)))
        tmpDir = directory;
#endif
306
307
308
309
310
311
    // directory might refer to a historical directory which doesn't exist.
    // In this case, don't cache it.
    if (!tmpDir.isEmpty()) {
        const QChar slash = QLatin1Char('/');
        const StringVersionControlPairs::const_iterator cend = allThatCanManage.constEnd();
        for (StringVersionControlPairs::const_iterator i = allThatCanManage.constBegin(); i != cend; ++i) {
312
313
314
            // If topLevel was already cached for another VC, skip this one
            if (tmpDir.count() < i->first.count())
                continue;
315
316
317
318
319
320
            d->cache(i->second, i->first, tmpDir);
            tmpDir = i->first;
            const int slashPos = tmpDir.lastIndexOf(slash);
            if (slashPos >= 0)
                tmpDir.truncate(slashPos);
        }
321
322
323
324
325
    }

    // return result
    if (topLevelDirectory)
        *topLevelDirectory = allThatCanManage.first().first;
326
    IVersionControl *versionControl = allThatCanManage.first().second;
327
328
329
    const bool isVcsConfigured = versionControl->isConfigured();
    if (!isVcsConfigured || d->m_unconfiguredVcs) {
        Id vcsWarning("VcsNotConfiguredWarning");
330
        IDocument *curDocument = EditorManager::currentDocument();
331
332
333
334
        if (isVcsConfigured) {
            if (curDocument && d->m_unconfiguredVcs == versionControl) {
                curDocument->infoBar()->removeInfo(vcsWarning);
                d->m_unconfiguredVcs = 0;
335
            }
336
337
            return versionControl;
        } else {
338
339
            InfoBar *infoBar = curDocument ? curDocument->infoBar() : 0;
            if (infoBar && infoBar->canInfoBeAdded(vcsWarning)) {
340
341
342
343
344
                InfoBarEntry info(vcsWarning,
                                  tr("%1 repository was detected but %1 is not configured.")
                                  .arg(versionControl->displayName()),
                                  InfoBarEntry::GlobalSuppressionEnabled);
                d->m_unconfiguredVcs = versionControl;
Orgad Shaneh's avatar
Orgad Shaneh committed
345
                info.setCustomButtonInfo(ICore::msgShowOptionsDialog(), []() {
346
                    QTC_ASSERT(d->m_unconfiguredVcs, return);
347
                    ICore::showOptionsDialog(d->m_unconfiguredVcs->id());
348
349
                 });

350
351
352
                infoBar->addInfo(info);
            }
            return 0;
353
354
355
        }
    }
    return versionControl;
con's avatar
con committed
356
357
}

358
359
360
361
362
363
364
QString VcsManager::findTopLevelForDirectory(const QString &directory)
{
    QString result;
    findVersionControlForDirectory(directory, &result);
    return result;
}

hjk's avatar
hjk committed
365
QStringList VcsManager::repositories(const IVersionControl *vc)
366
367
368
369
370
371
372
373
{
    QStringList result;
    foreach (const VcsManagerPrivate::VcsInfo *vi, d->m_vcsInfoList)
        if (vi->versionControl == vc)
            result.push_back(vi->topLevel);
    return result;
}

hjk's avatar
hjk committed
374
bool VcsManager::promptToDelete(const QString &fileName)
con's avatar
con committed
375
{
376
377
378
379
380
    if (IVersionControl *vc = findVersionControlForDirectory(QFileInfo(fileName).absolutePath()))
        return promptToDelete(vc, fileName);
    return true;
}

hjk's avatar
hjk committed
381
bool VcsManager::promptToDelete(IVersionControl *vc, const QString &fileName)
382
{
383
    QTC_ASSERT(vc, return true);
384
    if (!vc->supportsOperation(IVersionControl::DeleteOperation))
385
        return true;
hjk's avatar
hjk committed
386
387
388
    const QString title = tr("Version Control");
    const QString msg = tr("Would you like to remove this file from the version control system (%1)?\n"
                           "Note: This might remove the local file.").arg(vc->displayName());
con's avatar
con committed
389
    const QMessageBox::StandardButton button =
390
        QMessageBox::question(ICore::dialogParent(), title, msg, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
391
392
393
    if (button != QMessageBox::Yes)
        return true;
    return vc->vcsDelete(fileName);
con's avatar
con committed
394
395
}

Friedemann Kleint's avatar
Friedemann Kleint committed
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
QString VcsManager::msgAddToVcsTitle()
{
    return tr("Add to Version Control");
}

QString VcsManager::msgPromptToAddToVcs(const QStringList &files, const IVersionControl *vc)
{
    return files.size() == 1
        ? tr("Add the file\n%1\nto version control (%2)?")
              .arg(files.front(), vc->displayName())
        : tr("Add the files\n%1\nto version control (%2)?")
              .arg(files.join(QString(QLatin1Char('\n'))), vc->displayName());
}

QString VcsManager::msgAddToVcsFailedTitle()
{
    return tr("Adding to Version Control Failed");
}

QString VcsManager::msgToAddToVcsFailed(const QStringList &files, const IVersionControl *vc)
{
    return files.size() == 1
418
419
        ? tr("Could not add the file\n%1\nto version control (%2)\n")
              .arg(files.front(), vc->displayName())
Friedemann Kleint's avatar
Friedemann Kleint committed
420
421
422
423
        : tr("Could not add the following files to version control (%1)\n%2")
              .arg(vc->displayName(), files.join(QString(QLatin1Char('\n'))));
}

424
425
426
427
428
429
430
431
432
433
434
QStringList VcsManager::additionalToolsPath()
{
    if (d->m_cachedAdditionalToolsPathsDirty) {
        d->m_cachedAdditionalToolsPaths.clear();
        foreach (IVersionControl *vc, allVersionControls())
            d->m_cachedAdditionalToolsPaths.append(vc->additionalToolsPath());
        d->m_cachedAdditionalToolsPathsDirty = false;
    }
    return d->m_cachedAdditionalToolsPaths;
}

435
436
437
void VcsManager::promptToAdd(const QString &directory, const QStringList &fileNames)
{
    IVersionControl *vc = findVersionControlForDirectory(directory);
Orgad Shaneh's avatar
Orgad Shaneh committed
438
    if (!vc || !vc->supportsOperation(IVersionControl::AddOperation))
439
440
        return;

441
442
443
444
445
446
447
448
449
    QStringList unmanagedFiles;
    QDir dir(directory);
    foreach (const QString &fileName, fileNames) {
        if (!vc->managesFile(directory, dir.relativeFilePath(fileName)))
            unmanagedFiles << fileName;
    }
    if (unmanagedFiles.isEmpty())
        return;

Orgad Shaneh's avatar
Orgad Shaneh committed
450
    Internal::AddToVcsDialog dlg(ICore::mainWindow(), VcsManager::msgAddToVcsTitle(),
451
                                 unmanagedFiles, vc->displayName());
452
    if (dlg.exec() == QDialog::Accepted) {
453
        QStringList notAddedToVc;
454
        foreach (const QString &file, unmanagedFiles) {
455
456
457
458
459
            if (!vc->vcsAdd(file))
                notAddedToVc << file;
        }

        if (!notAddedToVc.isEmpty()) {
Orgad Shaneh's avatar
Orgad Shaneh committed
460
            QMessageBox::warning(ICore::mainWindow(), VcsManager::msgAddToVcsFailedTitle(),
Friedemann Kleint's avatar
Friedemann Kleint committed
461
                                 VcsManager::msgToAddToVcsFailed(notAddedToVc, vc));
462
463
464
465
        }
    }
}

466
467
void VcsManager::emitRepositoryChanged(const QString &repository)
{
hjk's avatar
hjk committed
468
    emit m_instance->repositoryChanged(repository);
469
470
}

471
472
473
474
475
void VcsManager::clearVersionControlCache()
{
    QStringList repoList = d->m_cachedMatches.keys();
    d->clearCache();
    foreach (const QString &repo, repoList)
hjk's avatar
hjk committed
476
        emit m_instance->repositoryChanged(repo);
477
478
}

479
480
481
void VcsManager::handleConfigurationChanges()
{
    d->m_cachedAdditionalToolsPathsDirty = true;
482
483
484
    IVersionControl *vcs = qobject_cast<IVersionControl *>(sender());
    if (vcs)
        emit configurationChanged(vcs);
485
486
}

hjk's avatar
hjk committed
487
} // namespace Core
Tobias Hunger's avatar
Tobias Hunger committed
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
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

#if defined(WITH_TESTS)

#include <QtTest>

#include "coreplugin.h"
#include "iversioncontrol.h"

#include <extensionsystem/pluginmanager.h>

namespace Core {
namespace Internal {

const char ID_VCS_A[] = "A";
const char ID_VCS_B[] = "B";

typedef QHash<QString, QString> FileHash;

template<class T>
class ObjectPoolGuard
{
public:
    ObjectPoolGuard(T *watch) : m_watched(watch)
    {
        ExtensionSystem::PluginManager::addObject(watch);
    }

    operator bool() { return m_watched; }
    bool operator !() { return !m_watched; }
    T &operator*() { return *m_watched; }
    T *operator->() { return m_watched; }
    T *value() { return m_watched; }

    ~ObjectPoolGuard()
    {
        ExtensionSystem::PluginManager::removeObject(m_watched);
        delete m_watched;
    }

private:
    T *m_watched;
};

static FileHash makeHash(const QStringList &list)
{
    FileHash result;
    foreach (const QString &i, list) {
        QStringList parts = i.split(QLatin1Char(':'));
        QTC_ASSERT(parts.count() == 2, continue);
        result.insert(QString::fromLatin1(TEST_PREFIX) + parts.at(0),
                      QString::fromLatin1(TEST_PREFIX) + parts.at(1));
    }
    return result;
}

static QString makeString(const QString &s)
{
    if (s.isEmpty())
        return QString();
    return QString::fromLatin1(TEST_PREFIX) + s;
}

void CorePlugin::testVcsManager_data()
{
    // avoid conflicts with real files and directories:

    QTest::addColumn<QStringList>("dirsVcsA"); // <directory>:<toplevel>
    QTest::addColumn<QStringList>("dirsVcsB"); // <directory>:<toplevel>
    // <directory>:<toplevel>:<vcsid>:<- from cache, * from VCS>
    QTest::addColumn<QStringList>("results");

    QTest::newRow("A and B next to each other")
            << (QStringList()
                << QLatin1String("a:a") << QLatin1String("a/1:a") << QLatin1String("a/2:a")
                << QLatin1String("a/2/5:a") << QLatin1String("a/2/5/6:a"))
            << (QStringList()
                << QLatin1String("b:b") << QLatin1String("b/3:b") << QLatin1String("b/4:b"))
            << (QStringList()
                << QLatin1String(":::-") // empty directory to look up
                << QLatin1String("c:::*") // Neither in A nor B
                << QLatin1String("a:a:A:*") // in A
                << QLatin1String("b:b:B:*") // in B
                << QLatin1String("b/3:b:B:*") // in B
                << QLatin1String("b/4:b:B:*") // in B
                << QLatin1String("a/1:a:A:*") // in A
                << QLatin1String("a/2:a:A:*") // in A
                << QLatin1String(":::-") // empty directory to look up
                << QLatin1String("a/2/5/6:a:A:*") // in A
                << QLatin1String("a/2/5:a:A:-") // in A (cached from before!)
                // repeat: These need to come from the cache now:
                << QLatin1String("c:::-") // Neither in A nor B
                << QLatin1String("a:a:A:-") // in A
                << QLatin1String("b:b:B:-") // in B
                << QLatin1String("b/3:b:B:-") // in B
                << QLatin1String("b/4:b:B:-") // in B
                << QLatin1String("a/1:a:A:-") // in A
                << QLatin1String("a/2:a:A:-") // in A
                << QLatin1String("a/2/5/6:a:A:-") // in A
                << QLatin1String("a/2/5:a:A:-") // in A
                );
    QTest::newRow("B in A")
            << (QStringList()
                << QLatin1String("a:a") << QLatin1String("a/1:a") << QLatin1String("a/2:a")
                << QLatin1String("a/2/5:a") << QLatin1String("a/2/5/6:a"))
            << (QStringList()
                << QLatin1String("a/1/b:a/1/b") << QLatin1String("a/1/b/3:a/1/b")
                << QLatin1String("a/1/b/4:a/1/b") << QLatin1String("a/1/b/3/5:a/1/b")
                << QLatin1String("a/1/b/3/5/6:a/1/b"))
            << (QStringList()
                << QLatin1String("a:a:A:*") // in A
                << QLatin1String("c:::*") // Neither in A nor B
                << QLatin1String("a/3:::*") // Neither in A nor B
                << QLatin1String("a/1/b/x:::*") // Neither in A nor B
                << QLatin1String("a/1/b:a/1/b:B:*") // in B
                << QLatin1String("a/1:a:A:*") // in A
                << QLatin1String("a/1/b/../../2:a:A:*") // in A
                );
    QTest::newRow("A and B") // first one wins...
            << (QStringList() << QLatin1String("a:a") << QLatin1String("a/1:a") << QLatin1String("a/2:a"))
            << (QStringList() << QLatin1String("a:a") << QLatin1String("a/1:a") << QLatin1String("a/2:a"))
            << (QStringList() << QLatin1String("a/2:a:A:*"));
}

void CorePlugin::testVcsManager()
{
    // setup:
    ObjectPoolGuard<TestVersionControl> vcsA(new TestVersionControl(ID_VCS_A, QLatin1String("A")));
    ObjectPoolGuard<TestVersionControl> vcsB(new TestVersionControl(ID_VCS_B, QLatin1String("B")));

    // test:
    QFETCH(QStringList, dirsVcsA);
    QFETCH(QStringList, dirsVcsB);
    QFETCH(QStringList, results);

    vcsA->setManagedDirectories(makeHash(dirsVcsA));
    vcsB->setManagedDirectories(makeHash(dirsVcsB));

    QString realTopLevel = QLatin1String("ABC"); // Make sure this gets cleared if needed.

    // From VCSes:
    int expectedCount = 0;
    foreach (const QString &result, results) {
        // qDebug() << "Expecting:" << result;

632
        QStringList split = result.split(QLatin1Char(':'));
Tobias Hunger's avatar
Tobias Hunger committed
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
        QCOMPARE(split.count(), 4);
        QVERIFY(split.at(3) == QLatin1String("*") || split.at(3) == QLatin1String("-"));


        const QString directory = split.at(0);
        const QString topLevel = split.at(1);
        const QString vcsId = split.at(2);
        bool fromCache = split.at(3) == QLatin1String("-");

        if (!fromCache && !directory.isEmpty())
            ++expectedCount;

        IVersionControl *vcs;
        vcs = VcsManager::findVersionControlForDirectory(makeString(directory), &realTopLevel);
        QCOMPARE(realTopLevel, makeString(topLevel));
        if (vcs)
            QCOMPARE(vcs->id().toString(), vcsId);
        else
            QCOMPARE(QString(), vcsId);
        QCOMPARE(vcsA->dirCount(), expectedCount);
        QCOMPARE(vcsA->fileCount(), 0);
        QCOMPARE(vcsB->dirCount(), expectedCount);
        QCOMPARE(vcsB->fileCount(), 0);
    }

    // teardown:
    // handled by guards
}

} // namespace Internal
} // namespace Core

#endif